Note
This page is a reference documentation. It only explains the function signature, and not how to use it. Please refer to the user guide for the big picture.
nidl.utils.data_parsing.collate_multimodal¶
- nidl.utils.data_parsing.collate_multimodal(batch, modalities=None)[source]¶
Collate samples with missing modalities into a multimodal batch.
This is the batch format of the multimodal estimators handling missing modalities, such as
CoMM: use it as thecollate_fnof their data loaders.Each sample is a dict
{modality: data}, or a(dict, y)pair, wheredatais:None(or no key) if the sample misses this modality;a list of augmented views of the scan, for training (two for CoMM);
a single scan, for feature extraction (
transform).
A scan is a tensor or an array of shape
(C, *). The scans of a modality are stacked over the samples having it, so they must share the same shape, which may differ from one modality to another (e.g.(1, 128, 128, 128)for an MRI and(10,)for tabular data).- Parameters:
- batchsequence
The samples of the batch.
- modalitiessequence of str or None, default=None
The M modalities. Their order defines the modality indices of the estimator:
modalities[m]is modalitymfor its modality_names, mod_to_encoder and list of adapters. By default, the keys of the first sample, in their order: pass it explicitly to make this order clear.
- Returns:
- Xdict
Dictionary containing:
“x”: a list of M tensors, one per modality, of shape
(N_m, C_m, *): the scans of the
samples having
modality
, or None if no sample of the batch has it. For
training, “views” holds one such list per view instead.“sample_idx”: a list of M tensors of shape
(N_m,), the sample of each scan of each modality (None if no sample has it).“n_samples”: the number of samples B in the batch.
- ytorch.Tensor, optional
The collated targets, only if the samples are
(dict, y)pairs.
- Raises:
- TypeError
If a sample is not a dict or a
(dict, y)pair.- ValueError
If a sample has no modality or an unknown one, if the scans do not hold the same number of views, or if the scans of a modality do not have the same shape.
Examples
>>> import torch >>> scan = torch.zeros(1, 4, 4, 4) >>> samples = [ ... {"t1": [scan, scan], "t2": None}, ... {"t1": [scan, scan], "t2": [scan, scan]}, ... ] >>> X = collate_multimodal(samples, modalities=("t1", "t2")) >>> [tuple(x.shape) for x in X["views"][0]] [(2, 1, 4, 4, 4), (1, 1, 4, 4, 4)] >>> X["sample_idx"] [tensor([0, 1]), tensor([1])]
With a data loader:
>>> from functools import partial >>> from torch.utils.data import DataLoader >>> loader = DataLoader( ... dataset, ... batch_size=32, ... collate_fn=partial( ... collate_multimodal, modalities=("t1", "t2", "flair") ... ), ... )
Examples using nidl.utils.data_parsing.collate_multimodal¶
Multimodal pretraining with missing modalities: CoMM on OpenMind