ml#
datasets#
- class scportrait.tools.ml.datasets.HDF5SingleCellDataset(dir_list: Sequence[str | PathLike[str]], dir_labels: list[int], index_list: list[list[int]] | None = None, transform=None, max_level: int = 5, return_id: bool = True, select_channel: int | list[int] | None = None)#
Dataset reader for scPortrait single-cell datasets stored in HDF5 files.
Examples
dataset = HDF5SingleCellDataset( dir_list=["path/to/data1.hdf5", "path/to/data2.hdf5"], dir_labels=[0, 1], return_id=True, ) image, label, cell_id = dataset[0]
Initialize a dataset with per-file labels stored outside the HDF5 payload.
- Parameters:
dir_list – Paths to HDF5 files or directories containing HDF5 files.
dir_labels – Bulk labels applied to all cells from each entry in dir_list.
index_list – Per-input lists of cell indices to include. If None, all cells are used.
transform – Optional transform applied to each returned tensor.
max_level – Maximum directory depth to scan when an entry in dir_list is a directory.
return_id – Whether to return the unique cell id together with the cell data.
select_channel – Channel index or indices to load from each cell image. If None, all channels are used.
- class scportrait.tools.ml.datasets.LabelledHDF5SingleCellDataset(dir_list: Sequence[str | PathLike[str]], label_colum: int, label_dtype: type, label_column_transform: Callable | None = None, index_list: list[list[int]] | None = None, transform: Callable | None = None, max_level: int = 5, return_id: bool = True, select_channel: list[int] | None | int = None)#
Dataset reader for HDF5 single-cell datasets with labels stored in the file.
Examples
dataset = LabelledHDF5SingleCellDataset( dir_list=["path/to/data.hdf5"], label_colum=0, label_dtype=float, ) image, label, cell_id = dataset[0]
Initialize a dataset that reads per-cell labels from each HDF5 file.
- Parameters:
dir_list – Paths to HDF5 files or directories containing HDF5 files.
label_colum – Column index in single_cell_index_labelled used as the label source.
label_dtype – Type used to convert the loaded labels.
label_column_transform – Optional transform applied to labels after loading.
index_list – Per-input lists of cell indices to include. If None, all cells are used.
transform – Optional transform applied to each returned tensor.
max_level – Maximum directory depth to scan when an entry in dir_list is a directory.
return_id – Whether to return the unique cell id together with the cell data.
select_channel – Channel index or indices to load from each cell image. If None, all channels are used.
- class scportrait.tools.ml.datasets.H5ScSingleCellDataset(dir_list: Sequence[str | PathLike[str]], dir_labels: list[int], index_list: list[list[int]] | None = None, transform=None, max_level: int = 5, return_id: bool = True, select_channel: int | list[int] | None = None)#
Dataset reader for scPortrait single-cell datasets stored in H5SC or H5AD files.
Examples
dataset = H5ScSingleCellDataset( dir_list=["path/to/data.h5sc"], dir_labels=[1], return_id=True, ) image, label, cell_id = dataset[0]
Initialize a dataset with per-file labels stored outside the H5SC payload.
- Parameters:
dir_list – Paths to H5SC/H5AD files or directories containing those files.
dir_labels – Bulk labels applied to all cells from each entry in dir_list.
index_list – Per-input lists of cell indices to include. If None, all cells are used.
transform – Optional transform applied to each returned tensor.
max_level – Maximum directory depth to scan when an entry in dir_list is a directory.
return_id – Whether to return the unique cell id together with the cell data.
select_channel – Channel index or indices to load from each cell image. If None, all channels are used.
- class scportrait.tools.ml.datasets.LabelledH5ScSingleCellDataset(dir_list: Sequence[str | PathLike[str]], label_colum: str, label_column_transform: Callable | None = None, index_list: list[list[int]] | None = None, transform: Callable | None = None, max_level: int = 5, return_id: bool = True, select_channel: list[int] | None | int = None)#
Dataset reader for H5SC/H5AD single-cell datasets with labels stored in the file.
Examples
dataset = LabelledH5ScSingleCellDataset( dir_list=["path/to/data.h5sc"], label_colum="cell_type", ) image, label, cell_id = dataset[0]
Initialize a dataset that reads per-cell labels from each H5SC or H5AD file.
- Parameters:
dir_list – Paths to H5SC/H5AD files or directories containing those files.
label_colum – Column name in obs used as the label source.
label_column_transform – Optional transform applied to labels after loading.
index_list – Per-input lists of cell indices to include. If None, all cells are used.
transform – Optional transform applied to each returned tensor.
max_level – Maximum directory depth to scan when an entry in dir_list is a directory.
return_id – Whether to return the unique cell id together with the cell data.
select_channel – Channel index or indices to load from each cell image. If None, all channels are used.
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: Any, **kwargs: Any)#
Bases:
ModuleBase 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
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
plmodels#
- class scportrait.tools.ml.plmodels.MultilabelSupervisedModel(model_type='VGG2', image_size_factor=None, **kwargs)
Bases:
LightningModuleA 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 orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis 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 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 thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.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 tensordict- 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 byaccumulate_grad_batchesinternally.
- 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 tensordict- 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. x, y = batch # implement your own out = self(x) if dataloader_idx == 0: loss = self.loss0(out, y) else: loss = self.loss1(out, y) # calculate acc labels_hat = torch.argmax(out, dim=1) acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs separately for each dataloader self.log_dict({f"val_loss_{dataloader_idx}": loss, f"val_acc_{dataloader_idx}": acc})
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 tensordict- 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. x, y = batch # implement your own out = self(x) if dataloader_idx == 0: loss = self.loss0(out, y) else: loss = self.loss1(out, y) # calculate acc labels_hat = torch.argmax(out, dim=1) acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs separately for each dataloader self.log_dict({f"test_loss_{dataloader_idx}": loss, f"test_acc_{dataloader_idx}": acc})
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.load_multilabelSupervised(checkpoint_path: str | Path, hparam_path: str | Path, model_type: str, eval: bool = True, device: Literal['cpu', 'cuda', 'mps'] = 'cuda') MultilabelSupervisedModel#
Load a pretrained model uploaded to the github repository.
- Parameters:
checkpoint_path – The path of the checkpoint file to load the pretrained model from
hparam_path – The path of the hparams file containing the hyperparameters
model_type – The type of the model, e.g., ‘VGG1’ or ‘VGG2’
eval – If True then the model will be returned in eval mode
device – Device to load the model on, either “cuda” or “cpu”
- Returns:
The pretrained multilabel classification model loaded from the checkpoint
Examples
>>> model = load_multilabelSupervised("path/to/checkpoint.ckpt", "path/to/hparams.yaml", "resnet50") >>> print(model) MultilabelSupervisedModel(...)
- scportrait.tools.ml.pretrained_models.get_data_dir() Path#
Get path to data that was packaged with scPortrait.
- Returns:
Path to data directory
- scportrait.tools.ml.pretrained_models.autophagy_classifier(device: Literal['cuda', 'cpu'] = 'cuda') MultilabelSupervisedModel#
Load binary autophagy classification model from original SPARCS publication.
- Parameters:
device – Device to load the model on, either “cuda” or “cpu”
- Returns:
Pretrained autophagy classification model
References
Schmacke NA, Mädler SC, Wallmann G, Metousis A, Bérouti M, Harz H, Leonhardt H, Mann M, Hornung V. SPARCS, a platform for genome-scale CRISPR screening for spatial cellular phenotypes. bioRxiv. 2023 Jun 1;542416. doi: 10.1101/2023.06.01.542416.
transforms#
- class scportrait.tools.ml.transforms.RandomRotation(choices: int = 4, include_zero: bool = True)#
Randomly rotate input image in x-degree steps (default is 90).
- Parameters:
choices – number of possible rotations
include_zero – include 0 degree rotation in the choices
- class scportrait.tools.ml.transforms.GaussianNoise(sigma: float | tuple[float, float] = 0.1, mean: float = 0.5, std: float = 1, channels_to_exclude: list[int] | None = None, deep_debug: bool = False)#
Add Gaussian noise to the input tensor.
- Parameters:
sigma – Strength of the added noise. If a range is provided a random value will be sampled form this range.
channels_to_exclude – List of channel indices to exclude from noise addition.
mean – Mean of the Gaussian distribution from which the noise is sampled.
std – Standard deviation of the Gaussian distribution from which the noise is sampled.
deep_debug – If True, the input tensor, the sampled noise, and the transformed tensor are plotted for debugging.
- class scportrait.tools.ml.transforms.GaussianBlur(kernel_size: list[int] | None = None, sigma: tuple[float, float] | None = None)#
Apply a gaussian blur to the input image.
- Parameters:
kernel_size – list of kernel sizes to randomly select from
sigma – tuple of min and max sigma values to randomly select from
- class scportrait.tools.ml.transforms.ChannelSelector(channels: list[int] | None = None, num_channels: int = 5)#
select the channel used for prediction.
- Parameters:
channels – list of channel indices to keep
num_channels – number of channels in the input tensor
- class scportrait.tools.ml.transforms.ChannelMultiplier(n_reps: int = 3)#
duplicate the input tensor
- Parameters:
n_reps – how often to duplicate the tensor
utils#
- scportrait.tools.ml.utils.combine_datasets_balanced(list_of_datasets: list[Dataset], class_labels: list[str | int], train_per_class: int, val_per_class: int, test_per_class: int, seed: int | None = None, return_residual: bool = False, concat_datasets: bool = True) tuple[ConcatDataset, ConcatDataset, ConcatDataset] | tuple[ConcatDataset, ConcatDataset, ConcatDataset, ConcatDataset] | tuple[list[Dataset], list[Dataset], list[Dataset]] | tuple[list[Dataset], list[Dataset], list[Dataset], list[Dataset]]#
Combine multiple datasets to create a balanced dataset for train, val, and test sets.
- Parameters:
list_of_datasets – List of datasets to be combined
class_labels – List of class labels present in the datasets
train_per_class – Number of samples per class in the train set
val_per_class – Number of samples per class in the validation set
test_per_class – Number of samples per class in the test set
seed – Random seed for reproducibility
return_residual – boolean value indicating of left over elements not allocated to one of the datasets should be returned as a seperate dataset
concat_datasets – if the returned datasets should be concatenated or returned as a list
- Returns:
train dataset(s) with balanced samples per class
validation dataset(s) with balanced samples per class
test dataset(s) with balanced samples per class
potentially: residual dataset(s) with all residual samples (unbalanced)
- Return type:
Tuple containing
- Raises:
ValueError – If dataset is too small to be split into requested sizes
- scportrait.tools.ml.utils.split_dataset_fractions(list_of_datasets: list[Dataset], train_size: int | None = None, test_size: int | None = None, val_size: int | None = None, fractions: Sequence[float] | None = None, seed: int | None = None) tuple[ConcatDataset, ConcatDataset, ConcatDataset]#
Split datasets into train, test, and validation sets based on sizes or fractions.
- Parameters:
list_of_datasets – List of datasets to split
train_size – Number of samples in the train set
test_size – Number of samples in the test set
val_size – Number of samples in the validation set
fractions – List of fractions for train/test/val split, must sum to 1
seed – Random seed for reproducibility
- Returns:
Train dataset
Test dataset
Validation dataset
- Return type:
Tuple containing
- Raises:
ValueError – If fractions don’t sum to 1 or if dataset is too small for requested sizes