DataLoader#

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

A dataloader protocol for the object detection 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 [ObjectDetectionTarget], and Sequence [DatumMetadata], which correspond to model input batch, model target 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[ObjectDetectionTarget], 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 [ObjectDetectionTarget]), 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 dataclasses import dataclass
>>> from maite.protocols import DatumMetadata, DatasetMetadata, object_detection as od
>>> from itertools import count
>>> from typing import Generator, Iterator

We will return 3 batches with 4 images each, where each image has 3 color channels and a height and width of 10 pixels.

>>> N_BATCHES = 3
>>> N_DATUM = 4
>>> C, H, W = 3, 10, 10

Each image may have zero, one, or two detections, which will be chosen at random. Each detection will have a randomly-drawn bounding box (with a minimum and maximum size in each dimension) and a label chosen randomly from 2 classes. The bounding box coordinates and labels are the “annotations” for the image.

>>> MAX_DETECTIONS = 2
>>> MIN_BOX_SIZE, MAX_BOX_SIZE = 2, 4
>>> N_CLASSES = 2
>>> def generate_random_annotations() -> Generator[np.ndarray]:
...     for _ in range(N_DATUM):
...         n_detections = np.random.choice(MAX_DETECTIONS + 1)
...         box_sizes = np.random.randint(MIN_BOX_SIZE, MAX_BOX_SIZE, (n_detections, 2))
...         box_tl_coords = np.random.randint(0, np.array([W, H]) - box_sizes)
...         box_br_coords = box_tl_coords + box_sizes
...         labels = np.random.choice(N_CLASSES, (n_detections, 1))
...         yield np.hstack([box_tl_coords, box_br_coords, labels])

Each image has a randomly-chosen hour of day that it was taken. The datum-specific metadata class is extended to include the hour of day (along with the unique id).

>>> class MyDatumMetadata(DatumMetadata):
...     hour_of_day: int

An object detection target class defines the bounding boxes, labels, and scores for each detection in an image.

>>> @dataclass
... class MyObjectDetectionTarget:
...     boxes: np.ndarray
...     labels: np.ndarray
...     scores: np.ndarray

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[MyObjectDetectionTarget], list[MyDatumMetadata]]]:
...         datum_id = count()
...         for _ in range(N_BATCHES):
...             images: list[np.ndarray] = list(np.random.rand(N_DATUM, C, H, W))
...             annotations: list[np.ndarray] = list(generate_random_annotations())
...             boxes: list[np.ndarray] = [a[:, :-1] for a in annotations]
...             labels: list[np.ndarray] = [a[:, -1:] for a in annotations]
...             scores: list[np.ndarray] = [np.ones_like(l) for l in labels]
...             od_targets = list(map(MyObjectDetectionTarget, boxes, labels, scores))
...             hours_of_day = list(np.random.choice(24, N_DATUM))
...             datum_metadata: list[MyDatumMetadata] = [
...                 MyDatumMetadata(id=next(datum_id), hour_of_day=h) for h in hours_of_day
...             ]
...             yield images, od_targets, datum_metadata

We can typehint an instance of the above class as a DataLoader and inspect the sizes of each batch:

>>> dataloader: od.DataLoader = MyDataLoader()
>>> print([len(images) for images, _, _ in dataloader])
[4, 4, 4]