### Install pyDeepInsight from GitHub Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/README.md Installs the latest development version directly from the GitHub repository. ```bash python3 -m pip install git+https://github.com/alok-ai-lab/pyDeepInsight.git#egg=pyDeepInsight ``` -------------------------------- ### Install pyDeepInsight from PyPI Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/README.md Installs the latest stable release of pyDeepInsight from PyPI using pip. ```bash python3 -m pip install pyDeepInsight ``` -------------------------------- ### Example output from Optuna optimization Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Shows the console output from the Optuna study, including study creation and trial results with loss values and hyperparameters. ```text Output: [I 2024-08-27 00:05:04,839] A new study created in RDB with name: Medelon_Example_Tensor [I 2024-08-27 00:12:28,690] Trial 0 finished with value: 0.6915705800056458 and parameters: {'batch_size': 240, 'lr': 0.0001321596289985998, 'momentum': 0.9041155241443515, 'weight_decay': 2.7660920789512236e-08}. Best is trial 0 with value: 0.6915705800056458. ``` -------------------------------- ### Import Libraries for DeepFeature CAM-based Feature Selection Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Imports necessary libraries including pyDeepInsight, pandas, numpy, sklearn, umap, torch, timm, and IPython display utilities. This is the setup for the entire example. ```python from pyDeepInsight import ImageTransformer, CAMFeatureSelector import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, LabelEncoder import umap.umap_ as umap import torch import torchvision.transforms as transforms import timm from torch.utils.data import TensorDataset, DataLoader import torch.nn as nn import torch.optim as optim from sklearn.metrics import accuracy_score from IPython.display import display, clear_output ``` -------------------------------- ### Optuna Study Output Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Example output from the Optuna study showing study creation and trial results. ```text Output: [I 2024-08-21 00:19:08,877] A new study created in RDB with name: Medelon_Example [I 2024-08-21 00:22:26,204] Trial 0 finished with value: 0.6918920278549194 and parameters: {'batch_size': 16, 'lr': 0.0006310268345248904, 'momentum': 0.8135201709890142, 'weight_decay': 0.0002463873146422607}. Best is trial 0 with value: 0.6918920278549194. ``` -------------------------------- ### Create dataset with 50% features (features < pixels) Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Sets the feature-to-pixel ratio to 0.5 and creates a dataset using the create_dataset function. This simulates a common setup for CNN inputs where image size exceeds feature count. ```python p_features = 0.5 it, X = create_dataset(img_size, p_features) ``` -------------------------------- ### Set flatten_method='mean' for threshold tuning Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Sets the flattening method to 'mean' before tuning the activation threshold. This is a prerequisite step for the subsequent threshold examples. ```python fl_method = 'mean' class_cam = camfs.calculate_class_activations(X_train_tensor, y_train_tensor, batch_size=100, flatten_method=fl_method) ``` -------------------------------- ### Get sample mappings for all RNASeq2GeneNorm data Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/data/README.md Combines sampleMap data from all disease codes into a single tibble, adding a cancer column. ```R samples <- purrr::map(dcodes, ~as_tibble(sampleMap(mae_all[[.x]])) %>% mutate(cancer=.x)) %>% bind_rows() %>% glimpse() ``` -------------------------------- ### Load and split TCGA data Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Loads example TCGA gene expression data from a gzipped tab-separated file, extracts the cancer type labels and feature matrix, and splits into training and testing sets with stratification. ```python expr_file = r"./data/curatedTCGAData_RNASeq2GeneNorm-20160128.txt.gz" expr = pd.read_csv(expr_file, sep="\t") y = expr['cancer'].values X = expr.iloc[:, 2:].values X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, stratify=y) ``` -------------------------------- ### Import required libraries for pyDeepInsight tutorial Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Imports ImageTransformer, numpy, copy, PCA, dataset generators, distance function, and plotting libraries needed for the tutorial. ```python from pyDeepInsight import ImageTransformer import numpy as np import copy from sklearn.decomposition import PCA from sklearn.datasets import make_classification, make_blobs from scipy.spatial.distance import euclidean import matplotlib.pyplot as plt import seaborn as sns ``` -------------------------------- ### Import PyTorch, Lightning, and Optuna Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Imports PyTorch modules, sets float32 matmul precision to 'medium', and imports datasets, timm, cv2, Lightning, callbacks, and Optuna for model training and hyperparameter tuning. ```python import torch from torch import nn, optim torch.set_float32_matmul_precision('medium') import datasets import timm import cv2 import lightning as L from lightning.pytorch.callbacks import ModelCheckpoint from lightning.pytorch.callbacks.early_stopping import EarlyStopping import optuna ``` -------------------------------- ### Run Optuna Optimization with Logging Filters Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Sets up and runs an Optuna study with 25 trials, using a SQLite storage. Filters out specific warning and logging messages to reduce output during the run. ```python n_trials = 25 storage_name = f"sqlite:///{work_path}/saved_studies.db" study_name = f"Medelon_Example" import warnings import logging logging.getLogger("lightning.pytorch.utilities.rank_zero").setLevel(logging.WARNING) logging.getLogger("lightning.pytorch.accelerators.cuda").setLevel(logging.WARNING) with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Checkpoint directory") warnings.filterwarnings("ignore", message="Applied workaround for CuDNN issue") study = optuna.create_study(direction="minimize", study_name=study_name, storage=storage_name) train_dataset = torch.utils.data.TensorDataset(train_input, train_target[:, None]) val_dataset = torch.utils.data.TensorDataset(val_input, val_target[:, None]) objective_ds = lambda trial: optobj(trial, train_dataset, val_dataset) study.optimize(objective_ds, n_trials=n_trials, gc_after_trial=True) ``` -------------------------------- ### Get all disease codes available for TCGA Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/data/README.md Retrieves disease codes from the diseaseCodes dataset where Available is 'Yes' and extracts the Study.Abbreviation column. ```R data(diseaseCodes) dcodes <- diseaseCodes %>% dplyr::filter(Available == 'Yes') %>% pull(Study.Abbreviation) %>% glimpse() ``` -------------------------------- ### Prepare data loaders for training and testing Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Transforms images to tensors, creates TensorDatasets, and wraps them in DataLoaders with a batch size of 50. The normalization step is commented out. ```python batch_size=50 preprocess = transforms.Compose([ transforms.ToTensor(), #transforms.Normalize(mean=net.default_cfg['mean'], std=net.default_cfg['std']), ]) X_train_tensor = torch.stack([preprocess(img) for img in X_train_img]).float().to(device) y_train_tensor = torch.from_numpy(y_train_enc).to(device) trainset = TensorDataset(X_train_tensor, y_train_tensor) trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True) X_test_tensor = torch.stack([preprocess(img) for img in X_test_img]).float().to(device) y_test_tensor = torch.from_numpy(y_test_enc).to(device) testset = TensorDataset(X_test_tensor, y_test_tensor) testloader = DataLoader(testset, batch_size=batch_size, shuffle=False) ``` -------------------------------- ### Run Optuna optimization with logging filters Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Sets up and runs an Optuna study with 25 trials, using a SQLite storage. It filters warning and logging messages to reduce output, creates TensorDatasets from input/target tensors, and optimizes the objective function. ```python n_trials = 25 storage_name = f"sqlite:///{work_path}/saved_studies.db" study_name = f"Medelon_Example_Tensor" import warnings import logging logging.getLogger("lightning.pytorch.utilities.rank_zero").setLevel(logging.WARNING) logging.getLogger("lightning.pytorch.accelerators.cuda").setLevel(logging.WARNING) with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Checkpoint directory") warnings.filterwarnings("ignore", message="Applied workaround for CuDNN issue") study = optuna.create_study(direction="minimize", study_name=study_name, storage=storage_name) train_dataset = torch.utils.data.TensorDataset(train_input, train_target[:, None]) val_dataset = torch.utils.data.TensorDataset(val_input, val_target[:, None]) objective_ds = lambda trial: optobj(trial, train_dataset, val_dataset) study.optimize(objective_ds, n_trials=n_trials, gc_after_trial=True) ``` -------------------------------- ### Import PyTorch and evaluation modules Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Imports PyTorch, torchvision, and scikit-learn metrics for building and evaluating the model. ```python import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import TensorDataset, DataLoader import torch.nn as nn import torch.optim as optim from sklearn.metrics import accuracy_score, ConfusionMatrixDisplay import warnings; warnings.simplefilter('ignore') ``` -------------------------------- ### Import pyDeepInsight modules Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Imports MRepImageTransformer and utility functions StepBlur2d and GaborFilter2d from pyDeepInsight. ```python from pyDeepInsight import MRepImageTransformer from pyDeepInsight.utils import StepBlur2d, GaborFilter2d ``` -------------------------------- ### Import MRep-DeepInsight modules Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Imports MRepImageTransformer and utility functions step_blur and imgaborfilt from pyDeepInsight. ```python from pyDeepInsight import MRepImageTransformer from pyDeepInsight.utils import step_blur, imgaborfilt ``` -------------------------------- ### Create dataset with equal features and pixels Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Sets the feature-to-pixel ratio to 1.0 and creates a dataset where the number of features equals the number of pixels. ```python p_features = 1. it, X = create_dataset(img_size, p_features) ``` -------------------------------- ### Load best model and generate predictions with PyTorch Lightning Trainer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Initializes a Lightning Trainer for prediction, loads the best model from an Optuna study, creates final data loaders for train/validation/test sets, and generates predictions using the trainer's predict method with the best checkpoint path. ```python # Initialize simple trainer for prediciton ftrainer = L.Trainer( accelerator="gpu", enable_checkpointing=True, enable_progress_bar=True, enable_model_summary=False, logger=False ) # Load best model from best trial hp = study.best_trial.params fmodel = model = timm.create_model('resnet50', pretrained=True, num_classes=1) foptimizer = optim.SGD(model.parameters(), lr=hp['lr'], momentum=hp['momentum'], weight_decay=hp['weight_decay']) flitmodel = LitResNet(fmodel, foptimizer) best_model_path = study.best_trial.user_attrs['best_model_path'] # Create final data loaders train_dataset = torch.utils.data.TensorDataset(train_input.to(torch.float32), train_target[:, None]) final_train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=False, num_workers=num_workers, pin_memory=pin_memory, persistent_workers=persistent_workers) val_dataset = torch.utils.data.TensorDataset(val_input.to(torch.float32), val_target[:, None]) final_val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=64, shuffle=False, num_workers=num_workers, pin_memory=pin_memory, persistent_workers=persistent_workers) test_dataset = torch.utils.data.TensorDataset(test_input.to(torch.float32), test_target[:, None]) final_test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=num_workers, pin_memory=pin_memory, persistent_workers=persistent_workers) # Generate predictions train_pred = torch.vstack(ftrainer.predict(flitmodel, dataloaders=final_train_loader, ckpt_path=best_model_path)) val_pred = torch.vstack(ftrainer.predict(flitmodel, dataloaders=final_val_loader, ckpt_path=best_model_path)) test_pred = torch.vstack(ftrainer.predict(flitmodel, dataloaders=final_test_loader, ckpt_path=best_model_path)) ``` -------------------------------- ### Plot training sample images Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Displays the first three training images with their class labels as titles. ```python fig, ax = plt.subplots(1, 3, figsize=(15, 5)) for i in range(0,3): ax[i].imshow(X_train_img[i]) ax[i].title.set_text(f"Train[{i}] - class '{y_train[i]}'") plt.tight_layout() ``` -------------------------------- ### Create ResNet26d model with timm Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Creates a pretrained ResNet26d model with a custom number of classes and moves it to the selected device. ```python net = timm.create_model('resnet26d', pretrained=True, num_classes=num_classes).to(device) net = net.to(device) ``` -------------------------------- ### TensorFlow Startup Output Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Output from running the import cell, showing TensorFlow and XLA warnings about cuDNN, cuFFT, cuBLAS registration, CPU feature guard, and TensorRT. This is the expected output when running the imports. ```text Output: 2024-04-11 08:33:13.384900: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-04-11 08:33:13.384974: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-04-11 08:33:13.386064: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered 2024-04-11 08:33:13.392443: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. 2024-04-11 08:33:14.194478: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT ``` -------------------------------- ### Prepare training input tensors Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Converts raw, Gabor, and blur images to tensors, concatenates them, and creates target tensors by tiling sample indices. ```python train_raw_input = pil_to_tensor(train_raw_img) train_gabor_input = pil_to_tensor(train_gabor_img) train_blur_input = pil_to_tensor(train_blur_img) train_input = torch.concat([train_raw_input, train_gabor_input, train_blur_input]).to(torch.float32) train_target_idx = np.tile(train_sample_idx, 3) train_target = torch.tensor(train_y[train_target_idx], dtype=torch.float32) ``` -------------------------------- ### Configure UMAP reducer and ImageTransformer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Sets up a UMAP reducer with cosine metric and 2 components, and an ImageTransformer with 224x224 pixel output. ```python reducer = umap.UMAP( n_components=2, #min_dist=0.8, metric='cosine', n_jobs=-1 ) pixel_size = (224,224) it = ImageTransformer( feature_extractor=reducer, pixels=pixel_size) ``` -------------------------------- ### Define loss function and optimizer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Sets up the cross-entropy loss and AdamW optimizer with a learning rate of 1e-04 and weight decay of 1e-05. The momentum parameter is commented out. ```python criterion = nn.CrossEntropyLoss() optimizer = optim.AdamW( model.parameters(), lr=1e-04, #momentum=0.8, weight_decay=1e-05 ) ``` -------------------------------- ### Combining flatten_method='min' and threshold=0.3 Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Combines the 'min' flattening method with a low threshold to select a specific set of features. The code calculates class activations, selects features, and displays the CAM image. ```python fl_method = 'min' fs_threshold = 0.3 class_cam = camfs.calculate_class_activations(X_train_tensor, y_train_tensor, batch_size=100, flatten_method=fl_method) feat_idx = camfs.select_class_features(cams=class_cam, threshold=fs_threshold) fig, _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) fig.suptitle(f"flatten_method='{fl_method}', theshold={fs_threshold}") plt.show() ``` ```text Result:
``` -------------------------------- ### Prepare test input tensors Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Converts raw, Gabor, and blur images to tensors, concatenates them, and creates target tensors by tiling sample indices. ```python test_raw_input = pil_to_tensor(test_raw_img) test_gabor_input = pil_to_tensor(test_gabor_img) test_blur_input = pil_to_tensor(test_blur_img) test_input = torch.concat([test_raw_input, test_gabor_input, test_blur_input]).to(torch.float32) test_target_idx = np.tile(test_sample_idx, 3) test_target = torch.tensor(test_y[test_target_idx], dtype=torch.float32) ``` -------------------------------- ### Load required R libraries Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/data/README.md Loads tidyverse, MultiAssayExperiment, curatedTCGAData, TCGAutils, and caret for data manipulation and analysis. ```R suppressMessages({ library('tidyverse') library('MultiAssayExperiment') library('curatedTCGAData') library('TCGAutils') library('caret') }) ``` -------------------------------- ### Import scikit-learn and manifold libraries Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Imports MinMaxScaler, train_test_split, metrics, TSNE, and UMAP for preprocessing, evaluation, and dimensionality reduction. ```python from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.manifold import TSNE from umap import UMAP ``` -------------------------------- ### Train SqueezeNet for 100 epochs Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Trains the model for 100 epochs, printing the running loss every 20 epochs and after the final epoch. The loss is normalized by the number of training samples. ```python model.train() model.to(device) for epoch in range(100): running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item() # print epoch statistics if not (epoch % 20): print(f'[{epoch}] loss: {running_loss / len(X_train_tensor) * batch_size:.3f}') print(f'[{epoch}] loss: {running_loss / len(X_train_tensor) * batch_size:.3f}') ``` -------------------------------- ### Configure t-SNE reducer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Sets up a t-SNE reducer with cosine distance metric for feature extraction. ```python distance_metric = 'cosine' reducer = TSNE( n_components=2, metric=distance_metric, init='random', learning_rate='auto', n_jobs=-1 ) ``` -------------------------------- ### Define a PyTorch Lightning module for training Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Defines a LightningModule class (LitResNet) that wraps a neural network and optimizer, using BCEWithLogitsLoss. It implements forward, configure_optimizers, training_step, validation_step, and predict_step methods, enabling use with Lightning's Trainer for early stopping and checkpointing. ```python class LitResNet(L.LightningModule): def __init__(self, net, optimizer): super().__init__() self.net = net self.optimizer = optimizer self.criterion = nn.BCEWithLogitsLoss() def forward(self, X): return self.net(X) def configure_optimizers(self): return self.optimizer def training_step(self, batch, batch_idx): X, y = batch y_hat = self.net(X) loss = self.criterion(y_hat, y) return loss def validation_step(self, batch, batch_idx): X, y = batch y_hat = self.net(X) loss = self.criterion(y_hat, y) self.log("val_loss", loss, on_step=False, on_epoch=True, prog_bar=True) def predict_step(self, batch, batch_idx): X, y = batch y_hat = self.net(X) return y_hat ``` -------------------------------- ### Set device for PyTorch Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Selects CUDA if available, otherwise CPU, and displays the chosen device. ```python device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device ``` -------------------------------- ### Plot testing sample images Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Transforms the testing data and displays the first three testing images with their class labels. ```python X_test_img = it.transform(X_test_norm) fig, ax = plt.subplots(1, 3, figsize=(15, 5)) for i in range(0,3): ax[i].imshow(X_test_img[i]) ax[i].title.set_text(f"Test[{i}] - class '{y_test[i]}'") plt.tight_layout() ``` -------------------------------- ### Import required libraries for DeepInsight and PyTorch Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Imports necessary modules from pyDeepInsight, scikit-learn, pandas, and numpy for data processing and model training. ```python from pyDeepInsight import ImageTransformer from pyDeepInsight.utils import Norm2Scaler from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.manifold import TSNE import pandas as pd import numpy as np ``` -------------------------------- ### Prepare validation input tensors Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Converts raw, Gabor, and blur images to tensors, concatenates them, and creates target tensors by tiling sample indices. ```python val_raw_input = pil_to_tensor(val_raw_img) val_gabor_input = pil_to_tensor(val_gabor_img) val_blur_input = pil_to_tensor(val_blur_img) val_input = torch.concat([val_raw_input, val_gabor_input, val_blur_input]).to(torch.float32) val_target_idx = np.tile(val_sample_idx, 3) val_target = torch.tensor(val_y[val_target_idx], dtype=torch.float32) ``` -------------------------------- ### Import core data science libraries Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Imports NumPy, pandas, and matplotlib for data manipulation and visualization. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` -------------------------------- ### Check CUDA availability and versions Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Checks if CUDA is available and prints the PyTorch and CUDA versions. ```python torch.cuda.is_available(), torch.__version__, torch.version.cuda ``` -------------------------------- ### Training loss output Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Shows the training loss values printed at epochs 0, 20, 40, 60, 80, and 99, indicating the model's convergence. ```text Output: [0] loss: 2.203 [20] loss: 0.091 [40] loss: 0.030 [60] loss: 0.010 [80] loss: 0.016 [99] loss: 0.001 ``` -------------------------------- ### Create PyTorch datasets and dataloaders Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Generates TensorDataset and DataLoader objects for training and testing with a batch size of 200. ```python batch_size = 200 trainset = TensorDataset(X_train_tensor, y_train_tensor) trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True) testset = TensorDataset(X_test_tensor, y_test_tensor) testloader = DataLoader(testset, batch_size=batch_size, shuffle=False) ``` -------------------------------- ### Download and split Madelon dataset Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Downloads the Madelon dataset from HuggingFace, splits the train set into train and validation, and uses the original validation set as the test set. ```python trainval_df = pd.DataFrame(datasets.load_dataset("mstz/madelon", split="train")) train_df, val_df = train_test_split(trainval_df, test_size=600, random_state=452, stratify=trainval_df.iloc[:,-1]) test_df = pd.DataFrame(datasets.load_dataset("mstz/madelon", split="validation")) train_df.shape, val_df.shape, test_df.shape ``` -------------------------------- ### Set device for CNN training Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Selects CUDA if available, otherwise uses CPU for model training. ```python device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') ``` -------------------------------- ### Convert images to tensors and encode labels Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Stacks the preprocessed images into tensors and encodes the labels for both training and testing sets. ```python X_train_tensor = torch.stack([preprocess(img) for img in X_train_img]).float() y_train_tensor = torch.from_numpy(le.fit_transform(y_train)) X_test_tensor = torch.stack([preprocess(img) for img in X_test_img]).float() y_test_tensor = torch.from_numpy(le.transform(y_test)) ``` -------------------------------- ### Plot discretization comparison for features < pixels Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Generates a comparison plot of discretization methods for the features < pixels scenario. The output is a figure with 6 axes. ```python desc_comparison_plot(it, X) ``` -------------------------------- ### Create synthetic dataset and ImageTransformer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Defines a function to create a synthetic dataset using make_blobs and initializes an ImageTransformer with PCA and 'bin' discretization. The dataset is min-max scaled to [0,1]. ```python def create_dataset(pixels, p_features): """Create a synthetic dataset and initialize an ImageTransformer for feature reduction.""" it = ImageTransformer( #feature_extractor=KernelPCA(n_components=2, kernel='rbf', gamma=0.001), feature_extractor=PCA(n_components=2), pixels=pixels, discretization='bin') n_features = int(np.prod(pixels)*p_features) X, y = make_blobs(n_samples=1000, n_features=n_features, centers=int(n_features*0.2), random_state=42) # MinMaxScale X = (X - X.min())/(X.max() - X.min()) return it, X ``` -------------------------------- ### Switch model to CPU and eval mode Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Moves the model to CPU and sets it to evaluation mode, which is necessary before making predictions. ```python model.to('cpu') model = model.eval() ``` -------------------------------- ### Plot sample images with filters Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Creates a 2x3 grid of subplots showing sample images from the t-SNE and UMAP transformations with no filter, Gabor filter, and blur filter. ```python fig, ax = plt.subplots(2, 3, figsize=(9,6)) fig.suptitle(f'Sample #0') ax[0,0].set_ylabel('t-SNE', size='large') ax[0,0].set_title('No Filter') ax[0,0].imshow(train_raw_img[0].permute(1, 2, 0)) ax[0,1].set_title('Gabor Filter') ax[0,1].imshow(train_gabor_img[0].permute(1, 2, 0)) ax[0,2].set_title('Blur Filter') ax[0,2].imshow(train_blur_img[0].permute(1, 2, 0)) ax[1,0].set_ylabel('UMAP', size='large') ax[1,0].imshow(train_raw_img[1400].permute(1, 2, 0)) ax[1,1].imshow(train_gabor_img[1400].permute(1, 2, 0)) ax[1,2].imshow(train_blur_img[1400].permute(1, 2, 0)) plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]); plt.subplots_adjust(wspace=0.01, hspace=0.01) ``` ```text Result:
``` -------------------------------- ### Define loss function and optimizer Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Uses cross-entropy loss and SGD optimizer with learning rate 0.01 and momentum 0.9. ```python criterion = nn.CrossEntropyLoss() optimizer = optim.SGD( net.parameters(), lr=1e-02, momentum=0.9, ) ``` -------------------------------- ### Display expression dataframe with limited rows and columns Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/data/README.md Sets display options to show only 10 rows and 15 columns for the exp_df dataframe. ```R options(repr.matrix.max.rows=10, repr.matrix.max.cols=15) exp_df ``` -------------------------------- ### Create CAMFeatureSelector object Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Initializes the CAMFeatureSelector with a trained CNN model and the ImageTransformer object. The cam_method parameter defaults to 'GradCAM' and can be changed to other methods from the grad-cam package. The target_layer parameter is optional; if not provided, an appropriate layer is chosen automatically using torchcam. ```python cm_method='GradCAM' camfs = CAMFeatureSelector( model=net, it=it, cam_method=cm_method ) ``` -------------------------------- ### CAMFeatureSelector Class Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/README.md Documentation for the CAMFeatureSelector class, including its constructor parameters and its two methods for calculating class activations and selecting class features. ```APIDOC ## CAMFeatureSelector Class ### Description Extracts important features from a trained PyTorch model using class activation mapping (CAM) as proposed in DeepFeature: feature selection in nonimage data using convolutional neural network. See the TCGA feature selection notebook for a detailed usage example. ### Constructor `DeepInsight.CAMFeatureSelector(model, it, target_layer, cam_method="GradCAM")` ### Parameters - **model** (pytorch.nn.Module) - Required - The CNN model should be trained on the output from an ImageTransformer instance. The torchvision.models subpackage provides many common CNN architectures. - **it** (ImageTransformer) - Required - The ImageTransformer instance used to generate the images on which the model was trained. - **target_layer** (str or pytorch.nn.Module) - Required - The target layer of the model on which the CAM is computed. Can be specified using the name provided by nn.Module.named_modules or by providing a pointer to the layer directly. If no layer is specified, the last non-reduced convolutional layer is selected as determined by the 'locate_candidate_layer' method of the TorchCAM package. - **cam_method** (str) - Optional - The name of a CAM method class provided by the pytorch_grad_cam package. Default is "GradCAM". ### Methods #### calculate_class_activations ##### Description Calculate CAM for each input then flatten for each class. ##### Signature `calculate_class_activations(X, y, batch_size=1, flatten_method='mean')` ##### Parameters - **X** - Required - Input data. - **y** - Required - Target labels. - **batch_size** (int) - Optional - Batch size for processing. Default is 1. - **flatten_method** (str) - Optional - Method to flatten CAMs. Default is 'mean'. #### select_class_features ##### Description Select features for each class using class-specific CAMs. Input feature coordinates are filtered based on activation at same coordinates. ##### Signature `select_class_features(cams, threshold=0.6)` ##### Parameters - **cams** - Required - Class activation maps. - **threshold** (float) - Optional - Threshold for feature selection. Default is 0.6. ``` -------------------------------- ### Train the CNN for 20 epochs Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Trains the model for 20 epochs, clearing output and displaying progress per batch. The final displayed result is 'Epoch 019, batch 072'. ```python net.train() for epoch in range(20): for i, (inputs, labels) in enumerate(trainloader): clear_output(wait=True) display(f"Epoch {epoch:03d}, batch {i:03d}") optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() ``` ```text Result: 'Epoch 019, batch 072' ``` -------------------------------- ### Set data loading parameters Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Sets the number of workers, pin_memory flag, persistent_workers flag, and the working path for data. ```python num_workers=32 pin_memory=False persistent_workers=True work_path = './data' ``` -------------------------------- ### Generate image transformers and measure discretization timings Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Defines functions to create ImageTransformer objects for varying pixel dimensions, measure time for changing discretization methods with timeout handling, and collect timing data across methods and pixel sizes. Includes plotting of timing results. ```python from concurrent.futures import ProcessPoolExecutor import multiprocessing as mp import time import pandas as pd import random from tqdm.notebook import tqdm def generate_image_transformers(p_features): """Generate a dictionary of ImageTransformer objects for varying pixel dimensions.""" its = {} for pixels in list(range(16, 224+1, 16)): it, X = create_dataset((pixels, pixels), p_features) _ = it.fit(X) it._fe = None its[pixels] = copy.deepcopy(it) return its def measure_time_discretization(it, method): """Measure the time taken to update the discretization method.""" start_time = time.time() change_discretization(it, method) return time.time() - start_time def time_discretization_with_pool(it, method, timeout=60): """Measure the time to apply a discretization method with a timeout constraint.""" with mp.Pool(1) as pool: async_result = pool.apply_async(measure_time_discretization, (it, method)) try: return async_result.get(timeout) except: return -1 def measure_time_with_timeout(task): """Execute and measure the time taken for a discretization task with timeout handling.""" method, pixels, it, timeout = task return (method, pixels, time_discretization_with_pool(it, method, timeout)) def get_timings(it_map, disc_methods, timeout=10, num_repeats=5): """Measure and collect timing data for various discretization methods across pixel sizes.""" combinations = [(method, pixels) for pixels in it_map.keys() for method in disc_methods] * num_repeats tasks = [(method, pixels, it_map[pixels], timeout) for method, pixels in combinations] random.shuffle(tasks) timings = [] with ProcessPoolExecutor(max_workers=5) as executor: for method, pixels, timing in tqdm(executor.map(measure_time_with_timeout, tasks), total=len(tasks)): timings.append((method, pixels, timing)) return pd.DataFrame([{'method': method, 'pixels': pixels, 'timing': timing} for method, pixels, timing in timings]) def plot_timings(timings): """Plot the timing results of discretization methods for different pixel sizes.""" timings = timings[timings.timing > 0].groupby(['method', 'pixels']).mean().reset_index() fig, axs = plt.subplots(1,2, figsize=(10, 3), sharex=True, layout='constrained') sns.lineplot(data=timings, x='pixels', y='timing', hue='method', marker='o', ax=axs[0], legend=False) sns.lineplot(data=timings, x='pixels', y='timing', hue='method', marker='o', ax=axs[1]) axs[1].set_yscale("log") axs[1].set_ylabel(None) handles, labels = axs[1].get_legend_handles_labels() axs[1].get_legend().remove() fig.legend(handles, labels, loc='center', bbox_to_anchor=(0.5, 1.05), ncol=len(labels), frameon=False) ``` ```python disc_methods = ['bin', 'qtb', 'lsa', 'sla', 'ags'] img_size = (16, 16) ``` -------------------------------- ### Feature selection with threshold=0.3 Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb A lower threshold selects more features. The code selects features using the threshold and displays the CAM image. ```python fs_threshold=0.3 feat_idx = camfs.select_class_features(cams=class_cam, threshold=fs_threshold) fig, _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) fig.suptitle(f"threshold={fs_threshold}") plt.show() ``` ```text Result:
``` -------------------------------- ### Convert between torch and PIL image formats Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon.ipynb Functions to convert between torch image format (N, C, H, W) and PIL image format (N, H, W, C). ```python def pil_to_tensor(img): return torch.from_numpy(img.transpose(0, 3, 1, 2)) def tensor_to_pil(img): return img.detach().cpu().permute(0, 2, 3, 1).numpy() ``` -------------------------------- ### CAM flattening with flatten_method='min' Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Selects features that pass the threshold in all members of the class (intersection). This results in fewer features with a stronger relationship to class prediction. The code calculates class activations, selects features, and displays the CAM image. ```python fl_method = 'min' class_cam = camfs.calculate_class_activations(X_train_tensor, y_train_tensor, batch_size=100, flatten_method=fl_method) feat_idx = camfs.select_class_features(cams=class_cam, threshold=fs_threshold) fig, _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) fig.suptitle(f"flatten_method='{fl_method}'") plt.show() ``` ```text Result:
``` -------------------------------- ### Time discretization methods for features < pixels Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Measures runtime of each discretization method with a one-hour timeout and three repeats. The progress bar shows 0/210 iterations. ```python timeout = 60 * 60 num_repeats = 3 timings = get_timings(its, disc_methods, timeout=timeout, num_repeats=num_repeats) ``` -------------------------------- ### CAM flattening with flatten_method='max' Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Selects features that pass the threshold in any member of the class (union). This results in more features with a broader relationship to class prediction. The code calculates class activations, selects features, and displays the CAM image. ```python fl_method = 'max' class_cam = camfs.calculate_class_activations(X_train_tensor, y_train_tensor, batch_size=100, flatten_method=fl_method) feat_idx = camfs.select_class_features(cams=class_cam, threshold=fs_threshold) fig, _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) fig.suptitle(f"flatten_method='{fl_method}'") plt.show() ``` ```text Result:
``` -------------------------------- ### Create ImageTransformer with pixel size Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Initializes the ImageTransformer with the t-SNE reducer and a pixel size of 227x227. ```python pixel_size = (227,227) it = ImageTransformer( feature_extractor=reducer, pixels=pixel_size) ``` -------------------------------- ### Time discretization methods for features = pixels Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Measures runtime of each discretization method with the same timeout and repeats as before. The progress bar shows 0/210 iterations. ```python timings = get_timings(its, disc_methods, timeout=timeout, num_repeats=num_repeats) ``` -------------------------------- ### Suppress FutureWarnings Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Ignores FutureWarnings to keep the output clean during the tutorial. ```python import warnings warnings.simplefilter(action='ignore', category=FutureWarning) ``` -------------------------------- ### Fit MRepImageTransformer and plot results Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Fits the MRepImageTransformer on the training data and plots the resulting manifold transformations. The output shows two figures of size 640x480 with 1 Axes each. ```python _ = mit.fit(train_x, plot=True) ``` ```text Result:
``` ```text Result:
``` -------------------------------- ### Generate comparison plot of discretization methods Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/discretization_methods.ipynb Defines a function that fits the ImageTransformer and creates a 2x3 grid of plots showing the reduced feature space and assignments for each discretization method in the global 'disc_methods' list. ```python def desc_comparison_plot(it, X): """Generate a comparison plot of different discretization methods.""" fig, axs = plt.subplots(2, 3, figsize=(10, 7), layout='constrained') plt.sca(axs[0,0]) _ = it.fit(X, plot=True) it._fe = None axs[0,0].set_title("Reduced Feature Space\nw/ Bounding Rectangle") for i, disc_method in enumerate(disc_methods): ax = axs.flat[i+1] try: plot_assignment(change_discretization(it, disc_method), ax, disc_method) except: pass for ax in axs.flat: _ = ax.axis('off') ``` -------------------------------- ### Define image preprocessing transform Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Creates a transform that converts numpy images to PyTorch tensors. Normalization is not required because the network is untrained. ```python preprocess = transforms.Compose([ transforms.ToTensor() ]) ``` -------------------------------- ### Transform train, validation, and test sets with return_index Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Transforms the train, validation, and test sets using the MRepImageTransformer, returning the raw images and sample indices for each set. ```python train_raw_img, train_sample_idx = mit.transform(train_x, return_index=True, img_format='pytorch') val_raw_img, val_sample_idx = mit.transform(val_x, return_index=True, img_format='pytorch') test_raw_img, test_sample_idx = mit.transform(test_x, return_index=True, img_format='pytorch') ``` -------------------------------- ### Feature selection with threshold=0.9 Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb A higher threshold selects fewer features. The code selects features using the threshold and displays the CAM image. ```python fs_threshold=0.9 feat_idx = camfs.select_class_features(cams=class_cam, threshold=fs_threshold) fig, _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) fig.suptitle(f"threshold={fs_threshold}") plt.show() ``` ```text Result:
``` -------------------------------- ### Reduce predictions per sample using MRepImageTransformer.prediction_reduction Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/mrep_madelon_tensor.ipynb Uses the prediction_reduction method from MRepImageTransformer to aggregate predictions for each sample, then computes sample-level accuracy by thresholding at 0.5 and prints the results. ```python train_pred_reduced = mit.prediction_reduction(train_pred.numpy(), train_target_idx) val_pred_reduced = mit.prediction_reduction(val_pred.numpy(), val_target_idx) test_pred_reduced = mit.prediction_reduction(test_pred.numpy(), test_target_idx) ``` ```python train_sample_acc = metrics.accuracy_score(train_y, train_pred_reduced > 0.5) val_sample_acc = metrics.accuracy_score(val_y, val_pred_reduced > 0.5) test_sample_acc = metrics.accuracy_score(test_y, test_pred_reduced > 0.5) print(f"Training Set Sample Accuracy: {train_sample_acc*100:.1f}%\n" + f"Validation Set Sample Accuracy: {val_sample_acc*100:.1f}%\n" + f"Testing Set Sample Accuracy: {test_sample_acc*100:.1f}%") ``` -------------------------------- ### Generate CAM visualization Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/cam_feature_selection.ipynb Calls the cam_image function to generate the visualization for the training data. The output is a Matplotlib figure with 8 axes (2 rows, 4 columns) displaying the CAMs for each class. ```python _ = cam_image(X_train_tensor, y_train_tensor.detach().cpu().numpy(), class_cam, feat_idx, fs_threshold) ``` -------------------------------- ### Display confusion matrix Source: https://github.com/alok-ai-lab/pydeepinsight/blob/master/examples/pytorch_squeezenet.ipynb Generates and displays a confusion matrix for the test predictions using the label encoder classes. ```python _ = ConfusionMatrixDisplay.from_predictions(test_predicted, y_test_tensor, display_labels=le.classes_) ```