### Progress Indicator Example Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb This output shows a progress bar, typically from a library like `tqdm`, indicating that an operation is running. The '0%' and '?' iterations/second suggest the process has started but is not yet significantly advanced or has completed very quickly. ```text Result: 0%| | 0/3 [00:0020}:' for target_col in tqdm(targets, leave=True): if target_col.startswith('DR Grade'): y_train = dftrain['Retinopathy grade'].values y_test = dftest['Retinopathy grade'].values start = time.time() clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=20_000, random_state=42)) clf.fit(X_train[diab_mask_train], y_train[diab_mask_train]) preds = clf.predict_proba(X_test[diab_mask_test]) stop = time.time() delta = stop - start name_times_dict[name].append(delta) for grade in range(5): curr_median_auc, curr_bootstrap_aucs = get_bootstrap_aucs(y_test[diab_mask_test] == grade, preds[:, grade]) name_bootstrap_aucs_dict[f'{name}-DR Grade {grade}'] = curr_bootstrap_aucs median_aucs.append(curr_median_auc) elif target_col.startswith('No/Mild vs rest'): y_train = dftrain['Retinopathy grade'].apply(lambda x: x > 1).values y_test = dftest['Retinopathy grade'].apply(lambda x: x > 1).values start = time.time() clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=20_000, random_state=42)) clf.fit(X_train[diab_mask_train], y_train[diab_mask_train]) ``` -------------------------------- ### Display Detailed Model Performance Metrics (Output) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_IDRiD.ipynb Presents the evaluation metrics for different models, including DR Grade, Macular Edema, No/Mild vs rest, AnyDR, and AnyDME. The output is formatted to show individual model scores and total processing time. ```output Output: RETFound-MEH:DR Grade:0.8622 Mac. Edema:0.5361 No/Mild vs rest:0.7631 AnyDR:0.7982 AnyDME:0.8313 Total time: 0.3792s / mean time: 0.0758s ``` ```output Output: DERETFound:DR Grade:0.8661 Mac. Edema:0.5709 No/Mild vs rest:0.6566 AnyDR:0.8168 AnyDME:0.9047 Total time: 0.3810s / mean time: 0.0762s ``` ```output Output: RETFound-Green@224:DR Grade:0.8696 Mac. Edema:0.7500 No/Mild vs rest:0.6392 AnyDR:0.7770 AnyDME:0.7857 Total time: 0.4451s / mean time: 0.0890s ``` -------------------------------- ### Custom PyTorch Dataset and DataLoader Setup (Python) Source: https://context7.com/justinengelmann/retfound_green/llms.txt Provides code for setting up custom PyTorch datasets and dataloaders for retinal image analysis. It demonstrates creating an `ImgDataset` from a directory or a list of image paths and configuring an optimized dataloader for efficient batch processing during training or inference. ```python from Training_and_eval_code.data import ImgDataset, get_dataloader, get_default_transforms, get_default_training_transforms from pathlib import Path # Create dataset from directory (recursively finds all .jpg files) img_directory = 'path/to/retinal_images/' inference_transforms = get_default_transforms(res=392) dataset = ImgDataset(img_directory, transform=inference_transforms) print(f"Found {len(dataset)} images") # Create optimized dataloader for batch processing dataloader = get_dataloader( dataset, batch_size=32, num_workers=4, shuffle=False, pin_memory=True, prefetch_factor=2, persistent_workers=True ) # Extract features for entire dataset all_features = [] with torch.inference_mode(): for batch in dataloader: batch = batch.to(device) features = rfg(batch) # Shape: [batch_size, 384] all_features.append(features.cpu()) all_features = torch.cat(all_features, dim=0) print(f"Extracted features for {len(all_features)} images") # Alternative: Create dataset from explicit list of image paths img_paths = list(Path('dataset_folder').rglob('*.jpg')) train_transforms = get_default_training_transforms(res=392) train_dataset = ImgDataset(img_paths, transform=train_transforms) train_loader = get_dataloader(train_dataset, batch_size=128, shuffle=True) ``` -------------------------------- ### Run Experiment with RETFound-Green@224 and DinoV2@224 (Diabetic Only) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET_DR.ipynb This Python code initiates an experiment using `run_brset_exp` to compare 'RETFound-Green@224' and 'DinoV2@224' on diabetic-only data. It defines the input data, model names, and color schemes, alongside parameters for figure size and plot aesthetics. ```python name_X_list = [ ('RETFound-Green@224', 'X_ours_brset_224.npy'), ('DinoV2@224', 'X_original_dinov2_224_brset.npy'), ] models = ['RETFound-Green@224', 'DinoV2@224'] colors = ['#B8FF3D', '#6EA6D1'] run_brset_exp(name_X_list, models, colors, diab_only=True, figsize=(4.5, 4), dashed_line_offsets=(-0.25, 1.5), xtick_loc_scaling=0.5, title_size='medium') ``` -------------------------------- ### Data Loading and Configuration (Python) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/ROP_2dProjections.ipynb This snippet loads training and testing datasets using pandas and defines configurations for feature extraction, target columns, and model-specific colors. It sets up data paths and mappings required for subsequent analysis and visualization. ```python import pandas as pd import numpy as np dftrain = pd.read_csv('/mnt/c/Users/Justin/Desktop/retina_imaging_datasets/ROP_dataset/dftrain.csv') dftest = pd.read_csv('/mnt/c/Users/Justin/Desktop/retina_imaging_datasets/ROP_dataset/dftest.csv') target_col = 'class' dataset = 'Retinopathy of Prematurity (ROP)' name_X_list = [ ('RETFound-MEH', '/home/justin/RETFound_MAE/ROP_Train_RETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/ROP_Test_RETFound_Feature_latent.npy'), ('DERETFound', '/home/justin/RETFound_MAE/ROP_Train_DERETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/ROP_Test_DERETFound_Feature_latent.npy'), ('RETFound-Green', 'ROP_Train_X_ours.npy', 'ROP_Test_X_ours.npy'), ] target_to_colour = { 'Normal': 'gold', 'laser_scars': 'crimson', 'Stage_1_ROP': 'cornflowerblue', 'Stage_2_ROP': 'royalblue', 'Stage_3_ROP': 'navy', } models = ['RETFound-MEH', 'DERETFound', 'RETFound-Green'] colors = ['#ff595e', '#ffca3a', '#8ac926'] # Colors for models ``` -------------------------------- ### Calculate and Format P-values Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb Calculates p-values from AUC scores and formats them into a human-readable string. It uses the Wilcoxon signed-rank test for comparison. Dependencies include numpy and scipy.stats.wilcoxon. ```python import numpy as np from scipy.stats import wilcoxon def get_p_values(all_aucs): all_aucs = np.vstack(all_aucs) median_aucs = np.median(all_aucs, -1) second_best_idx, best_idx = median_aucs.argsort()[-2:] p_val = wilcoxon(all_aucs[best_idx], all_aucs[second_best_idx])[1] return p_val, (best_idx, second_best_idx) def pval_to_str(p_val): if p_val < 0.0001: p_val = 'p<0.0001' p_val = '***' else: p_val = f'p={p_val:.4f}' return p_val ``` -------------------------------- ### Format and Print Performance String Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb This code formats performance metrics (AUC scores) into a tab-separated string and prints it. It also prints the total and mean processing times for a given model. ```python perf_str += '\t'.join([f'{c}:{v:.4f}' for c, v in zip(targets, median_aucs)]) print(perf_str) print(f'Total time: {sum(name_times_dict[name]):.4f}s / mean time: {np.mean(name_times_dict[name]):.4f}s') ``` -------------------------------- ### Calculate and Store Bootstrap AUCs Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb This snippet calculates bootstrap AUCs for model predictions and stores them along with median AUCs. It's used to assess the variability and reliability of model performance. ```python curr_median_auc, curr_bootstrap_aucs = get_bootstrap_aucs(y_test, preds) name_bootstrap_aucs_dict[f'{name}-{target_col}'] = curr_bootstrap_aucs median_aucs.append(curr_median_auc) ``` -------------------------------- ### Load and Prepare Datasets Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/DR_BRESET_IDRiD_2dProjections.ipynb Loads training and testing datasets using pandas and sets up target column and dataset configurations. It also defines lists of model names and corresponding file paths for feature data. ```python dftrain = pd.read_csv('/mnt/e/IDRiD_B_DiseaseGrading/B. Disease Grading/2. Groundtruths/a. IDRiD_Disease Grading_Training Labels.csv') dftest = pd.read_csv('/mnt/e/IDRiD_B_DiseaseGrading/B. Disease Grading/2. Groundtruths/b. IDRiD_Disease Grading_Testing Labels.csv') target_col = 'Retinopathy grade' dataset = 'Diabetic Retinopathy (IDRiD → BRSET) - Points correspond to unseen BRSET dataset' target_cols = list(range(5)) + [-1] name_X_list = [ ('RETFound-MEH', '/home/justin/RETFound_MAE/IRID_Train_RETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/BRSET_RETFound_Feature_latent.npy'), ('DERETFound', '/home/justin/RETFound_MAE/IRID_Train_DERETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/BRSET_DERETFound_Feature_latent.npy'), ('RETFound-Green', 'IRID_Train_X_ours.npy', 'X_ours_brset.npy'), ] dfbr = pd.read_csv('/mnt/c/Users/Justin/Desktop/labels.csv') dfbr['Retinopathy grade'] = dfbr['DR_ICDR'] br_diab_mask = dfbr.diabetes=='yes' dfbr = dfbr[br_diab_mask].copy().reset_index() target_to_colour = { 'Normal': '#5bc0de', # Light blue (neutral/safe) 'Grade 1': '#66c266', # Medium-light green 'Grade 2': '#ffcc00', # Golden yellow 'Grade 3': '#ff6600', # Orange-red 'Grade 4': '#990000', # Dark red 'No/Mild': None, } target_int_to_name = {_: f"Grade {_}" for _ in target_cols} target_int_to_name[0] = 'Normal' target_int_to_name[-1] = 'No/Mild' models = ['RETFound-MEH', 'DERETFound', 'RETFound-Green'] colors = ['#ff595e', '#ffca3a', '#8ac926'] # Colors for models ``` -------------------------------- ### Import Core ML and Data Science Libraries (Python) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET_DR.ipynb Imports essential Python libraries for data analysis and machine learning. This includes pandas for data manipulation, numpy for numerical operations, scikit-learn for ML algorithms and preprocessing, and joblib for saving models. These libraries are fundamental for building and evaluating machine learning models. ```python import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.metrics import roc_auc_score import joblib ``` -------------------------------- ### Convert P-value to String Representation (Python) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_IDRiD.ipynb Formats a given p-value into a human-readable string, indicating significance levels like 'p<0.0001' or '***'. This is useful for presenting statistical test results. ```python def pval_to_str(p_val): if p_val < 0.0001: p_val = 'p<0.0001' p_val = '***' else: p_val = f'p={p_val:.4f}' return p_val ``` -------------------------------- ### Calculate Bootstrap AUCs Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb Calculates Area Under the ROC Curve (AUC) using bootstrapping. It generates multiple AUC scores by resampling with replacement from the true labels and predicted probabilities. Dependencies include numpy and sklearn.metrics.roc_auc_score. ```python import numpy as np from sklearn.metrics import roc_auc_score def get_bootstrap_aucs(y_true, y_pred, bootstrap_iters=100): rng = np.random.RandomState(seed=42) idxs = list(range(y_pred.shape[0])) bootstrap_aucs = [] for _ in range(bootstrap_iters): curr_idxs = rng.choice(idxs, size=len(idxs), replace=True) bootstrap_aucs.append(roc_auc_score(y_true[curr_idxs], y_pred[curr_idxs], multi_class='ovr', average='macro')) return np.median(bootstrap_aucs), bootstrap_aucs ``` -------------------------------- ### Calculate Bootstrap AUC Scores (Python) Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_IDRiD.ipynb Computes bootstrap estimates for Area Under the Receiver Operating Characteristic Curve (AUC) scores. This function helps in assessing the uncertainty and robustness of model performance. ```python def get_bootstrap_aucs(y_true, y_pred, bootstrap_iters=100): rng = np.random.RandomState(seed=42) idxs = list(range(y_pred.shape[0])) bootstrap_aucs = [] for _ in range(bootstrap_iters): curr_idxs = rng.choice(idxs, size=len(idxs), replace=True) bootstrap_aucs.append(roc_auc_score(y_true[curr_idxs], y_pred[curr_idxs], multi_class='ovr', average='macro')) return np.median(bootstrap_aucs), bootstrap_aucs ``` -------------------------------- ### Results DataFrame Snapshot Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET.ipynb This is a partial view of a pandas DataFrame summarizing model performance metrics (AUC scores) for different tasks. It displays rows for 'RETFound-MEH', 'DERETFound', and 'RETFound-Green', showing their scores for 'macula', 'optic_disc', and 'vessels'. ```python Result: Name macula optic_disc vessels \ RETFound-MEH RETFound-MEH 0.8442 0.8487 0.7990 DERETFound DERETFound 0.8551 0.8873 0.7924 RETFound-Green RETFound-Green 0.8922 0.8561 0.8296 diabetic_retinopathy amd macular_edema quality \ ``` -------------------------------- ### Darken Hex Color Code in Python Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET_DR.ipynb Adjusts the brightness of a given hexadecimal color code by a specified factor. This function is useful for creating color variations in visualizations, ensuring the factor is within a valid range. ```python def darken_hex(hex_color, factor=0.5): # Ensure the factor is between 0 and 1 factor = max(0, min(factor, 1)) # Remove the hash symbol if present hex_color = hex_color.lstrip('#') # Convert hex to RGB rgb = tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4)) # Darken the RGB values by multiplying by the factor darkened_rgb = tuple(int(c * factor) for c in rgb) # Convert the RGB values back to hex darkened_hex = '#{:02x}{:02x}{:02x}'.format(*darkened_rgb) return darkened_hex ``` -------------------------------- ### Run ROP Experiment with RETFound-Green@224 and DinoV2@224 Models Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_ROP.ipynb This Python code initializes an experiment comparing 'RETFound-Green@224' and 'DinoV2@224' models. It defines the model names, corresponding data files, and specific colors for plotting. The `run_rop_exp` function is then called to execute the experiment with these settings. ```python name_X_list = [ ('RETFound-Green@224', 'ROP_Train_X_ours224.npy', 'ROP_Test_X_ours224.npy'), ('DinoV2@224', 'ROP_Train_X_dino224.npy', 'ROP_Test_X_dino224.npy'), ] models = ['RETFound-Green@224', 'DinoV2@224'] colors = ['#B8FF3D', '#6EA6D1'] run_rop_exp(name_X_list, models, colors, ``` -------------------------------- ### Retrieve and Format P-values with Python Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_BRSET_DR.ipynb Processes arrays of AUC scores to compute a p-value using the Wilcoxon signed-rank test and formats it into a human-readable string. It identifies the best and second-best performing models based on median AUC. ```python from scipy.stats import wilcoxon import numpy as np def get_p_values(all_aucs): all_aucs = np.vstack(all_aucs) median_aucs = np.median(all_aucs, -1) second_best_idx, best_idx = median_aucs.argsort()[-2:] p_val = wilcoxon(all_aucs[best_idx], all_aucs[second_best_idx])[1] return p_val, (best_idx, second_best_idx) def pval_to_str(p_val): if p_val < 0.0001: p_val = 'p<0.0001' p_val = '***' else: p_val = f'p={p_val:.4f}' return p_val ``` -------------------------------- ### Run ROP Experiment with RETFound-Green and DinoV2 Models Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_ROP.ipynb This code configures and runs an experiment comparing the 'RETFound-Green' and 'DinoV2' models. It defines lists for model names, associated data files, and visualization colors. The `run_rop_exp` function is called to execute the experiment with specified parameters like figure size and line offsets. ```python name_X_list = [ ('RETFound-Green', 'ROP_Train_X_ours.npy', 'ROP_Test_X_ours.npy'), ('DinoV2', 'ROP_Train_X_dino392.npy', 'ROP_Test_X_dino392.npy'), ] models = ['RETFound-Green', 'DinoV2'] colors = ['#8ac926', '#4d759a'] run_rop_exp(name_X_list, models, colors, figsize=(8.5, 4), dashed_line_offsets=(-0.25, 1.5), xtick_loc_scaling=0.5, title_size='medium') ``` -------------------------------- ### Run ROP Experiment with RETFound-MEH, DERETFound, and RETFound-Green@224 Models Source: https://github.com/justinengelmann/retfound_green/blob/main/Training_and_eval_code/evaluation/Eval_ROP.ipynb This Python script sets up and executes a comparative experiment for three models: 'RETFound-MEH', 'DERETFound', and 'RETFound-Green@224'. It specifies the training and testing data file paths and assigns distinct colors for visualization. The `run_rop_exp` function is invoked to process these configurations. ```python name_X_list = [ ('RETFound-MEH', '/home/justin/RETFound_MAE/ROP_Train_RETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/ROP_Test_RETFound_Feature_latent.npy'), ('DERETFound', '/home/justin/RETFound_MAE/ROP_Train_DERETFound_Feature_latent.npy', '/home/justin/RETFound_MAE/ROP_Test_DERETFound_Feature_latent.npy'), ('RETFound-Green@224', 'ROP_Train_X_ours224.npy', 'ROP_Test_X_ours224.npy'), ] models = ['RETFound-MEH', 'DERETFound', 'RETFound-Green@224'] colors = ['#ff595e', '#ffca3a', '#B8FF3D'] run_rop_exp(name_X_list, models, colors) ```