def launch(method, neighbor_by_class: int = 3, store: bool = False): """Launch a classification algorithm. Train on a first dataset, and validate it with a second (and print result) Args: method (object): Class object that have a make_samples function neighbor_by_class (int, optional): Nb nearsest neighbors by class. Defaults to 3. store (bool, optional): True if you want to store the alg result in a folder. Default to False. """ db_train = Database(DB_TRAIN) db_validation = Database(DB_VALIDATION) train_samples = method.make_samples(db_train) validation_samples = method.make_samples(db_validation) if store: # Delete previous result for classe in db_train.get_class(): shutil.rmtree(os.path.join(RESULT_RETRIEVAL, classe), ignore_errors=True) # and re-create directory for classe in db_train.get_class(): os.mkdir(os.path.join(RESULT_RETRIEVAL, classe)) final = {cl: [0, 0] for cl in sorted(db_train.get_class())} for img in validation_samples: selected_class = knn(img, train_samples, neighbor_by_class=neighbor_by_class) # Compare selected class with real class if img['cls'] == selected_class: final[img['cls']][0] += 1 final[img['cls']][1] += 1 # Store image class result if asked if store: # Copy image to result dir i = os.path.basename(img['img']) shutil.copy(img['img'], os.path.join(RESULT_RETRIEVAL, selected_class, i)) # Beautiful print print("\n========= Result =========") col_width = max(len(cl) for cl, v in final.items()) + 2 for cl, v in final.items(): print( f"{cl.ljust(col_width)}: {v[0]}/{v[1]}\t{round(v[0]*100/v[1], 2)} %" )
samples.append({'img': d_img, 'cls': d_cls, 'hist': d_hist}) cPickle.dump(samples, open(os.path.join(cache_dir, sample_cache), "wb")) return samples if __name__ == "__main__": d = Daisy() # Create my samples db = Database("database\\train") print("Train databse created.") samples = d.make_samples(db, sample_name="train") print("Train samples created.") test = Database("database\dev") print("Test databse created.") sample_test = d.make_samples(test, sample_name="dev") print("Test samples created.") # Find class for each image of my test DB and verify the result nb_good_classification = 0 for img_test in sample_test: _, resultes = infer(img_test, samples) real_cls = KNN(resultes, db.get_class()) nb_good_classification += get_cls(img_test['cls']) == get_cls(real_cls) print("\n{}/{}".format(nb_good_classification, len(sample_test)))