ml

datasets

class scportrait.tools.ml.datasets.HDF5SingleCellDataset(dir_list, dir_labels, max_level=5, transform=None, return_id=False, return_fake_id=False, index_list=None, select_channel=None)

Class for handling scPortrait single cell datasets stored in HDF5 files.

This class provides a convenient interface for scPortrait formatted hdf5 files containing single cell datasets. It supports loading data from multiple hdf5 files within specified directories, applying transformations on the data, and returning the required information, such as label or id, along with the single cell data.

dir_labels

List of labels corresponding to the directories in dir_list.

Type:

list of int

dir_list

List of path(s) where the hdf5 files are stored. Supports specifying a path to a specific hdf5 file or directory containing hdf5 files.

Type:

list of str

index_list

List of indices to select from the dataset. If set to None all cells are taken. Default is None.

Type:

list of int, or None

transform

A optional user-defined function to apply transformations to the data. Default is None.

Type:

callable, optional

max_level

Maximum levels of directory to search for hdf5 files. Default is 5.

Type:

int, optional

return_id

Whether to return the index of the cell with the data. Default is False.

Type:

bool, optional

return_fake_id

Whether to return a fake index (0) with the data. Default is False.

Type:

bool, optional

select_channel

Specify a specific channel to select from the data. Default is None, which returns all channels.

Type:

int, optional

add_hdf_to_index(current_label, path)

Adds single cell data from the hdf5 file located at path with the specified current_label to the index.

scan_directory(path, current_label, levels_left)

Scans directories for hdf5 files and adds their data to the index with the specified current_label.

stats()

Prints dataset statistics including total count and count per label.

len()

Returns the total number of single cells in the dataset.

getitem(idx)

Returns the data, label, and optional id/fake_id of the single cell specified by the index idx.

Examples

>>> hdf5_data = HDF5SingleCellDataset(
...     dir_list=['path/to/data/data1.hdf5', 'path/to/data2/data2.hdf5'],
...     dir_labels=[0, 1],
...     transform=None,
...     return_id=True
... )
>>> len(hdf5_data)
2000
>>> sample = hdf5_data[0]
>>> sample[0].shape
torch.Size([1, 128, 128])
>>> sample[1]
tensor(0)
>>> sample[2]
tensor(0)
stats()

Print the dataset statistics.

class scportrait.tools.ml.datasets.HDF5SingleCellDatasetRegression(dir_list: list[str], target_col: list[int], hours: False, max_level: int = 5, transform=None, return_id: bool = False, return_fake_id: bool = False, select_channel=None)

Class for handling scPortrait single cell datasets stored in HDF5 files where the label should be read from the dataset itself.

class scportrait.tools.ml.datasets.HDF5SingleCellDatasetRegressionSubset(dir_list: list[str], target_col: list[int], index_list: list[int], hours: False, max_level: int = 5, transform=None, return_id: bool = False, return_fake_id: bool = False, select_channel=None)

Class for handling scPortrait single cell datasets stored in HDF5 files for regression tasks. Supports selecting a subset of the data based on given indices.

metrics

scportrait.tools.ml.metrics.precision(predictions, labels, pos_label=0)

Calculate precision for predicting class pos_label.

Parameters:
  • predictions (torch.Tensor) – Model predictions.

  • labels (torch.Tensor) – Ground truth labels.

  • pos_label (int, optional, default = 0) – The positive label for which to calculate precision.

Returns:

precision – Precision for predicting class pos_label.

Return type:

float

scportrait.tools.ml.metrics.recall(predictions, labels, pos_label=0)

Calculate recall for predicting class pos_label.

Parameters:
  • predictions (torch.Tensor) – Model predictions.

  • labels (torch.Tensor) – Ground truth labels.

  • pos_label (int, optional, default = 0) – The positive label for which to calculate precision.

Returns:

recall – Recall for predicting class pos_label.

Return type:

float

models

class scportrait.tools.ml.models.VGGBase(*args, **kwargs)

Bases: Module

Base implementation of VGG Model Architecture. Can be implemented with varying number of convolutional neural layers and fully connected layers.

Parameters:

nn (Module) – Pytorch Module

Returns:

Pytorch Module

Return type:

nn.Module

make_layers(cfg: list, in_channels: int, batch_norm: bool = True)

Create sequential models layers according to the chosen configuration provided in cfg with optional batch normalization for the CNN.

Parameters:
  • cfg (list) – A list of integers and “M” representing the specific

  • CNN (VGG architecture of the)

  • in_channels (int) – Number of input channels

  • batch_norm (bool, optional) – Whether to use batch normalization. Defaults to True.

Returns:

A sequential model representing the VGG architecture.

Return type:

nn.Sequential

make_layers_MLP(cfg_MLP: list, cfg: list, image_size_factor: int = 2)

Create sequential models layers according to the chosen configuration provided in cfg for the MLP.

Parameters:
  • cfg_MLP (list) – A list of integers and “M” representing the specific

  • MLP (VGG architecture of the)

  • cfg (list) – A list of integers and “M” representing the specific

  • CNN (VGG architecture of the)

  • image_size_factor (int, optional) – VGG model as implemented expects input images of 128x128 pixels.

  • example (Defaults to 2. For)

  • 256x256 (if the input image is)

  • 4. (the image_size_factor should be)

Returns:

A sequential model representing the MLP architecture.

Return type:

nn.Sequential

forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class scportrait.tools.ml.models.VGG1(cfg='B', cfg_MLP='A', dimensions=196, in_channels=1, num_classes=2, image_size_factor=2)

Bases: VGGBase

Instance of VGGBase with the model architecture 1.

class scportrait.tools.ml.models.VGG2(cfg='B', cfg_MLP='B', dimensions=196, in_channels=1, num_classes=2, image_size_factor=2)

Bases: VGGBase

Instance of VGGBase with the model architecture 2.

plmodels

class scportrait.tools.ml.plmodels.MultilabelSupervisedModel(model_type='VGG2', **kwargs)

Bases: LightningModule

A pytorch lightning network module to use a multi-label supervised Model.

Parameters:
  • type (str, optional, default = "VGG2") – Network architecture to used in model. Architectures are defined in scPortrait.tools.ml.models Valid options: “VGG1”, “VGG2”, “VGG1_old”, “VGG2_old”.

  • kwargs (dict) – Additional parameters passed to the model.

network

The selected network architecture.

Type:

torch.nn.Module

train_metrics

MetricCollection for evaluating model on training data.

Type:

torchmetrics.MetricCollection

val_metrics

MetricCollection for evaluating model on validation data.

Type:

torchmetrics.MetricCollection

test_metrics

MetricCollection for evaluating model on test data.

Type:

torchmetrics.MetricCollection

forward(x)

perform forward pass of model.

configure_optimizers()

Optimization function

on_train_epoch_end()

Callback function after each training epoch

on_validation_epoch_end()

Callback function after each validation epoch

confusion_plot(matrix)

Generate confusion matrix plot

training_step(batch, batch_idx)

Perform a single training step

validation_step(batch, batch_idx)

Perform a single validation step

test_step(batch, batch_idx)

Perform a single test step

test_epoch_end(outputs)

Callback function after testing epochs

forward(x)

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode.

Returns:

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

Some things to know:

  • Lightning calls .backward() and .step() automatically in case of automatic optimization.

  • If a learning rate scheduler is specified in configure_optimizers() with key "interval" (default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s .step() method automatically in case of automatic optimization.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizer.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.

  • If you need to control how often the optimizer steps, override the optimizer_step() hook.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    ...

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

pretrained_models

Collection of functions to load pretrained models to use in the scPortrait environment.

scportrait.tools.ml.pretrained_models.autophagy_classifier1_0(device='cuda')

Load binary autophagy classification model published as Model 1.0 in original scPortrait publication.

scportrait.tools.ml.pretrained_models.autophagy_classifier2_0(device='cuda')

Load binary autophagy classification model published as Model 2.0 in original scPortrait publication.

scportrait.tools.ml.pretrained_models.autophagy_classifier2_1(device='cuda')

Load binary autophagy classification model published as Model 2.1 in original scPortrait publication.

transforms

class scportrait.tools.ml.transforms.RandomRotation(choices=4, include_zero=True)

Randomly rotate input image in 90 degree steps.

class scportrait.tools.ml.transforms.GaussianNoise(sigma=0.1, channels_to_exclude=[])

Add gaussian noise to the input image.

class scportrait.tools.ml.transforms.GaussianBlur(kernel_size=[1, 1, 1, 1, 5, 5, 7, 9], sigma=(0.1, 2), channels=[])

Apply a gaussian blur to the input image.

class scportrait.tools.ml.transforms.ChannelReducer(channels=5)

can reduce an imaging dataset dataset to 5, 3 or 1 channel 5: nuclei_mask, cell_mask, channel_nucleus, channel_cellmask, channel_of_interest 3: nuclei_mask, cell_mask, channel_of_interestå 1: channel_of_interestå

class scportrait.tools.ml.transforms.ChannelSelector(channels=[0, 1, 2, 3, 4], num_channels=5)

select the channel used for prediction.

utils

scportrait.tools.ml.utils.combine_datasets_balanced(list_of_datasets, class_labels, train_per_class, val_per_class, test_per_class, seed=None)

Combine multiple datasets to create a single balanced dataset with a specified number of samples per class for train, validation, and test set. A balanced dataset means that from each label source an equal number of data instances are used.

Parameters:
  • list_of_datasets (list of torch.utils.data.Dataset) – List of datasets to be combined.

  • class_labels (list of str or int) – List of class labels present in the datasets.

  • train_per_class (int) – Number of samples per class in the train set.

  • val_per_class (int) – Number of samples per class in the validation set.

  • test_per_class (int) – Number of samples per class in the test set.

Returns:

  • train (torch.utils.data.Dataset) – Combined train dataset with balanced samples per class.

  • val (torch.utils.data.Dataset) – Combined validation dataset with balanced samples per class.

  • test (torch.utils.data.Dataset) – Combined test dataset with balanced samples per class.

scportrait.tools.ml.utils.split_dataset_fractions(list_of_datasets, train_size=None, test_size=None, val_size=None, fractions=None, seed=None)

Split a dataset into train, test, and validation set based on the provided fractions or sizes.

Parameters:
  • dataset (torch.utils.data.Dataset) – Dataset to be split.

  • train_size (int) – Number of samples in the train set.

  • test_size (int) – Number of samples in the test set.

  • val_size (int) – Number of samples in the validation set.

  • fractions (list of float) – Fractions of the dataset to be used for train, test, and validation set. Should sum up to 1 (100%). For example, [0.8, 0.1, 0.1] will split the dataset into 80% train, 10% test, and 10% validation set.

Returns:

  • train (torch.utils.data.Dataset) – Train dataset.

  • val (torch.utils.data.Dataset) – Validation dataset.

  • test (torch.utils.data.Dataset) – Test dataset.