predict#
- maite.tasks.predict(*, model, dataloader=None, dataset=None, batch_size=1, augmentation=None, return_augmented_data=False)[source]#
Make predictions for a given model & data source with optional augmentation.
- Parameters:
- model
SomeModel Maite Model object.
- dataloader
SomeDataloader|None, (default=None) Compatible maite dataloader.
- dataset
SomeDataset|None, (default=None) Compatible maite dataset.
- batch_size
int, (default=1) Batch size for use with dataset (ignored if dataset=None).
- augmentation
SomeAugmentation|None, (default=None) Compatible maite augmentation.
- return_augmented_data
bool, (default=False) Set to True to return post-augmentation data as a function output.
When this is True, any individual input, target, or metadata datum whose type iterates destructively (i.e. an iterator, such as a generator) is materialized into a tuple before being stored for return. This avoids handing back a spent iterator that has already been consumed by the model or metric. Non-destructive iterables (e.g. lists, tuples, strings, NumPy arrays) are returned unchanged. Materialization holds the datum’s full contents in memory, so a one-time
UserWarningis issued if it occurs; this may be costly for iterator-typed data referencing large amounts of data. Note that only the top level of each datum is materialized: an iterator nested inside an otherwise reusable container may still be returned spent.
- model
- Returns:
tuple[Sequence[Sequence[SomeTargetType]],Sequence[tuple[Sequence[SomeInputType], Sequence[SomeTargetType], Sequence[SomeMetadataType]]]],
A tuple of the predictions (as a sequence of batches) and a sequence of tuples containing the information associated with each batch. Note that the second return argument will be empty if return_augmented_data is False. See
return_augmented_dataabove for how iterator-typed data in the third return argument is materialized to avoid returning spent iterators.
- Raises:
ValueErrorIf neither a dataloader nor a dataset is provided.
Examples
We illustrate with image classification, but the same pattern applies to any AI problem. See the
maite.protocols.image_classificationdocumentation 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, DatasetMetadata, DatumMetadata, ModelMetadata >>> from maite.protocols import image_classification as ic
We set up a tiny three-class problem in which the class of an image is the index of its brightest channel.
>>> def make_image(bright_channel: int) -> npt.NDArray: ... img = np.full((3, 4, 4), 0.1) ... img[bright_channel] = 0.9 ... return img >>> images = [make_image(c) for c in [0, 1, 2, 0]] >>> targets = [np.eye(3)[t] for t in [0, 1, 2, 0]]
We create a
Modelthat predicts the brightest-channel class for each image in a batch, returning a prediction vector per image.>>> class ChannelClassifier: ... metadata: ModelMetadata = {"id": "ChannelClassifier"} ... ... def __call__(self, batch: Sequence[ArrayLike]) -> Sequence[npt.NDArray]: ... preds = [] ... for x in batch: ... cls = int(np.asarray(x).mean(axis=(1, 2)).argmax()) ... preds.append(np.eye(3)[cls]) ... return preds
We define a
Datasetthat returns an (input, target, metadata) 3-tuple per index.predictignores targets, so any placeholder target of the correct type will do.>>> class ImageDataset: ... metadata: DatasetMetadata = {"id": "example_dataset"} ... ... def __init__(self, images: list[npt.NDArray], targets: list[npt.NDArray]) -> None: ... self.images = images ... self.targets = targets ... ... def __len__(self) -> int: ... return len(self.images) ... ... def __getitem__(self, i: int) -> tuple[npt.NDArray, npt.NDArray, DatumMetadata]: ... md: DatumMetadata = {"id": i} ... return self.images[i], self.targets[i], md
Running
predictreturns one sequence of prediction batches (plus a sequence of augmented-data batches, empty here sincereturn_augmented_datadefaults to False).>>> from maite.tasks import predict >>> model: ic.Model = ChannelClassifier() >>> dataset: ic.Dataset = ImageDataset(images, targets) >>> preds, _ = predict(model=model, dataset=dataset, batch_size=2)
We flatten the batched predictions and take the argmax of each score vector to recover the predicted class per image.
>>> [int(np.asarray(p).argmax()) for batch in preds for p in batch] [0, 1, 2, 0]