evaluate#
- maite.tasks.evaluate(*, model, metric=None, dataloader=None, dataset=None, batch_size=1, augmentation=None, return_augmented_data=False, return_preds=False, collate_fn=<function default_collate_fn>)[source]#
Evaluate a model’s performance on data according to some metric with optional augmentation.
The types handled by all passed components must be compatible to avoid static type checking errors. For example, if the __getitem__ method of a passed dataset returns some
InputTypein the first element of the return tuple then themodel.__call__argument must be type hinted such thatSequence[InputType] can be assigned to it.- Parameters:
- model
SomeModel Maite Model object.
- metric
SomeMetric|None, (default=None) Compatible maite Metric.
- 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.- return_preds
bool, (default=False) Set to True to return raw predictions as a function output.
- collate_fn
SomeCollateFn, (default=default_collate_fn) Callable responsible for transforming an iterable of 3-tuples where each encodes a single datapoint in some batch into a tuple of 3 sequences that each represent a batch of collated inputs, collated targets, and collated metadata, respectively. Defaults to naively push elements from input iterable onto sequences in their order of iteration.
- model
- Returns:
tuple[dict[str,Any],Sequence[TargetType], Sequence[tuple[Sequence[InputType], Sequence[TargetType], Sequence[DatumMetadataType]]]]
Tuple of returned metric value, sequence of model predictions, and sequence of data batch tuples fed to the model during inference. The actual types represented by InputType, TargetType, and DatumMetadataType will vary by the AI problem of the components provided as input arguments (e.g., image classification or object detection.) Note that the second and third return arguments will be empty if return_preds is False or return_augmented_data is False, respectively. 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, MetricMetadata, 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, 1]] # note: last image is mislabeled
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
Metricthat accumulates predictions and targets across batches and computes accuracy oncompute.>>> class Accuracy: ... metadata: MetricMetadata = {"id": "accuracy"} ... ... def __init__(self) -> None: ... self.reset() ... ... def reset(self) -> None: ... self._correct = 0 ... self._total = 0 ... ... def update( ... self, ... preds: Sequence[ArrayLike], ... targets: Sequence[ArrayLike], ... metadata: Sequence[DatumMetadata], ... ) -> None: ... pred_classes = np.vstack([np.asarray(p) for p in preds]).argmax(axis=1) ... true_classes = np.vstack([np.asarray(t) for t in targets]).argmax(axis=1) ... self._correct += int((pred_classes == true_classes).sum()) ... self._total += len(pred_classes) ... ... def compute(self) -> dict[str, float]: ... return {"accuracy": self._correct / self._total}
We create a
Datasetthat returns an (input, target, metadata) 3-tuple per index.>>> 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
We type-hint each instance against its protocol so a static type checker can verify compliance, then run
evaluate. Passing adataset(rather than adataloader) letsevaluatebuild batches ofbatch_sizeinternally.>>> from maite.tasks import evaluate >>> model: ic.Model = ChannelClassifier() >>> metric: ic.Metric = Accuracy() >>> dataset: ic.Dataset = ImageDataset(images, targets) >>> metric_results, _, _ = evaluate( ... model=model, ... metric=metric, ... dataset=dataset, ... batch_size=2, ... )
Three of the four images are classified in agreement with their (possibly noisy) targets.
>>> metric_results {'accuracy': 0.75}
Set
return_preds=Trueand/orreturn_augmented_data=Trueto additionally receive the per-batch predictions and the (post-augmentation) data batches fed to the model; both are empty sequences otherwise.