DataLoader#

class maite.protocols.image_classification.DataLoader(*args, **kwargs)[source]#

A dataloader protocol for the image classification AI problem providing batch-level data access.

Implementers must provide an iterable object (returning an iterator via the __iter__ method) that yields tuples containing batches of data. These tuples contain types Sequence [Image] (elements of shape (C, H, W)), Sequence [ImgClassification] (elements shape (Cl, )), and Sequence [DatumMetadata], which correspond to model input batch, model target type batch, and a datum metadata batch.

Note: Unlike Dataset, this protocol does not require indexing support, only iterating.

Methods

__iter__ -> Iterator[tuple[Sequence[Image], Sequence[ImgClassification], Sequence[DatumMetadata]]]

Return an iterator over batches of data, where each batch contains a tuple of of model input batch (as Sequence [Image]), model target batch (as Sequence [ImgClassification]), and batched datum-level metadata (as Sequence [DatumMetadata]), respectively.

Examples

We create an implementation of the dataloader protocol that returns dummy data.

>>> import numpy as np
>>> from itertools import count
>>> from typing import Iterator

Assume there are 5 classes, and we want to return 3 batches of data, where each batch has 4 datapoints and 4 target labels:

>>> N_CLASSES: int = 5
>>> N_BATCHES: int = 3
>>> N_DATUM: int = 4

We want each datapoint’s metadata to have a unique integer ‘id’ field and a floating-point ‘hour_of_day’ field, so we subclass the DatumMetadata TypedDict:

>>> from maite.protocols import DatumMetadata
>>> class MyDatumMetadata(DatumMetadata):
...     hour_of_day: float

The dataloader assigns sequential ‘id’ values to each datapoint, but otherwise the data it returns during each iteration is randomly generated.

>>> class MyDataLoader:
...     def __iter__(self) -> Iterator[tuple[list[np.ndarray], list[np.ndarray], list[MyDatumMetadata]]]:
...         datum_id = count()
...         for _ in range(N_BATCHES):
...             images: list[np.ndarray] = list(np.random.rand(N_DATUM, 3, 32, 16))
...             targets: list[np.ndarray] = list(np.eye(N_CLASSES)[np.random.choice(N_CLASSES, N_DATUM)])
...             datum_metadata: list[MyDatumMetadata] = [
...                 MyDatumMetadata(id=next(datum_id), hour_of_day=np.random.rand() * 24) for _ in range(N_DATUM)
...             ]
...             yield images, targets, datum_metadata

We can typehint an instance of the above class as a DataLoader:

>>> from maite.protocols import image_classification as ic
>>> dataloader: ic.DataLoader = MyDataLoader()

Finally, we iterate over all batches and print the size of each batch:

>>> print([len(images) for images, _, _ in dataloader])
[4, 4, 4]