Ejemplo n.º 1
0
def main(args):
    # Get validation arguments
    model_path = args.path
    method = args.method
    dtype = args.dtype

    # ============= 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"]

    # get the correct preprocessing function
    preprocessing_function = get_preprocessing_function(architecture)

    # ========= LOAD AND PREPROCESS VALIDATION & FINETUNING IMAGES =============

    # initialize preprocessor
    preprocessor = Preprocessor(
        input_directory=input_directory,
        rescale=rescale,
        shape=shape,
        color_mode=color_mode,
        preprocessing_function=preprocessing_function,
    )

    # -------------------------------------------------------------------

    # get validation generator
    validation_generator = preprocessor.get_val_generator(
        batch_size=nb_validation_images, shuffle=False)

    # retrieve preprocessed validation images from generator
    imgs_val_input = validation_generator.next()[0]

    # retrieve validation image_names
    filenames_val = validation_generator.filenames

    # reconstruct (i.e predict) validation images
    imgs_val_pred = 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 = resmaps.TensorImages(
        imgs_input=imgs_val_input,
        imgs_pred=imgs_val_pred,
        vmin=vmin,
        vmax=vmax,
        method=method,
        dtype=dtype,
        filenames=filenames_val,
    )

    # -------------------------------------------------------------------

    # get finetuning generator
    nb_test_images = preprocessor.get_total_number_test_images()

    finetuning_generator = preprocessor.get_finetuning_generator(
        batch_size=nb_test_images, shuffle=False)

    # retrieve preprocessed test images from generator
    imgs_test_input = finetuning_generator.next()[0]
    filenames_test = finetuning_generator.filenames

    # select a representative subset of test images for finetuning
    #  using stratified sampling
    assert "good" in finetuning_generator.class_indices
    index_array = finetuning_generator.index_array
    classes = finetuning_generator.classes
    _, index_array_ft, _, classes_ft = train_test_split(
        index_array,
        classes,
        test_size=FINETUNE_SPLIT,
        random_state=42,
        stratify=classes,
    )

    # get correct classes corresponding to selected images
    good_class_i = finetuning_generator.class_indices["good"]
    y_ft_true = np.array(
        [0 if class_i == good_class_i else 1 for class_i in classes_ft])

    # select test images for finetuninig
    imgs_ft_input = imgs_test_input[index_array_ft]
    filenames_ft = list(np.array(filenames_test)[index_array_ft])

    # reconstruct (i.e predict) finetuning images
    imgs_ft_pred = model.predict(imgs_ft_input)

    # convert to grayscale if RGB
    if color_mode == "rgb":
        imgs_ft_input = tf.image.rgb_to_grayscale(imgs_ft_input).numpy()
        imgs_ft_pred = tf.image.rgb_to_grayscale(imgs_ft_pred).numpy()

    # remove last channel since images are grayscale
    imgs_ft_input = imgs_ft_input[:, :, :, 0]
    imgs_ft_pred = imgs_ft_pred[:, :, :, 0]

    # instantiate TensorImages object to compute finetuning resmaps
    tensor_ft = resmaps.TensorImages(
        imgs_input=imgs_ft_input,
        imgs_pred=imgs_ft_pred,
        vmin=vmin,
        vmax=vmax,
        method=method,
        dtype=dtype,
        filenames=filenames_ft,
    )

    # ======================== COMPUTE THRESHOLDS ===========================

    # initialize finetuning dictionary
    dict_finetune = {
        "min_area": [],
        "threshold": [],
        "TPR": [],
        "TNR": [],
        "FPR": [],
        "FNR": [],
        "score": [],
    }

    # create discrete min_area values
    min_areas = np.arange(start=5, stop=505, step=STEP_MIN_AREA)
    length = len(min_areas)

    for i, min_area in enumerate(min_areas):
        print("step {}/{} | current min_area = {}".format(
            i + 1, length, min_area))
        # compute threshold corresponding to current min_area
        threshold = determine_threshold(
            resmaps=tensor_val.resmaps,
            min_area=min_area,
            thresh_min=tensor_val.thresh_min,
            thresh_max=tensor_val.thresh_max,
            thresh_step=tensor_val.thresh_step,
        )

        # apply the min_area, threshold pair to finetuning images
        y_ft_pred = predict_classes(resmaps=tensor_ft.resmaps,
                                    min_area=min_area,
                                    threshold=threshold)

        # confusion matrix
        tnr, fpr, fnr, tpr = confusion_matrix(y_ft_true,
                                              y_ft_pred,
                                              normalize="true").ravel()

        # record current results
        dict_finetune["min_area"].append(min_area)
        dict_finetune["threshold"].append(threshold)
        dict_finetune["TPR"].append(tpr)
        dict_finetune["TNR"].append(tnr)
        dict_finetune["FPR"].append(fpr)
        dict_finetune["FNR"].append(fnr)
        dict_finetune["score"].append((tpr + tnr) / 2)

    # get min_area, threshold pair corresponding to best score
    max_score_i = np.argmax(dict_finetune["score"])
    max_score = float(dict_finetune["score"][max_score_i])
    best_min_area = int(dict_finetune["min_area"][max_score_i])
    best_threshold = float(dict_finetune["threshold"][max_score_i])

    # ===================== SAVE VALIDATION RESULTS ========================

    # create a results directory if not existent
    model_dir_name = os.path.basename(str(Path(model_path).parent))

    save_dir = os.path.join(
        os.getcwd(),
        "results",
        input_directory,
        architecture,
        loss,
        model_dir_name,
        "finetuning",
        "{}_{}".format(method, dtype),
    )
    if not os.path.isdir(save_dir):
        os.makedirs(save_dir)

    # save area and threshold pair
    finetuning_result = {
        "best_min_area": best_min_area,
        "best_threshold": best_threshold,
        "best_score": max_score,
        "method": method,
        "dtype": dtype,
        "split": FINETUNE_SPLIT,
    }
    print("finetuning results: {}".format(finetuning_result))

    # save validation result
    with open(os.path.join(save_dir, "finetuning_result.json"),
              "w") as json_file:
        json.dump(finetuning_result, json_file, indent=4, sort_keys=False)
    logger.info("finetuning results saved at {}".format(save_dir))

    # save finetuning plots
    plot_min_area_threshold(dict_finetune,
                            index_best=max_score_i,
                            save_dir=save_dir)
    plot_scores(dict_finetune, index_best=max_score_i, save_dir=save_dir)

    return
Ejemplo n.º 2
0
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))