def main(args): # parse arguments model_path = args.path save = args.save # ============= LOAD MODEL AND PREPROCESSING CONFIGURATION ================ # load model and info model, info, _ = utils.load_model_HDF5(model_path) # set parameters input_directory = info["data"]["input_directory"] architecture = info["model"]["architecture"] loss = info["model"]["loss"] rescale = info["preprocessing"]["rescale"] shape = info["preprocessing"]["shape"] color_mode = info["preprocessing"]["color_mode"] vmin = info["preprocessing"]["vmin"] vmax = info["preprocessing"]["vmax"] nb_validation_images = info["data"]["nb_validation_images"] # =================== LOAD VALIDATION PARAMETERS ========================= model_dir_name = os.path.basename(str(Path(model_path).parent)) finetune_dir = os.path.join( os.getcwd(), "results", input_directory, architecture, loss, model_dir_name, "finetuning", ) subdirs = os.listdir(finetune_dir) for subdir in subdirs: logger.info("testing with finetuning parameters from \n{}...".format( os.path.join(finetune_dir, subdir))) try: with open( os.path.join(finetune_dir, subdir, "finetuning_result.json"), "r") as read_file: validation_result = json.load(read_file) except FileNotFoundError: logger.warning("run finetune.py before testing.\nexiting script.") sys.exit() min_area = validation_result["best_min_area"] threshold = validation_result["best_threshold"] method = validation_result["method"] dtype = validation_result["dtype"] # ====================== PREPROCESS TEST IMAGES ========================== # get the correct preprocessing function preprocessing_function = get_preprocessing_function(architecture) # initialize preprocessor preprocessor = Preprocessor( input_directory=input_directory, rescale=rescale, shape=shape, color_mode=color_mode, preprocessing_function=preprocessing_function, ) # get test generator nb_test_images = preprocessor.get_total_number_test_images() test_generator = preprocessor.get_test_generator( batch_size=nb_test_images, shuffle=False) # retrieve test images from generator imgs_test_input = test_generator.next()[0] # retrieve test image names filenames = test_generator.filenames # predict on test images imgs_test_pred = model.predict(imgs_test_input) # instantiate TensorImages object tensor_test = postprocessing.TensorImages( imgs_input=imgs_test_input, imgs_pred=imgs_test_pred, vmin=vmin, vmax=vmax, method=method, dtype=dtype, filenames=filenames, ) # ====================== CLASSIFICATION ========================== # retrieve ground truth y_true = get_true_classes(filenames) # predict classes on test images y_pred = predict_classes(resmaps=tensor_test.resmaps, min_area=min_area, threshold=threshold) # confusion matrix tnr, fp, fn, tpr = confusion_matrix(y_true, y_pred, normalize="true").ravel() # initialize dictionary to store test results test_result = { "min_area": min_area, "threshold": threshold, "TPR": tpr, "TNR": tnr, "score": (tpr + tnr) / 2, "method": method, "dtype": dtype, } # ====================== SAVE TEST RESULTS ========================= # create directory to save test results save_dir = os.path.join( os.getcwd(), "results", input_directory, architecture, loss, model_dir_name, "test", subdir, ) if not os.path.isdir(save_dir): os.makedirs(save_dir) # save test result with open(os.path.join(save_dir, "test_result.json"), "w") as json_file: json.dump(test_result, json_file, indent=4, sort_keys=False) # save classification of image files in a .txt file classification = { "filenames": filenames, "predictions": y_pred, "truth": y_true, "accurate_predictions": np.array(y_true) == np.array(y_pred), } df_clf = pd.DataFrame.from_dict(classification) with open(os.path.join(save_dir, "classification.txt"), "w") as f: f.write( "min_area = {}, threshold = {}, method = {}, dtype = {}\n\n". format(min_area, threshold, method, dtype)) f.write(df_clf.to_string(header=True, index=True)) # print classification results to console with pd.option_context("display.max_rows", None, "display.max_columns", None): print(df_clf) # save segmented resmaps if save: save_segmented_images(tensor_test.resmaps, threshold, filenames, save_dir) # print test_results to console print("test results: {}".format(test_result))
def main(args): # get parsed arguments from user input_dir = args.input_dir architecture = args.architecture color_mode = args.color loss = args.loss batch_size = args.batch # check arguments check_arguments(architecture, color_mode, loss) # get autoencoder autoencoder = AutoEncoder(input_dir, architecture, color_mode, loss, batch_size) # load data as generators that yield batches of preprocessed images preprocessor = Preprocessor( input_directory=input_dir, rescale=autoencoder.rescale, shape=autoencoder.shape, color_mode=autoencoder.color_mode, preprocessing_function=autoencoder.preprocessing_function, ) train_generator = preprocessor.get_train_generator( batch_size=autoencoder.batch_size, shuffle=True) validation_generator = preprocessor.get_val_generator( batch_size=autoencoder.batch_size, shuffle=True) # find best learning rates for training autoencoder.find_opt_lr(train_generator, validation_generator) # train autoencoder.fit() # save model autoencoder.save() if args.inspect: # -------------- INSPECTING VALIDATION IMAGES -------------- logger.info("generating inspection plots of validation images...") # create a directory to save inspection plots inspection_val_dir = os.path.join(autoencoder.save_dir, "inspection_val") if not os.path.isdir(inspection_val_dir): os.makedirs(inspection_val_dir) inspection_val_generator = preprocessor.get_val_generator( batch_size=autoencoder.learner.val_data.samples, shuffle=False) imgs_val_input = inspection_val_generator.next()[0] filenames_val = inspection_val_generator.filenames # get reconstructed images (i.e predictions) on validation dataset logger.info("reconstructing validation images...") imgs_val_pred = autoencoder.model.predict(imgs_val_input) # convert to grayscale if RGB if color_mode == "rgb": imgs_val_input = tf.image.rgb_to_grayscale(imgs_val_input).numpy() imgs_val_pred = tf.image.rgb_to_grayscale(imgs_val_pred).numpy() # remove last channel since images are grayscale imgs_val_input = imgs_val_input[:, :, :, 0] imgs_val_pred = imgs_val_pred[:, :, :, 0] # instantiate TensorImages object to compute validation resmaps tensor_val = postprocessing.TensorImages( imgs_input=imgs_val_input, imgs_pred=imgs_val_pred, vmin=autoencoder.vmin, vmax=autoencoder.vmax, method=autoencoder.loss, dtype="float64", filenames=filenames_val, ) # generate and save inspection validation plots tensor_val.generate_inspection_plots(group="validation", save_dir=inspection_val_dir) # -------------- INSPECTING TEST IMAGES -------------- logger.info("generating inspection plots of test images...") # create a directory to save inspection plots inspection_test_dir = os.path.join(autoencoder.save_dir, "inspection_test") if not os.path.isdir(inspection_test_dir): os.makedirs(inspection_test_dir) nb_test_images = preprocessor.get_total_number_test_images() inspection_test_generator = preprocessor.get_test_generator( batch_size=nb_test_images, shuffle=False) imgs_test_input = inspection_test_generator.next()[0] filenames_test = inspection_test_generator.filenames # get reconstructed images (i.e predictions) on validation dataset logger.info("reconstructing test images...") imgs_test_pred = autoencoder.model.predict(imgs_test_input) # convert to grayscale if RGB if color_mode == "rgb": imgs_test_input = tf.image.rgb_to_grayscale( imgs_test_input).numpy() imgs_test_pred = tf.image.rgb_to_grayscale(imgs_test_pred).numpy() # remove last channel since images are grayscale imgs_test_input = imgs_test_input[:, :, :, 0] imgs_test_pred = imgs_test_pred[:, :, :, 0] # instantiate TensorImages object to compute test resmaps tensor_test = postprocessing.TensorImages( imgs_input=imgs_test_input, imgs_pred=imgs_test_pred, vmin=autoencoder.vmin, vmax=autoencoder.vmax, method=autoencoder.loss, dtype="float64", filenames=filenames_test, ) # generate and save inspection test plots tensor_test.generate_inspection_plots(group="test", save_dir=inspection_test_dir) logger.info("done.") return
def inspect_images(model_path): # load model for inspection logger.info("loading model for inspection...") model, info, _ = utils.load_model_HDF5(model_path) save_dir = os.path.dirname(model_path) input_dir = info["data"]["input_directory"] # architecture = info["model"]["architecture"] # loss = info["model"]["loss"] rescale = info["preprocessing"]["rescale"] shape = info["preprocessing"]["shape"] color_mode = info["preprocessing"]["color_mode"] vmin = info["preprocessing"]["vmin"] vmax = info["preprocessing"]["vmax"] nb_validation_images = info["data"]["nb_validation_images"] # instantiate preprocessor object to preprocess validation and test inspection images preprocessor = Preprocessor( input_directory=input_dir, rescale=rescale, shape=shape, color_mode=color_mode, ) # -------------- INSPECTING VALIDATION IMAGES -------------- logger.info("generating inspection plots for validation images...") inspection_val_generator = preprocessor.get_val_generator( batch_size=nb_validation_images, shuffle=False) imgs_val_input = inspection_val_generator.next()[0] filenames_val = inspection_val_generator.filenames # get indices of validation inspection images val_insp_i = [ filenames_val.index(filename) for filename in config.FILENAMES_VAL_INSPECTION ] imgs_val_input = imgs_val_input[val_insp_i] # reconstruct validation inspection images (i.e predict) imgs_val_pred = model.predict(imgs_val_input) # instantiate ResmapPlotter object to compute resmaps postproc_val = postprocessing.ResmapPlotter( imgs_input=imgs_val_input, imgs_pred=imgs_val_pred, filenames=config.FILENAMES_VAL_INSPECTION, color="grayscale", vmin=vmin, vmax=vmax, ) # generate resmaps and save fig_res_val = postproc_val.generate_inspection_figure() fig_res_val.savefig(os.path.join(save_dir, "fig_insp_val.svg")) # -------------- INSPECTING TEST IMAGES -------------- logger.info("generating inspection plots for test images...") nb_test_images = preprocessor.get_total_number_test_images() inspection_test_generator = preprocessor.get_test_generator( batch_size=nb_test_images, shuffle=False) # get preprocessed test images imgs_test_input = inspection_test_generator.next()[0] filenames_test = inspection_test_generator.filenames # get indices of test inspection images test_insp_i = [ filenames_test.index(filename) for filename in config.FILENAMES_TEST_INSPECTION ] imgs_test_input = imgs_test_input[test_insp_i] # reconstruct inspection test images (i.e predict) imgs_test_pred = model.predict(imgs_test_input) # instantiate ResmapPlotter object to compute resmaps postproc_test = postprocessing.ResmapPlotter( imgs_input=imgs_test_input, imgs_pred=imgs_test_pred, filenames=config.FILENAMES_TEST_INSPECTION, color="grayscale", vmin=vmin, vmax=vmax, ) # generate resmaps and save fig_res_test = postproc_test.generate_inspection_figure() fig_res_test.savefig(os.path.join(save_dir, "fig_insp_test.svg")) # -------------------------------------------------- # fig_score_insp = postproc_test.generate_score_scatter_plot( # inspection_test_generator, model_path, filenames_test_insp # ) # fig_score_insp.savefig(os.path.join(save_dir, "fig_score_insp.svg")) # fig_score_test = postproc_test.generate_score_scatter_plot( # inspection_test_generator, model_path # ) # fig_score_test.savefig(os.path.join(save_dir, "fig_score_test.svg")) return