Histopathology

Tutorial histopathology: This tutorial provides a comprehensive, step-by-step guide to using the bioMONAI platform for nuclei segmentation in histopathology images.

Setup imports

from bioMONAI.data import *
from bioMONAI.transforms import *
from bioMONAI.core import *
from bioMONAI.core import Path
from bioMONAI.data import get_images, get_target, RandomSplitter
from bioMONAI.losses import *
from bioMONAI.losses import SSIMLoss
from bioMONAI.metrics import *
from bioMONAI.datasets import download_file
import warnings
warnings.filterwarnings("ignore")
device = get_device()
print(device)
cuda

Download Data

In the next cell, we will download the dataset required for this tutorial. The dataset is hosted online, and we will use the download_file function from the bioMONAI library to download and extract the files.

  • You can change the output_directory variable to specify a different directory where you want to save the downloaded files.
  • The url variable contains the link to the dataset. If you have a different dataset, you can replace this URL with the link to your dataset.
  • By default, we are downloading only the first two images. You can modify the code to download more images if needed.

Make sure you have enough storage space in the specified directory before downloading the dataset.

# Specify the directory where you want to save the downloaded files
output_directory = "../_data/TNBC_NucleiSegmentation"
# Define the base URL for the dataset
url = 'https://zenodo.org/records/2579118/files/TNBC_NucleiSegmentation.zip'

# Download only the first two images
download_file(url, output_directory, extract=True, extract_dir='.', hash='014bc1e08d6459be5508620ad219063a45179a1767b7caf84d64245d7f6cc5a3')
The file has been downloaded and saved to: /home/biagio/bioMONAI/nbs/_data/TNBC_NucleiSegmentation

Prepare Data for Training

In the next cell, we will prepare the data for training. We will specify the path to the training images and define the batch size and patch size. Additionally, we will apply several transformations to the images to augment the dataset and improve the model’s robustness.

  • X_path: The path to the directory containing the low-resolution training images.
  • bs: The batch size, which determines the number of images processed together in one iteration.
  • patch_size: The size of the patches to be extracted from the images.
  • itemTfms: A list of item-level transformations applied to each image, including random cropping, rotation, and flipping.
  • batchTfms: A list of batch-level transformations applied to each batch of images, including intensity scaling.
  • get_target_fn: A function to get the corresponding ground truth images for the low-resolution images.

You can customize the following parameters to suit your needs: - Change the X_path variable to point to a different dataset. - Adjust the bs and patch_size variables to match your hardware capabilities and model requirements. - Modify the transformations in itemTfms and batchTfms to include other augmentations or preprocessing steps.

After defining these parameters and transformations, we will create a BioDataLoaders object to load the training and validation datasets.

X_path = Path(output_directory)/'TNBC_dataset'
img_paths = get_images(X_path,'Slide*')
# create a function to get the target path from the image path
get_target_fn = get_target('GT', same_filename=True, relative_path=True, map_foldername=True, target_folder_prefix="GT", signal_folder_prefix="Slide")

print('input:', img_paths[4], '\ntarget:', get_target_fn(img_paths[4]))
input: ../_data/TNBC_NucleiSegmentation/TNBC_dataset/Slide_07/07_2.png 
target: ../_data/TNBC_NucleiSegmentation/TNBC_dataset/GT_07/07_2.png
gt_paths = [get_target_fn(img_paths[i]) for i in range(len(img_paths))]
patch_size = (4, 128, 128)
overlap = 0.5
save_patches_grid(img_paths, gt_paths, output_directory, patch_size, overlap)
Processing files: 100%|██████████| 50/50 [00:02<00:00, 19.04it/s]
Train set saved to '../_data/TNBC_NucleiSegmentation/patches_train.csv'.
Test set saved to '../_data/TNBC_NucleiSegmentation/patches_test.csv'.
'is_valid' column added to '../_data/TNBC_NucleiSegmentation/patches_train.csv' for validation samples.
n_channels = 3
data_ops = {
    'fn_col': ['path_signal'],
    'target_col': ['path_target'],
    'valid_col': ['is_valid'],
    'seed': 42, 
    'bs': 16,
    'img_cls': BioImageMulti,
    'target_img_cls': BioImage,   # class for target images
    'item_tfms': [CropND(slices=[(0,n_channels)], dims=[0]),  # crop channels
                # RandCropND(patch_size),   # item transformations
                RandRot90(prob=.75), 
                RandFlip(prob=0.75)],
    'batch_tfms': [ScaleIntensityPercentiles()],   # batch transformations 
}

data = BioDataLoaders.from_csv(
    '',
    output_directory + '/patches_train.csv',
    show_summary=False,
    **data_ops,
    )

# print length of training and validation datasets
print('train images:', len(data.train_ds.items), '\nvalidation images:', len(data.valid_ds.items))
train images: 1611 
validation images: 231

Visualize a Batch of Training Data

In the next cell, we will visualize a batch of training data to get an idea of what the images look like after applying the transformations. This step is crucial to ensure that the data augmentation and preprocessing steps are working as expected.

  • data.show_batch(cmap='magma'): This function will display a batch of images from the training dataset using the ‘magma’ colormap.

Change the cmap parameter to use a different colormap (e.g., ‘gray’, ‘viridis’, ‘plasma’) based on your preference.

Visualizing the data helps in understanding the dataset better and ensures that the transformations are applied correctly.

data.show_batch(cmap='magma')

Define and Train the Model

# from monai.networks.nets import UNETR
from bioMONAI.nets import create_unet_model, resnet34
# from fastai.vision.all import xresnet50

# model = UNETR(in_channels=n_channels, out_channels=1, img_size=patch_size[1:], feature_size=32, norm_name='batch', spatial_dims=2)

model = create_unet_model(resnet34, 1, patch_size[1:], True, n_in=n_channels, cut=None, blur_final=True, self_attention=False)
from fastai.vision.all import BCEWithLogitsLossFlat
from bioMONAI.metrics import DiceMetric

loss = BCEWithLogitsLossFlat()

metrics = [DiceMetric(include_background=False)]

trainer = fastTrainer(data, model, loss_fn=loss, metrics=metrics, show_summary=False)
# trainer.fit_one_cycle(50, 1e-3)
trainer.fine_tune(50, freeze_epochs=2)
epoch train_loss valid_loss Dice time
0 0.184499 0.162620 0.673594 00:07
1 0.134555 0.120975 0.768951 00:07

epoch train_loss valid_loss Dice time
0 0.091764 0.097456 0.798134 00:07
1 0.086050 0.091826 0.827446 00:06
2 0.081616 0.089969 0.835127 00:07
3 0.073072 0.084859 0.823746 00:07
4 0.070320 0.082582 0.843956 00:07
5 0.067187 0.090941 0.839529 00:07
6 0.063999 0.082716 0.848953 00:06
7 0.061475 0.082668 0.817931 00:07
8 0.060817 0.078503 0.844330 00:07
9 0.060438 0.085385 0.845426 00:06
10 0.060647 0.085425 0.847906 00:07
11 0.065261 0.078340 0.851368 00:06
12 0.055217 0.080057 0.853913 00:07
13 0.057883 0.086349 0.854765 00:07
14 0.051903 0.071777 0.869676 00:08
15 0.048770 0.083856 0.848438 00:07
16 0.045779 0.073468 0.872384 00:07
17 0.042115 0.071264 0.862684 00:07
18 0.042158 0.072633 0.866532 00:07
19 0.041533 0.071844 0.858294 00:07
20 0.039272 0.074185 0.870372 00:07
21 0.036202 0.065099 0.884588 00:07
22 0.036708 0.071725 0.877802 00:07
23 0.033993 0.070112 0.882150 00:07
24 0.030676 0.063484 0.892478 00:07
25 0.028386 0.065040 0.894892 00:07
26 0.027225 0.067199 0.895281 -1:53:33
27 0.024244 0.062721 0.907350 00:07
28 0.023432 0.060378 0.901014 00:06
29 0.021402 0.064535 0.909008 00:07
30 0.020900 0.060750 0.908314 00:06
31 0.017871 0.059637 0.913912 00:07
32 0.016801 0.061332 0.912723 00:06
33 0.015870 0.058473 0.914617 00:07
34 0.015032 0.058980 0.918565 00:07
35 0.013754 0.059343 0.922802 00:06
36 0.012705 0.064594 0.921573 00:07
37 0.011910 0.064638 0.921512 00:06
38 0.011060 0.063823 0.923453 00:07
39 0.010980 0.064713 0.919502 00:06
40 0.010291 0.067489 0.922427 00:07
41 0.009685 0.063932 0.924545 00:07
42 0.009040 0.065260 0.925301 00:06
43 0.009024 0.065027 0.929672 00:07
44 0.008723 0.068986 0.925818 00:06
45 0.008219 0.067019 0.928363 00:07
46 0.008122 0.070048 0.923837 00:07
47 0.007932 0.067041 0.926900 00:06
48 0.007961 0.070229 0.924903 00:07
49 0.007738 0.068012 0.927388 00:06

Show Results

In the next cell, we will visualize the results of the trained model on a batch of validation data. This step helps in understanding how well the model has learned to denoise the images.

  • trainer.show_results(cmap='magma'): This function will display a batch of images from the validation dataset along with their corresponding denoised outputs using the ‘magma’ colormap.

Visualizing the results helps in assessing the performance of the model and identifying any areas that may need further improvement.

trainer.show_results(cmap='magma')

Save the Trained Model

In the next cell, we will save the trained model to a file. This step is crucial to preserve the model’s weights and architecture, allowing you to load and use the model later without retraining it.

  • trainer.save('tmp-model'): This function saves the model to a file named ‘tmp-model’. You can change the filename to something more descriptive based on your project.

Suggestions for customization: - Change the filename to include details like the model architecture, dataset, or date (e.g., ‘unet_resnet34_U2OS_2023’). - Save the model in a specific directory by providing the full path (e.g., ‘models/unet_resnet34_U2OS_2023’). - Save additional information like training history, metrics, or configuration settings in a separate file for better reproducibility.

Saving the model ensures that you can easily share it with others or deploy it in a production environment without needing to retrain it.

# trainer.save('tmp-model')

Evaluate the Model on Test Data

In the next cell, we will evaluate the performance of the trained model on unseen test data. This step is crucial to get an unbiased evaluation of the model’s performance and understand how well it generalizes to new data.

  • test_X_path: The path to the directory containing the low-resolution test images.
  • test_data: A DataLoader object created from the test images.
  • evaluate_model(trainer, test_data, metrics=SSIMMetric(2)): This function evaluates the model on the test dataset using the specified metrics (in this case, SSIM).

Suggestions for customization: - Change the test_X_path variable to point to a different test dataset. - Add more metrics to the metrics parameter to get a comprehensive evaluation (e.g., MSEMetric(), MAEMetric()). - Save the evaluation results to a file for further analysis or reporting.

Evaluating the model on test data helps in understanding its performance in real-world scenarios and identifying any areas that may need further improvement.

test_data = test_biodataloader(data, output_directory + '/patches_test.csv')
# print length of test dataset
print('test images:', len(test_data.items))

evaluate_model(trainer, test_data, metrics=[SSIMMetric(2)]);
test images: 461

Value
BCEWithLogitsLossFlat
Mean 0.651290
Median 0.660990
Standard Deviation 0.038701
Min 0.522329
Max 0.700462
Q1 0.625884
Q3 0.683948

Value
SSIM
Mean 0.947963
Median 0.962454
Standard Deviation 0.051858
Min 0.691255
Max 1.000000
Q1 0.922833
Q3 0.989023