Metric Base Class#
- class anomalib.metrics.AnomalibMetric(fields=None, prefix='', strict=True, **kwargs)#
Bases:
objectBase class for metrics in Anomalib.
Makes any torchmetrics metric compatible with the Anomalib framework by adding batch processing capabilities. Subclasses must inherit from both this class and a torchmetrics metric.
The class enables updating metrics with
Batchobjects instead of individual tensors. It extracts the specified fields from the batch and passes them to the underlying metric’s update method.- Parameters:
fields (
Sequence[str] |None) – Names of fields to extract from batch. If None, uses class’sdefault_fields. Required if no defaults.prefix (
str) – Prefix added to metric name. Defaults to “”.strict (
bool) – Whether to raise an error if batch is missing fields.**kwargs – Additional arguments passed to parent metric class.
- Raises:
ValueError – If no fields are specified and class has no defaults.
Example
Create image and pixel-level F1 metrics:
>>> from torchmetrics.classification import BinaryF1Score >>> class F1Score(AnomalibMetric, BinaryF1Score): ... pass ... >>> # Image-level metric using pred_label and gt_label >>> image_f1 = F1Score( ... fields=["pred_label", "gt_label"], ... prefix="image_" ... ) >>> # Pixel-level metric using pred_mask and gt_mask >>> pixel_f1 = F1Score( ... fields=["pred_mask", "gt_mask"], ... prefix="pixel_" ... )
- compute()#
Compute the metric value.
If the metric has not been updated, and metric is not in strict mode, return None.
- Returns:
Computed metric value or None.
- Return type:
Tensor
- update(batch, *args, **kwargs)#
Update metric with values from batch fields.
- Parameters:
batch (
Batch) – Batch object containing required fields.*args – Additional positional arguments passed to parent update.
**kwargs – Additional keyword arguments passed to parent update.
- Raises:
ValueError – If batch is missing any required fields.
- Return type:
None