augment_dataloader#

maite.tasks.augment_dataloader(*, augmentation, dataloader)[source]#

Create an DataLoader of augmented inputs from a Dataset or DataLoader.

Parameters:
augmentationAugmentation

Compatible maite augmentation.

dataloaderDataloader

Compatible maite dataloader.

Returns:
DataLoader[InputType, TargetType, DatumMetadataType]

DataLoader for augmented inputs.

Examples

We illustrate with image classification, but the same pattern applies to any AI problem. See the maite.protocols.image_classification documentation for details on writing compliant components.

>>> import numpy as np
>>> import numpy.typing as npt
>>> from collections.abc import Sequence
>>> from maite.protocols import ArrayLike, AugmentationMetadata, DatumMetadata
>>> from maite.protocols import image_classification as ic

An Augmentation takes a data batch (a tuple of input, target, and metadata batches) and returns a modified batch. This one zeros out the first channel of every image.

>>> class ZeroFirstChannel:
...     metadata: AugmentationMetadata = {"id": "zero_first_channel"}
...
...     def __call__(
...         self,
...         batch: tuple[Sequence[ArrayLike], Sequence[ArrayLike], Sequence[DatumMetadata]],
...     ) -> tuple[Sequence[npt.NDArray], Sequence[ArrayLike], Sequence[DatumMetadata]]:
...         inputs, targets, metadata = batch
...         inputs_aug = []
...         for x in inputs:
...             arr = np.asarray(x).copy()
...             arr[0] = 0.0
...             inputs_aug.append(arr)
...         return inputs_aug, targets, metadata

A DataLoader is any iterable of such batches. Here we build one by hand from two shape-(3, 4, 4) images.

>>> images = [np.ones((3, 4, 4)) for _ in range(2)]
>>> targets = [np.eye(3)[c] for c in [0, 1]]
>>> metadata: list[DatumMetadata] = [{"id": 0}, {"id": 1}]
>>> dataloader = [(images, targets, metadata)]

Wrapping the dataloader with the augmentation yields a new dataloader whose batches have been augmented.

>>> from maite.tasks import augment_dataloader
>>> augmentation: ic.Augmentation = ZeroFirstChannel()
>>> augmented = augment_dataloader(augmentation=augmentation, dataloader=dataloader)
>>> aug_inputs, _, _ = next(iter(augmented))
>>> float(np.asarray(aug_inputs[0])[0].sum())  # first channel is now all zeros
0.0