Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(metrics): Convention blocks and pins for the task metrics (batch 12d) (#5635)

Dmytro Mishkinf8c622d2e7af
diff --git a/changelog.d/5635.added.md b/changelog.d/5635.added.md
new file mode 100644
index 000000000..a75e22cbc
--- /dev/null
+++ b/changelog.d/5635.added.md
@@ -0,0 +1 @@
+Convention blocks for the task metrics (classification, segmentation, detection, optical flow, disparity and pose), with `test_convention_*` pins and a "Task metrics" sub-section on the conventions page that tabulates each metric's output, pooling and scale.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 03ebdeaf9..4e8b260d3 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -900,6 +900,117 @@ Task metrics
:func:`~kornia.metrics.confusion_matrix` puts the target class on the rows and the predicted class on the columns, and
:func:`~kornia.metrics.mean_iou` reads its per-class IoU from that matrix.
+The task metrics differ in what they return, in what they pool and in their scale: percent, fraction, pixels or
+degrees. Each Convention block states its own, and the table collects them. For the background class 0 and for a
+class absent from a sample, see `Dense-prediction losses`_.
+
+.. list-table::
+ :header-rows: 1
+
+ * - functions
+ - output
+ - pooled over
+ - scale
+ * - :func:`~kornia.metrics.accuracy`
+ - a list of 0-d tensors, one per entry of ``topk``
+ - the batch
+ - percent, ``[0, 100]``
+ * - :func:`~kornia.metrics.confusion_matrix`
+ - ``(B, K, K)``, rows the target and columns the prediction
+ - nothing: one matrix per sample
+ - counts
+ * - :func:`~kornia.metrics.mean_iou`
+ - ``(B, K)``
+ - nothing: one IoU per sample and class
+ - fraction, ``[0, 1]``
+ * - :func:`~kornia.metrics.mean_iou_bbox`
+ - ``(B1, B2)``
+ - nothing: one IoU per pair of boxes
+ - fraction, ``[0, 1]``
+ * - :func:`~kornia.metrics.mean_average_precision`
+ - a 0-d tensor and a ``{class id: AP}`` dict
+ - the detections of all images, per class, then a mean over the classes with objects
+ - fraction, ``[0, 1]``; ``-1`` for a class without objects, and for the mAP when no image has a foreground
+ object
+ * - :func:`~kornia.metrics.aepe`, :func:`~kornia.metrics.average_endpoint_error`, :class:`~kornia.metrics.AEPE`
+ - 0-d, or ``(*)`` for ``reduction='none'``
+ - every position of every sample
+ - the units of the flow
+ * - :func:`~kornia.metrics.mean_absolute_disparity_error`,
+ :func:`~kornia.metrics.root_mean_squared_disparity_error`
+ - 0-d, or ``(*)`` for ``reduction='none'``
+ - every valid pixel of every image
+ - pixels
+ * - :func:`~kornia.metrics.mean_bad_pixel_error`, :func:`~kornia.metrics.kitti_d1_error`
+ - 0-d, or ``(*)`` for ``reduction='none'``
+ - every valid pixel of every image
+ - fraction, ``[0, 1]``
+ * - :func:`~kornia.metrics.angle_error_mat`, :func:`~kornia.metrics.angle_error_vec`
+ - ``(*)``, 0-d for one pair
+ - nothing: one angle per pair
+ - degrees
+ * - :func:`~kornia.metrics.pose_errors`
+ - a dict of ``(B,)`` tensors, ``(1,)`` for one pose
+ - nothing: one error per pose
+ - degrees
+ * - :func:`~kornia.metrics.translation_ate`
+ - ``(*)``, ``(1,)`` for one translation
+ - nothing: one distance per sample
+ - the units of the translations
+ * - :func:`~kornia.metrics.auc_from_errors`
+ - a ``{threshold: AUC}`` dict of Python floats
+ - all errors
+ - percent, ``[0, 100]``
+ * - :class:`~kornia.metrics.AverageMeter`
+ - ``avg``, a Python float
+ - every update, weighted by its ``n``
+ - the scale of the values passed
+
+Porting the task metrics from other libraries:
+
+- scikit-learn takes the target first and kornia the prediction; both put the target on the rows:
+ ``confusion_matrix(pred, target, K)[b]`` equals
+ ``sklearn.metrics.confusion_matrix(target[b].ravel(), pred[b].ravel(), labels=range(K))``. ``normalized=True`` is
+ ``normalize='true'`` up to the ``1e-6`` added to every row sum, not the per-prediction ``normalize='pred'``. Without
+ tied scores, ``accuracy(pred, target, topk=(k,))[0]`` is 100 times
+ ``top_k_accuracy_score(target, pred, k=k, labels=range(C))`` for more than two classes, and 100 times
+ ``accuracy_score(target, pred.argmax(1))`` for ``k=1``.
+- The IoU of a whole batch or dataset, which
+ ``jaccard_score(target.ravel(), pred.ravel(), labels=range(K), average=None)`` and torchmetrics'
+ ``MulticlassJaccardIndex(num_classes=K, average='none')`` report, is the IoU of the summed matrix
+ ``confusion_matrix(pred, target, K).sum(0)``, not the mean of :func:`~kornia.metrics.mean_iou` over the batch.
+- :func:`~kornia.metrics.mean_average_precision` matches a detection to an object only when their IoU is strictly
+ greater than ``threshold``, as ``voc_eval`` of py-faster-rcnn does, and computes that IoU on exclusive boxes, as
+ :func:`~kornia.metrics.mean_iou_bbox` does, where py-faster-rcnn and the PASCAL VOC devkit add 1 to every box width
+ and height. The devkit (``VOCevaldet.m``) matches at ``IoU >= 0.5``, so a detection whose IoU equals the threshold
+ is a false positive in kornia and a true positive there.
+- COCO's evaluation, run as torchmetrics' ``MeanAveragePrecision(iou_thresholds=[0.5],
+ rec_thresholds=[i / 10 for i in range(11)], backend='pycocotools')``, pools the detections of all images,
+ interpolates at kornia's 11 recall levels and leaves a class without objects out of the mean, with AP ``-1`` where it
+ lists one, as kornia does. It reproduces kornia's AP except in five cases: it matches at ``IoU >= 0.5``; it gives a
+ detection whose best object is already matched to the best object still free; it scores class 0 like every other
+ class; it scores only the 100 highest-scoring detections of a class in each image; and it ranks detections of equal
+ score by image, then in input order, where kornia leaves their order to ``torch.sort``.
+- torchvision's RAFT models return a list of ``(B, 2, H, W)`` flows, channel first, where
+ :func:`~kornia.metrics.aepe` takes ``(B, H, W, 2)``. The endpoint error of RAFT's training code,
+ ``((pred - gt) ** 2).sum(1).sqrt()`` on channel-first flows (``sum(0)`` on one flow in its evaluation code), equals
+ ``aepe(pred.permute(0, 2, 3, 1), gt.permute(0, 2, 3, 1), reduction='none')``. Its mean is the default ``'mean'``
+ where every pixel is valid, as in RAFT's Chairs and Sintel evaluation; RAFT's training metrics and its KITTI
+ evaluation average only the valid pixels, KITTI image by image, so take those means of the ``'none'`` map.
+- :func:`~kornia.metrics.kitti_d1_error` applies the outlier rule of the KITTI 2015 devkit (``evaluate_scene_flow.cpp``)
+ and pools like it: the devkit adds up outliers and valid pixels over all images before dividing, so its value is not
+ the mean of per-image D1. The devkit also reads a ground-truth disparity of 0 as invalid and scores its own
+ interpolated version of the estimate: pass a dense prediction and ``valid_mask=target > 0`` to reproduce its
+ number.
+- SuperGlue's ``pose_auc`` and the ``cal_error_auc`` of glue-factory, the evaluation code of LightGlue, return the pose
+ AUC as a fraction, glue-factory's rounded to four decimals. Both equal :func:`~kornia.metrics.auc_from_errors`
+ divided by 100 for errors without NaN: the references count a NaN as a failure, kornia propagates it. SuperGlue's
+ ``match_pairs.py`` prints 100 times that fraction, a percentage like kornia's; glue-factory reports the fraction
+ itself. glue-factory's pose error, the larger of the rotation angle and the folded translation angle, is the
+ ``"max_err"`` of :func:`~kornia.metrics.pose_errors` with the default ``fold_translation=True``. For a zero
+ ground-truth translation glue-factory reads a translation error of 90 degrees, where
+ :func:`~kornia.metrics.pose_errors` returns NaN.
+
.. _two-view-conventions:
Two-view geometry
diff --git a/docs/source/metrics.optical_flow.rst b/docs/source/metrics.optical_flow.rst
index 87facbc9c..b95e319d1 100644
--- a/docs/source/metrics.optical_flow.rst
+++ b/docs/source/metrics.optical_flow.rst
@@ -4,5 +4,6 @@ Optical flow
.. currentmodule:: kornia.metrics
.. autofunction:: aepe
+.. autofunction:: average_endpoint_error
.. autoclass:: AEPE
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index a729f7351..08ce90bda 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -23,9 +23,17 @@ import torch
def accuracy(pred: torch.Tensor, target: torch.Tensor, topk: Tuple[int, ...] = (1,)) -> List[torch.Tensor]:
"""Compute the accuracy over the k top predictions for the specified values of k.
+ Convention:
+ - ``pred`` holds one score per class, :math:`(B, C)`; only the order of the scores in a row matters.
+ ``target`` holds class indices, :math:`(B,)` or :math:`(B, 1)`.
+ - The result is a list with one 0-d float32 tensor per entry of ``topk``, in that order. Each is a
+ **percentage** in :math:`[0, 100]`, not a fraction, taken over the whole batch: a sample counts for ``k``
+ when its target is among its ``k`` highest scores, and a ``k`` above :math:`C` counts as :math:`C`.
+ :ref:`Losses and metrics <losses-metrics-conventions>` lists the scale of every task metric.
+
Args:
- pred: the input torch.Tensor with the logits to evaluate.
- target: the torch.Tensor containing the ground truth.
+ pred: the class scores, with shape :math:`(B, C)`.
+ target: the ground-truth class indices, with shape :math:`(B,)` or :math:`(B, 1)`.
topk: the expected topk ranking.
Example:
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index ab6b714bb..957ef4488 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -23,12 +23,20 @@ import torch
class AverageMeter:
"""Computes and stores the average and current value.
+ Convention:
+ - ``update(val, n)`` adds ``val * n`` to ``sum`` and ``n`` to ``count``, so ``avg`` is the ``n``-weighted
+ mean: the mean over samples when every ``val`` is a batch mean and ``n`` its batch size. ``val`` keeps the
+ last value passed, unweighted.
+ - Values are not rescaled: :func:`~kornia.metrics.accuracy` percentages average to a percentage. A tensor
+ ``val`` keeps ``sum`` a tensor that holds its autograd graph; pass a detached tensor or a Python number to
+ avoid keeping it.
+
Example:
>>> stats = AverageMeter()
- >>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy
+ >>> acc1 = torch.tensor(99.0) # top-1 accuracy of a batch in percent, as in K.metrics.accuracy(...)[0]
>>> stats.update(acc1, n=1) # where n is batch size usually
>>> round(stats.avg, 2)
- 0.99
+ 99.0
"""
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index c5eca292b..33889c6a1 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -46,22 +46,34 @@ def confusion_matrix(
) -> torch.Tensor:
r"""Compute confusion matrix to evaluate the accuracy of a classification.
+ Convention:
+ - ``pred`` and ``target`` are class labels of the same shape, prediction first, in ``uint8`` or any signed
+ integer dtype; a bool tensor counts as the labels 0 and 1. A floating-point label tensor raises, and so does
+ a label outside :math:`[0, K)`, unless the call is exported or compiled, which may skip the range check.
+ - The first axis is always the batch: the result holds one :math:`(K, K)` float32 count matrix per sample,
+ :math:`(B, K, K)`, and is never pooled over the batch, so a flat :math:`(N,)` label vector gives :math:`N`
+ matrices that count one label each. Sum over the first axis for the matrix of a whole batch or dataset.
+ - Rows are the target and columns the prediction, ``cm[b, target, pred]``; swapping the two arguments
+ transposes every count matrix. :ref:`Losses and metrics <losses-metrics-conventions>` maps the matrix and
+ ``normalized`` onto scikit-learn.
+ - Known defect: the range check follows ``is_exporting()``, whose meaning under ``torch.compile`` depends on
+ the torch version, so a compiled call can skip it and count an out-of-range prediction in another cell
+ (`#5037 <https://github.com/kornia/kornia/issues/5037>`_).
+
Args:
pred: tensor with estimated targets returned by a
classifier. The shape can be :math:`(B, *)` and must contain integer
values between 0 and K-1.
target: tensor with ground truth (correct) target
- values. The shape can be :math:`(B, *)` and must contain integer
- values between 0 and K-1, where targets are assumed to be provided as
- one-hot vectors.
+ values. The shape must be that of ``pred``, and it must contain integer
+ values between 0 and K-1.
num_classes: total possible number of classes in target.
normalized: whether to normalize each target row by its sum plus ``1e-6``.
Non-empty rows sum approximately to one; empty rows remain zero.
Returns:
a tensor containing the confusion matrix with shape
- :math:`(B, K, K)` where K is the number of classes, rows represent targets,
- and columns represent predictions.
+ :math:`(B, K, K)` where K is the number of classes.
Example:
>>> logits = torch.tensor([[0, 1, 0]])
diff --git a/kornia/metrics/disparity.py b/kornia/metrics/disparity.py
index 5490eae51..5d9769ec4 100644
--- a/kornia/metrics/disparity.py
+++ b/kornia/metrics/disparity.py
@@ -101,6 +101,19 @@ def mean_absolute_disparity_error(
\text{MAE}(D, D^{gt}) = \frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} |D_{p} - D^{gt}_{p}|
+ Convention:
+ - The maps hold disparities in pixels, have any shape :math:`(*)` and must have a floating dtype. ``'mean'``
+ and ``'sum'`` pool every valid pixel of every image into one 0-d value, in pixels here, so for images with
+ different numbers of valid pixels the result is not the mean of the per-image errors. The other disparity
+ metrics pool the same way.
+ - ``valid_mask`` is broadcast to the maps from the right: an :math:`(H, W)` mask applies to every image of a
+ :math:`(B, H, W)` batch and a :math:`(B, 1, 1)` mask selects whole images, while a :math:`(B,)` mask is
+ matched against the last axis, not the batch. Nothing is masked automatically: a pixel with an invalid
+ ground truth, such as a zero disparity, counts unless ``valid_mask`` excludes it.
+ - A ``nan`` at a valid pixel of either map propagates into this error and the RMSE, while
+ :func:`~kornia.metrics.mean_bad_pixel_error` and :func:`~kornia.metrics.kitti_d1_error` count it as a
+ good pixel.
+
Args:
input: the predicted disparity map with arbitrary shape :math:`(*)`.
target: the ground truth disparity map with the same shape as ``input``.
@@ -160,6 +173,11 @@ def root_mean_squared_disparity_error(
\text{RMSE}(D, D^{gt}) =
\sqrt{\frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} (D_{p} - D^{gt}_{p})^{2}}
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.mean_absolute_disparity_error`: ``'mean'`` gives one 0-d
+ value in pixels, pooled over every valid pixel of the batch, and ``'sum'`` gives :math:`\sqrt{\sum e^2}`, not
+ a sum of errors.
+
Args:
input: the predicted disparity map with arbitrary shape :math:`(*)`.
target: the ground truth disparity map with the same shape as ``input``.
@@ -227,6 +245,11 @@ def mean_bad_pixel_error(
KITTI reports: that benchmark uses D1, which adds a relative criterion on top of this one.
See :func:`kitti_d1_error`.
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.mean_absolute_disparity_error`: ``'mean'`` gives one 0-d
+ value pooled over every valid pixel of the batch, here a **fraction** in :math:`[0, 1]`, and ``'sum'`` the
+ number of bad pixels.
+
Args:
input: the predicted disparity map with arbitrary shape :math:`(*)`.
target: the ground truth disparity map with the same shape as ``input``.
@@ -242,8 +265,6 @@ def mean_bad_pixel_error(
Return:
the computed metric as a scalar, or the per-pixel bad-pixel map if ``reduction='none'``.
- The scalar is a **fraction** in :math:`[0, 1]`, not a percentage, and a batch is **pooled**
- over every valid pixel of every image rather than averaged per image.
Note:
If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.
@@ -295,9 +316,15 @@ def kitti_d1_error(
\frac{|D_{p} - D^{gt}_{p}|}{|D^{gt}_{p}|} > \tau_{rel}\right]
This is the outlier ratio reported by the KITTI 2015 stereo benchmark, expressed as a fraction
- in :math:`[0, 1]` instead of a percentage. Unlike :func:`mean_bad_pixel_error`, the additional
- relative criterion keeps large disparities from being penalised for errors that are small
- compared to their magnitude.
+ in :math:`[0, 1]` instead of a percentage.
+
+ Convention:
+ - See the Convention block of :func:`~kornia.metrics.mean_absolute_disparity_error`: ``'mean'`` gives one
+ 0-d value pooled over every valid pixel of the batch, here a **fraction** in :math:`[0, 1]`, and ``'sum'``
+ the number of outliers. :ref:`Losses and metrics <losses-metrics-conventions>` relates it to the KITTI
+ devkit.
+ - The relative error divides by ``target``, so the two maps are not interchangeable: swapping them can
+ change the result.
Args:
input: the predicted disparity map with arbitrary shape :math:`(*)`.
@@ -315,11 +342,6 @@ def kitti_d1_error(
Return:
the computed metric as a scalar, or the per-pixel outlier map if ``reduction='none'``.
- The scalar is a **fraction** in :math:`[0, 1]`, not a percentage. A batch is **pooled**:
- every valid pixel of every image contributes equally to one ratio, which is what the KITTI
- devkit accumulates and what the leaderboard reports. That is not the same as averaging the
- per-image D1 values, and the two differ whenever the images hold different numbers of valid
- pixels.
Note:
If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.
diff --git a/kornia/metrics/endpoint_error.py b/kornia/metrics/endpoint_error.py
index 9e915941d..f05ba47dd 100644
--- a/kornia/metrics/endpoint_error.py
+++ b/kornia/metrics/endpoint_error.py
@@ -22,7 +22,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK
def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
- r"""Create a function that calculates the average endpoint error (AEPE) between 2 flow maps.
+ r"""Calculate the average endpoint error (AEPE) between 2 flow maps.
AEPE is the endpoint error between two 2D vectors (e.g., optical flow).
Given a h x w x 2 optical flow map, the AEPE is:
@@ -31,6 +31,18 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
\text{AEPE}=\frac{1}{hw}\sum_{i=1, j=1}^{h, w}\sqrt{(I_{i,j,1}-T_{i,j,1})^{2}+(I_{i,j,2}-T_{i,j,2})^{2}}
+ Convention:
+ - Flow is channel-last, :math:`(*, 2)` such as :math:`(B, H, W, 2)`, in the units of the flow (pixels for
+ optical flow). Permute a channel-first :math:`(B, 2, H, W)` flow to :math:`(B, H, W, 2)` first: it raises
+ unless :math:`W = 2`, where it is read wrongly. :ref:`Losses and metrics <losses-metrics-conventions>` ports
+ RAFT's endpoint error.
+ - The endpoint error is the Euclidean distance between the two vectors at every position, symmetric in
+ ``input`` and ``target`` and not normalized by the image size. ``reduction='mean'`` (the default) averages
+ it over every position of every sample at once and ``'sum'`` adds it up, both into a 0-d tensor;
+ ``'none'`` returns the :math:`(*)` map. There is no valid mask: mask sparse ground truth on the ``'none'``
+ map. An unknown ``reduction`` raises ``NotImplementedError``.
+ - :func:`~kornia.metrics.aepe` and :func:`~kornia.metrics.average_endpoint_error` are the same function.
+
Args:
input: the input flow map with shape :math:`(*, 2)`.
target: the target flow map with shape :math:`(*, 2)`.
@@ -40,7 +52,7 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
in the output, ``'sum'``: the output will be summed.
Return:
- the computed AEPE as a scalar.
+ the computed AEPE as a 0-d tensor, or the endpoint-error map of shape :math:`(*)` for ``reduction='none'``.
Examples:
>>> ones = torch.ones(4, 4, 2)
@@ -83,6 +95,9 @@ class AEPE(nn.Module):
\text{AEPE}=\frac{1}{hw}\sum_{i=1, j=1}^{h, w}\sqrt{(I_{i,j,1}-T_{i,j,1})^{2}+(I_{i,j,2}-T_{i,j,2})^{2}}
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.aepe`, which this module calls with its ``reduction``.
+
Args:
reduction : Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
@@ -92,7 +107,7 @@ class AEPE(nn.Module):
Shape:
- input: :math:`(*, 2)`.
- target :math:`(*, 2)`.
- - output: :math:`(1)`.
+ - output: :math:`()` for ``'mean'`` and ``'sum'``, :math:`(*)` for ``'none'``.
Examples:
>>> input1 = torch.rand(1, 4, 5, 2)
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index c8bb4733e..96a067769 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -36,10 +36,31 @@ def mean_average_precision(
"""Calculate the Mean Average Precision (mAP) of detected objects.
Code altered from https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/utils.py#L271.
- Background class (0 index) is excluded. Only foreground classes with ground-truth objects
- across the evaluated images contribute to mAP. Classes without ground truth have undefined
- AP, represented by ``-1.0`` as in COCO. If no foreground class has ground truth, mAP is ``-1.0``.
- Classes with ground truth but no detections have AP ``0.0`` and contribute to mAP.
+
+ Convention:
+ - Every argument but ``n_classes`` and ``threshold`` is a list with one tensor per image. The call raises when
+ the five lists differ in length, when the boxes, labels and scores of an image differ in their number of
+ rows, or when a label lies outside ``[0, n_classes)``. Boxes are exclusive ``xyxy``, the default format of
+ :func:`~kornia.metrics.mean_iou_bbox`, which computes the overlaps.
+ - Class 0 is background: its objects and detections are never scored, and ``n_classes`` counts it, so the
+ classes ``1`` to ``n_classes - 1`` are scored.
+ - The detections of a class are ranked by score over all images at once, so the AP is not a mean of
+ per-image APs. In that order, a detection takes the object of its image and class that it overlaps most;
+ it is a true positive when that IoU is strictly greater than ``threshold`` and the object is not taken
+ yet, and a false positive otherwise. A class with objects and no detection has AP 0.
+ - A class without objects in any image has no AP: its entry is ``-1.0`` and it stays out of the mean, so
+ neither a larger ``n_classes`` nor detections of such a class change the mAP. Without any foreground
+ object the mAP is ``-1.0`` too.
+ - The AP is the 11-point interpolated AP of PASCAL VOC2007: the mean, over the recall levels
+ ``0, 0.1, ..., 1``, of the highest precision at a recall of at least that level.
+ - The result is a 0-d tensor and a dict of Python floats, fractions in :math:`[0, 1]` apart from that
+ ``-1.0``. The tensor takes the floating dtype of the boxes: integer boxes count as float32, and predicted
+ and ground-truth boxes of different dtypes give the promotion of those two floating dtypes (float32 when one
+ set is integer and the other float16). :ref:`Losses and metrics <losses-metrics-conventions>` compares the
+ match rule with the VOC devkit and COCO.
+ - Known defect: labels are checked for their range only, so a fractional label such as ``1.5`` matches no
+ class and its detections and objects are dropped without an error
+ (`#5629 <https://github.com/kornia/kornia/issues/5629>`_).
Args:
pred_boxes: a torch.Tensor list of predicted bounding boxes.
@@ -47,11 +68,11 @@ def mean_average_precision(
pred_scores: a torch.Tensor list of predicted labels' scores.
gt_boxes: a torch.Tensor list of ground truth bounding boxes.
gt_labels: a torch.Tensor list of ground truth labels in ``[0, n_classes)``.
- n_classes: the number of classes.
+ n_classes: the number of classes, background (class 0) included.
threshold: count as a positive if the overlap is greater than the threshold.
Returns:
- mean average precision (mAP), dictionary of average precisions for each foreground class.
+ the mAP, and a dict mapping each scored class id to its average precision.
Examples:
>>> boxes, labels, scores = torch.tensor([[100, 50, 150, 100.]]), torch.tensor([1]), torch.tensor([.7])
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index d9c41b78c..1d0fd37aa 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -23,24 +23,35 @@ from .confusion_matrix import confusion_matrix
def mean_iou(pred: torch.Tensor, target: torch.Tensor, num_classes: int, eps: float = 1e-6) -> torch.Tensor:
- r"""Calculate mean Intersection-Over-Union (mIOU).
+ r"""Calculate the Intersection-Over-Union (IoU) of every class in every sample.
The function internally computes the confusion matrix.
+ Convention:
+ - See the Convention block of :func:`~kornia.metrics.confusion_matrix`, which counts the labels: the same
+ label contract, one result per sample.
+ - The result is the IoU of every class in every sample, :math:`(B, K)` float32, each a fraction in
+ :math:`[0, 1]`; despite the name, neither axis is averaged. Averaging it over :math:`B` gives the mean of
+ per-image IoUs; for the IoU of a whole dataset, sum :func:`~kornia.metrics.confusion_matrix` over all
+ images and take the IoU of the sum.
+ - ``eps`` is added to the numerator and the denominator, so a class absent from both maps scores 1 (NaN with
+ ``eps=0``), and a class only predicted or only in the target scores about 0. Exclude absent classes before
+ averaging over :math:`K`: a larger ``num_classes`` can only raise the average.
+ :ref:`Losses and metrics <losses-metrics-conventions>` compares this absent-class rule with the losses,
+ :func:`~kornia.metrics.mean_average_precision` and scikit-learn.
+
Args:
pred : tensor with estimated targets returned by a
classifier. The shape can be :math:`(B, *)` and must contain integer
values between 0 and K-1.
target: tensor with ground truth (correct) target
- values. The shape can be :math:`(B, *)` and must contain integer
- values between 0 and K-1, where targets are assumed to be provided as
- one-hot vectors.
+ values. The shape must be that of ``pred``, and it must contain integer
+ values between 0 and K-1.
num_classes: total possible number of classes in target.
- eps: epsilon for numerical stability.
+ eps: the value added to the numerator and the denominator of every IoU.
Returns:
- a tensor representing the mean intersection-over union
- with shape :math:`(B, K)` where K is the number of classes.
+ a tensor with the IoU of every class, with shape :math:`(B, K)` where K is the number of classes.
Example:
>>> logits = torch.tensor([[0, 1, 0]])
@@ -100,6 +111,17 @@ def _promote_integer_boxes(boxes: torch.Tensor) -> torch.Tensor:
def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str = "xyxy") -> torch.Tensor:
"""Compute the IoU of the cartesian product of two sets of boxes.
+ Convention:
+ - The result is the IoU of every pair, :math:`(B1, B2)`, each a fraction in :math:`[0, 1]`; despite the name,
+ nothing is averaged, and swapping the two sets transposes it.
+ - Boxes are exclusive in every ``box_format``: the area of ``(x1, y1, x2, y2)`` is
+ :math:`(x_2 - x_1)(y_2 - y_1)`, with no ``+ 1``, as in :func:`~kornia.geometry.bbox.nms`. A box with a
+ non-positive width or height raises ``AssertionError``, unless the call is exported or compiled, which may
+ skip the check. A :class:`~kornia.geometry.boxes.Boxes` gives the same IoU through ``to_tensor('xyxy')``,
+ not through its inclusive ``'xyxy_plus'`` export.
+ - Known defect: a compiled call can skip that check, and an invalid box then gives an IoU of 0 or NaN instead
+ of raising (`#5037 <https://github.com/kornia/kornia/issues/5037>`_).
+
Args:
boxes_1: a tensor of bounding boxes in :math:`(B1, 4)`.
boxes_2: a tensor of bounding boxes in :math:`(B2, 4)`.
@@ -111,7 +133,7 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
Returns:
a tensor in dimensions :math:`(B1, B2)`, representing the
- intersection of each of the boxes in set 1 with respect to each of the boxes in set 2.
+ IoU of each of the boxes in set 1 with each of the boxes in set 2.
.. note::
Integer (and bool) boxes are computed in ``float32``, so the result is ``float32`` and widths, areas and the
diff --git a/kornia/metrics/pose.py b/kornia/metrics/pose.py
index 685b8bdfd..59c8bf2b3 100644
--- a/kornia/metrics/pose.py
+++ b/kornia/metrics/pose.py
@@ -58,6 +58,11 @@ def angle_error_mat(R1: Tensor, R2: Tensor) -> Tensor:
:math:`\arccos\!\big((\mathrm{tr}\,R - 1) / 2\big)` loses next to :math:`1`: in float32 the result
stays within about :math:`2 \cdot 10^{-5}` degrees of the exact angle over the whole range.
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.pose_errors`, whose ``"R_err"`` this is: one angle in
+ degrees per pair, symmetric in ``R1`` and ``R2``. An unbatched pair gives a 0-d tensor. The inputs are not
+ checked to be rotations.
+
Args:
R1: a rotation matrix of shape :math:`(*, 3, 3)`.
R2: a rotation matrix of shape :math:`(*, 3, 3)`.
@@ -98,6 +103,12 @@ def angle_error_vec(v1: Tensor, v2: Tensor) -> Tensor:
:math:`\arccos(\hat v_1 \cdot \hat v_2)` loses next to :math:`1`: in float32 the result stays within
about :math:`2 \cdot 10^{-5}` degrees of the exact angle over the whole range.
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.pose_errors`, whose ``"t_err"`` is this angle before
+ folding: one angle in degrees per pair, symmetric in ``v1`` and ``v2`` up to roundoff. An unbatched pair gives
+ a 0-d tensor. Only the directions are compared, so the vectors need not have unit length. The angle is not
+ folded: opposite vectors give 180.
+
Args:
v1: a vector of shape :math:`(*, 3)`.
v2: a vector of shape :math:`(*, 3)`.
@@ -142,6 +153,11 @@ def translation_ate(t: Tensor, t_gt: Tensor) -> Tensor:
translations share a common metric scale (it is **not** scale-invariant, so it is not suitable
for raw essential-matrix translations).
+ Convention:
+ See the Convention block of :func:`~kornia.metrics.pose_errors`, whose ``"t_err"`` compares translation
+ directions only; this function keeps the magnitude. The result is one distance per sample, in the units of
+ the translations, with no alignment: a trajectory shifted by a constant keeps that offset at every pose.
+
Args:
t: an estimated translation of shape :math:`(*, 3)`.
t_gt: a ground-truth translation of the same shape as ``t``.
@@ -173,6 +189,14 @@ def translation_ate(t: Tensor, t_gt: Tensor) -> Tensor:
def pose_errors(P: Tensor, P_gt: Tensor, fold_translation: bool = True) -> dict[str, Tensor]:
r"""Rotation and translation angular error (in degrees) between two relative poses.
+ Convention:
+ - Every error is an angle in **degrees**, one per pose and never averaged over the batch; an unbatched pose
+ gives shape :math:`(1,)`, where :func:`~kornia.metrics.angle_error_mat` gives a 0-d tensor.
+ - ``"R_err"`` is :func:`~kornia.metrics.angle_error_mat` of the two rotation blocks and is never folded.
+ ``"t_err"`` is :func:`~kornia.metrics.angle_error_vec` of the two translations, so it compares their
+ directions only, folded as ``fold_translation`` says. ``"max_err"`` is the larger of the two per pose.
+ - Only the top three rows are read: the bottom row of a :math:`(4, 4)` pose is ignored.
+
Args:
P: an estimated relative pose ``[R | t]`` of shape :math:`(3, 4)`, :math:`(4, 4)`, or batched
:math:`(B, 3, 4)` / :math:`(B, 4, 4)`.
@@ -220,6 +244,16 @@ def auc_from_errors(errors: Tensor, thresholds: float | Sequence[float] = (1, 3,
``"max_err"`` of :func:`pose_errors`) are one common source, but the thresholds simply need to be
in the same units as ``errors``.
+ Convention:
+ - See the Convention block of :func:`~kornia.metrics.pose_errors`, whose ``"max_err"`` is the usual input.
+ - All errors are pooled into one curve, whatever their shape. The recall curve rises by :math:`1/n` at each
+ of the :math:`n` sorted errors, joined to :math:`(0, 0)` and to each other by straight lines (the trapezoid
+ rule), and is held flat from the last error below the threshold out to the threshold. The AUC is its area
+ divided by the threshold, times 100: a **percentage**, keyed by the threshold as a Python float. An ``inf``
+ error never enters the area, so it counts as a failure. :ref:`Losses and metrics
+ <losses-metrics-conventions>` maps the AUC and :func:`~kornia.metrics.pose_errors` onto glue-factory and
+ SuperGlue.
+
Args:
errors: per-sample error values of shape :math:`(B,)`. Must be non-negative. Integer and
half-precision inputs are promoted to the default floating dtype before accumulating.
diff --git a/tests/metrics/test_accuracy.py b/tests/metrics/test_accuracy.py
index f2ccb89aa..ce2cdd50e 100644
--- a/tests/metrics/test_accuracy.py
+++ b/tests/metrics/test_accuracy.py
@@ -17,10 +17,14 @@
from __future__ import annotations
+import pytest
import torch
+import kornia
from kornia.metrics import accuracy
+from testing.base import BaseTester, supports_topk
+
class TestAccuracy:
def test_top1_perfect(self):
@@ -55,3 +59,32 @@ class TestAccuracy:
target = torch.tensor([[1]])
result = accuracy(logits, target, topk=(5,))
assert result[0].item() == 100.0
+
+
+class TestConventionsAccuracy(BaseTester):
+ def test_convention_accuracy_is_a_percentage_per_topk(self, device, dtype):
+ """accuracy returns a list of 0-d float32 percentages, one per entry of topk and in its order."""
+ if not supports_topk(device, dtype):
+ pytest.skip(f"this torch build has no topk kernel for {dtype} on {device.type}")
+ # Four samples, three classes. The target is the 1st, 3rd, 1st and 2nd highest score, so top-1 hits 2 of 4,
+ # top-2 hits 3 and top-3 hits 4. scikit-learn 1.9.0 gives the fractions: accuracy_score -> 0.5,
+ # top_k_accuracy_score(k=2) -> 0.75; kornia reports them as percentages.
+ logits = torch.tensor(
+ [[0.1, 0.7, 0.2], [0.6, 0.3, 0.1], [0.2, 0.3, 0.5], [0.5, 0.1, 0.4]], device=device, dtype=dtype
+ )
+ target = torch.tensor([1, 2, 2, 2], device=device)
+ out = kornia.metrics.accuracy(logits, target, topk=(1, 2, 3, 5))
+ assert isinstance(out, list)
+ assert len(out) == 4
+ assert all(value.shape == () and value.dtype == torch.float32 for value in out)
+ # k larger than the number of classes is clipped to it, so top-5 of 3 classes is 100
+ self.assert_close(torch.stack(out), torch.tensor([50.0, 75.0, 100.0, 100.0], device=device))
+ # the list follows the order of topk; a (B, 1) target is read like a (B,) one
+ swapped = kornia.metrics.accuracy(logits, target[:, None], topk=(2, 1))
+ self.assert_close(torch.stack(swapped), torch.tensor([75.0, 50.0], device=device))
+ # relabel: renaming class c to perm[c] in the scores and the targets alike leaves the result unchanged
+ perm = torch.tensor([2, 0, 1], device=device)
+ relabelled = torch.empty_like(logits)
+ relabelled[:, perm] = logits
+ out_relabelled = kornia.metrics.accuracy(relabelled, perm[target], topk=(1, 2))
+ self.assert_close(torch.stack(out_relabelled), torch.tensor([50.0, 75.0], device=device))
diff --git a/tests/metrics/test_aepe.py b/tests/metrics/test_aepe.py
index d2305a368..85f2884f1 100644
--- a/tests/metrics/test_aepe.py
+++ b/tests/metrics/test_aepe.py
@@ -19,6 +19,7 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import BaseError
from testing.base import BaseTester
@@ -87,3 +88,33 @@ class TestAepe(BaseTester):
criterion = kornia.metrics.AEPE()
assert criterion(input, target) is not None
+
+
+class TestConventionsAepe(BaseTester):
+ def test_convention_aepe_flow_is_channel_last_and_pools_every_element(self, device, dtype):
+ """aepe reads (*, 2) flow in pixels; 'mean' averages the endpoint error over every pixel of every sample."""
+ # (B, H, W, 2) = (2, 3, 4, 2). Sample 0: one pixel off by (3, 4), error 5; sample 1: two pixels off by 1.
+ target = torch.zeros(2, 3, 4, 2, device=device, dtype=dtype)
+ flow = target.clone()
+ flow[0, 1, 2] = flow.new_tensor([3.0, 4.0])
+ flow[1, 2, 3] = flow.new_tensor([0.0, -1.0])
+ flow[1, 0, 0] = flow.new_tensor([1.0, 0.0])
+ # (5 + 1 + 1) / 24 pixels; the sum is 7 px, not normalised by the image size
+ mean = kornia.metrics.aepe(flow, target)
+ assert mean.shape == ()
+ self.assert_close(mean, torch.tensor(7.0 / 24.0, device=device, dtype=dtype))
+ self.assert_close(
+ kornia.metrics.aepe(flow, target, reduction="sum"), torch.tensor(7.0, device=device, dtype=dtype)
+ )
+ epe = kornia.metrics.aepe(flow, target, reduction="none")
+ assert epe.shape == (2, 3, 4)
+ expected = torch.zeros(2, 3, 4, device=device, dtype=dtype)
+ expected[0, 1, 2], expected[1, 2, 3], expected[1, 0, 0] = 5.0, 1.0, 1.0
+ self.assert_close(epe, expected)
+ # a channel-first (B, 2, H, W) flow, as RAFT and torchvision store it, is rejected here because W = 4 != 2 (with
+ # W == 2 it is accepted and read wrongly): permute it to (B, H, W, 2)
+ with pytest.raises((ValueError, BaseError)):
+ kornia.metrics.aepe(flow.permute(0, 3, 1, 2), target.permute(0, 3, 1, 2))
+ # average_endpoint_error is aepe itself, and AEPE(reduction) calls it
+ assert kornia.metrics.average_endpoint_error is kornia.metrics.aepe
+ self.assert_close(kornia.metrics.AEPE("sum")(flow, target), torch.tensor(7.0, device=device, dtype=dtype))
diff --git a/tests/metrics/test_average_meter.py b/tests/metrics/test_average_meter.py
index 0b09d0f60..7627d6ab0 100644
--- a/tests/metrics/test_average_meter.py
+++ b/tests/metrics/test_average_meter.py
@@ -17,10 +17,14 @@
from __future__ import annotations
+import pytest
import torch
+import kornia
from kornia.metrics import AverageMeter
+from testing.base import BaseTester, supports_topk
+
class TestAverageMeter:
def test_initial_state(self):
@@ -55,3 +59,31 @@ class TestAverageMeter:
assert m.val == 0
assert m.avg == 0
assert m.count == 0
+
+
+class TestConventionsAverageMeter(BaseTester):
+ def test_convention_average_meter_weights_each_value_by_n(self, device, dtype):
+ """update(val, n) adds val * n to sum and n to count: avg is the n-weighted mean, in the caller's units."""
+ meter = AverageMeter()
+ meter.update(torch.tensor(0.75, device=device, dtype=dtype), n=4)
+ meter.update(torch.tensor(0.5, device=device, dtype=dtype), n=1)
+ # (0.75 * 4 + 0.5 * 1) / 5 = 0.7, not the unweighted (0.75 + 0.5) / 2 = 0.625
+ assert isinstance(meter.avg, float)
+ self.assert_close(torch.tensor(meter.avg, dtype=dtype), torch.tensor(0.7, dtype=dtype))
+ assert meter.count == 5
+ self.assert_close(meter.sum, torch.tensor(3.5, device=device, dtype=dtype))
+ # val is the last raw value, not weighted
+ self.assert_close(meter.val, torch.tensor(0.5, device=device, dtype=dtype))
+ # a tensor val keeps its autograd graph in sum
+ graph = AverageMeter()
+ graph.update(torch.tensor(0.5, device=device, dtype=dtype, requires_grad=True) * 2, n=3)
+ assert graph.sum.requires_grad
+
+ def test_convention_average_meter_keeps_the_callers_scale(self, device, dtype):
+ """AverageMeter does not rescale: accuracy's percentage stays a percentage."""
+ if not supports_topk(device, dtype):
+ pytest.skip(f"this torch build has no topk kernel for {dtype} on {device.type}")
+ percent = AverageMeter()
+ logits = torch.tensor([[0.1, 0.9], [0.8, 0.2]], device=device, dtype=dtype)
+ percent.update(kornia.metrics.accuracy(logits, torch.tensor([1, 1], device=device))[0], n=2)
+ assert percent.avg == 50.0
diff --git a/tests/metrics/test_confusion.py b/tests/metrics/test_confusion.py
index 5835270ba..1a7748f5b 100644
--- a/tests/metrics/test_confusion.py
+++ b/tests/metrics/test_confusion.py
@@ -244,3 +244,34 @@ class TestConfusionMatrix(BaseTester):
exported = torch.export.export(_ConfusionMatrix(), (pred, target), strict=True).module()
for p, t in ((pred, target), (target, pred.flip(-1))):
self.assert_close(exported(p, t), kornia.metrics.confusion_matrix(p, t, num_classes=3), rtol=0, atol=0)
+
+
+class TestConventionsConfusionMatrix(BaseTester):
+ # Two (H, W) = (3, 4) label maps, three classes; the class counts differ between target and prediction (rows 3, 5,
+ # 4 against columns 3, 4, 5 in sample 0) and between the two samples.
+ PRED = [[[0, 0, 1, 2], [1, 1, 2, 2], [0, 2, 2, 1]], [[2, 2, 2, 2], [0, 1, 1, 0], [0, 0, 1, 2]]]
+ TARGET = [[[0, 1, 1, 2], [1, 1, 1, 2], [0, 0, 2, 2]], [[2, 2, 1, 1], [0, 0, 1, 0], [1, 0, 1, 2]]]
+
+ def test_convention_confusion_matrix_rows_are_targets_per_sample(self, device, dtype):
+ """confusion_matrix returns one float32 count matrix per sample, cm[b, target, prediction]."""
+ pred = torch.tensor(self.PRED, device=device)
+ target = torch.tensor(self.TARGET, device=device)
+ # Snippet used to generate expected (scikit-learn 1.9.0, same orientation: rows y_true, columns y_pred):
+ # [sklearn.metrics.confusion_matrix(np.ravel(t), np.ravel(p), labels=[0, 1, 2]) for p, t in zip(PRED, TARGET)]
+ expected = torch.tensor(
+ [[[2.0, 0.0, 1.0], [1.0, 3.0, 1.0], [0.0, 1.0, 3.0]], [[3.0, 1.0, 0.0], [1.0, 2.0, 2.0], [0.0, 0.0, 3.0]]],
+ device=device,
+ )
+ cm = kornia.metrics.confusion_matrix(pred, target, 3)
+ assert cm.dtype == torch.float32
+ self.assert_close(cm, expected)
+ # swapping the arguments transposes every matrix
+ self.assert_close(kornia.metrics.confusion_matrix(target, pred, 3), expected.transpose(-2, -1))
+ # relabel: renaming class c to perm[c] in both maps permutes the rows and the columns alike
+ perm = torch.tensor([2, 0, 1], device=device)
+ inv = torch.argsort(perm)
+ self.assert_close(kornia.metrics.confusion_matrix(perm[pred], perm[target], 3), expected[:, inv][:, :, inv])
+ # the first axis is always the batch: a flat (N,) label vector gives N one-pixel matrices, not one matrix
+ flat = kornia.metrics.confusion_matrix(pred[0, 0], target[0, 0], 3)
+ assert flat.shape == (4, 3, 3)
+ self.assert_close(flat.sum(0), torch.tensor([[1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device))
diff --git a/tests/metrics/test_disparity.py b/tests/metrics/test_disparity.py
index 17a3ef8e2..adf03660f 100644
--- a/tests/metrics/test_disparity.py
+++ b/tests/metrics/test_disparity.py
@@ -586,3 +586,75 @@ class TestKittiD1Error(BaseTester):
op = kornia.metrics.kitti_d1_error
op_optimized = torch_optimizer(op)
self.assert_close(op(input, target, 3.0, 0.05, mask), op_optimized(input, target, 3.0, 0.05, mask))
+
+
+class TestConventionsDisparity(BaseTester):
+ # Two (H, W) = (3, 4) maps. Sample 0: all 12 pixels valid, errors 4, 3 and 2 px on disparities 10, 60 and 45.
+ # Sample 1: only the first row valid, errors 4 px on 100 (4 %) and 6 px on 90 (6.7 %); its masked rows hide a
+ # 1 px error on a disparity of 5.
+ TARGET = [
+ [[10.0, 20.0, 30.0, 40.0], [50.0, 60.0, 70.0, 80.0], [15.0, 25.0, 35.0, 45.0]],
+ [[100.0, 90.0, 80.0, 70.0], [60.0, 50.0, 40.0, 30.0], [20.0, 10.0, 5.0, 1.0]],
+ ]
+ INPUT = [
+ [[14.0, 20.0, 30.0, 40.0], [50.0, 63.0, 70.0, 80.0], [15.0, 25.0, 35.0, 47.0]],
+ [[104.0, 96.0, 80.0, 70.0], [60.0, 50.0, 40.0, 30.0], [20.0, 10.0, 6.0, 1.0]],
+ ]
+
+ def _sample(self, device, dtype):
+ input = torch.tensor(self.INPUT, device=device, dtype=dtype)
+ target = torch.tensor(self.TARGET, device=device, dtype=dtype)
+ mask = torch.ones(2, 3, 4, device=device, dtype=torch.bool)
+ mask[1, 1:] = False
+ return input, target, mask
+
+ def test_convention_disparity_metrics_pool_every_valid_pixel_of_the_batch(self, device, dtype):
+ """The four metrics pool the valid pixels of all images into one value; bad-pixel and D1 are fractions."""
+ input, target, mask = self._sample(device, dtype)
+ # Pooled over the 16 valid pixels, against the mean of the two per-image values:
+ # MAE (4 + 3 + 2 + 4 + 6) / 16 = 1.1875, not (9/12 + 10/4) / 2 = 1.625
+ # RMSE sqrt((16 + 9 + 4 + 16 + 36) / 16) = 2.25, not (sqrt(29/12) + sqrt(52/4)) / 2 = 2.5801
+ # bad 3 / 16 = 0.1875 (the 3 px error is not > 3), not (1/12 + 2/4) / 2 = 0.2917
+ # D1 2 / 16 = 0.125 (4 px on 100 is not > 5 %), not (1/12 + 1/4) / 2 = 0.1667
+ # The KITTI devkit (evaluate_scene_flow.cpp lines 51, 487, 673) sums the outlier and pixel counts over the
+ # images before dividing: D1 = 0.125 here.
+ expected = {
+ kornia.metrics.mean_absolute_disparity_error: 1.1875,
+ kornia.metrics.root_mean_squared_disparity_error: 2.25,
+ kornia.metrics.mean_bad_pixel_error: 0.1875,
+ kornia.metrics.kitti_d1_error: 0.125,
+ }
+ for metric, value in expected.items():
+ pooled = metric(input, target, valid_mask=mask)
+ assert pooled.shape == ()
+ self.assert_close(pooled, torch.tensor(value, device=device, dtype=dtype))
+ assert metric(input, target, valid_mask=mask, reduction="none").shape == (2, 3, 4)
+ # A NaN at a valid pixel, input[0, 0, 0] (a bad pixel and a D1 outlier above), propagates into MAE and RMSE,
+ # while bad-pixel and D1 count it as a good pixel: 2 / 16 and 1 / 16.
+ nan_input = input.clone()
+ nan_input[0, 0, 0] = float("nan")
+ assert torch.isnan(kornia.metrics.mean_absolute_disparity_error(nan_input, target, valid_mask=mask))
+ assert torch.isnan(kornia.metrics.root_mean_squared_disparity_error(nan_input, target, valid_mask=mask))
+ self.assert_close(
+ kornia.metrics.mean_bad_pixel_error(nan_input, target, valid_mask=mask),
+ torch.tensor(0.125, device=device, dtype=dtype),
+ )
+ self.assert_close(
+ kornia.metrics.kitti_d1_error(nan_input, target, valid_mask=mask),
+ torch.tensor(0.0625, device=device, dtype=dtype),
+ )
+
+ def test_convention_disparity_valid_mask_broadcasts_from_the_right(self, device, dtype):
+ """valid_mask is broadcast to the input from the right: (H, W) masks every image, (B, 1, 1) whole images."""
+ input, target, _ = self._sample(device, dtype)
+ metric = kornia.metrics.mean_absolute_disparity_error
+ # (H, W): the first row of both images, errors 4 | 4 and 6 over 8 pixels
+ first_row = torch.zeros(3, 4, device=device, dtype=torch.bool)
+ first_row[0] = True
+ self.assert_close(metric(input, target, valid_mask=first_row), torch.tensor(1.75, device=device, dtype=dtype))
+ # (B, 1, 1): image 0 only, 9 px over its 12 pixels
+ image_0 = torch.tensor([True, False], device=device).view(2, 1, 1)
+ self.assert_close(metric(input, target, valid_mask=image_0), torch.tensor(0.75, device=device, dtype=dtype))
+ # a (B,) mask is aligned with W, not with the batch: rejected here since W = 4 != B = 2 (W == B would broadcast)
+ with pytest.raises((ValueError, BaseError)):
+ metric(input, target, valid_mask=torch.tensor([True, False], device=device))
diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.py
index f1131da5d..30741c1b4 100644
--- a/tests/metrics/test_map.py
+++ b/tests/metrics/test_map.py
@@ -348,3 +348,124 @@ class TestMeanAveragePrecision(BaseTester):
expected = torch.tensor((1.0 + sum(2 * i / (4 * i - 1) for i in range(1, 11))) / 11, device=device, dtype=dtype)
self.assert_close(mean_ap, expected)
self.assert_close(torch.tensor(ap[1], device=device, dtype=dtype), expected)
+
+
+class TestConventionsMeanAveragePrecision(BaseTester):
+ BOX_1 = [0.0, 0.0, 10.0, 20.0] # 10 x 20
+ BOX_2 = [30.0, 30.0, 45.0, 40.0] # 15 x 10
+ FAR = [100.0, 100.0, 120.0, 110.0] # overlaps nothing
+
+ @staticmethod
+ def _map(device, dtype, pred_boxes, pred_labels, pred_scores, gt_boxes, gt_labels, n_classes, threshold=0.5):
+ """Run mean_average_precision on per-image lists of Python lists."""
+ return kornia.metrics.mean_average_precision(
+ [torch.tensor(b, device=device, dtype=dtype) for b in pred_boxes],
+ [torch.tensor(lbl, device=device, dtype=torch.long) for lbl in pred_labels],
+ [torch.tensor(s, device=device, dtype=dtype) for s in pred_scores],
+ [torch.tensor(b, device=device, dtype=dtype) for b in gt_boxes],
+ [torch.tensor(lbl, device=device, dtype=torch.long) for lbl in gt_labels],
+ n_classes,
+ threshold,
+ )
+
+ def _assert_aps(self, ap, expected, device, dtype):
+ """Compare the per-class dict: the same class ids, and values close in the box dtype."""
+ assert sorted(ap) == sorted(expected)
+ keys = sorted(expected)
+ self.assert_close(
+ torch.tensor([ap[k] for k in keys], device=device, dtype=dtype),
+ torch.tensor([expected[k] for k in keys], device=device, dtype=dtype),
+ )
+
+ def test_convention_mean_average_precision_pools_detections_over_images(self, device, dtype):
+ """mAP ranks the detections of a class over all images at once and returns (0-d mAP, {class: AP}) fractions."""
+ # Image A: one exact detection (score 0.5). Image B: a false positive (0.9), then an exact detection (0.3).
+ # Pooled ranking FP, TP, TP over 2 objects: precision 2/3 at recall 1, so AP = 2/3. Image by image the APs
+ # are 1 and 1/2 (mean 3/4). COCO (pycocotools 2.0.11 via torchmetrics 1.9.0) also pools: 0.666667.
+ mean_ap, ap = self._map(
+ device,
+ dtype,
+ [[self.BOX_1], [self.FAR, self.BOX_2]],
+ [[1], [1, 1]],
+ [[0.5], [0.9, 0.3]],
+ [[self.BOX_1], [self.BOX_2]],
+ [[1], [1]],
+ 2,
+ )
+ assert mean_ap.shape == ()
+ assert mean_ap.dtype == dtype
+ self.assert_close(mean_ap, torch.tensor(2.0 / 3.0, device=device, dtype=dtype))
+ assert isinstance(ap, dict)
+ assert isinstance(ap[1], float)
+ self._assert_aps(ap, {1: 2.0 / 3.0}, device, dtype)
+
+ def test_convention_mean_average_precision_class_zero_is_background(self, device, dtype):
+ """Classes 1 ... n_classes - 1 are scored; class 0 objects and detections are never looked at."""
+ # Class 0 has an object that nobody detects and a confident detection on the class-1 box; scored like any
+ # class (as COCO does) it would add AP 0. Class 1: one exact detection, AP 1. Class 2: a false positive ranked
+ # above the exact detection, precision 1/2 at recall 1, AP 1/2.
+ class_zero_box = [50.0, 0.0, 60.0, 30.0]
+ pred = ([[self.BOX_1, self.BOX_1, self.FAR, self.BOX_2]], [[0.99, 0.9, 0.95, 0.6]])
+ gt_boxes = [[class_zero_box, self.BOX_1, self.BOX_2]]
+ for c1, c2 in ((1, 2), (2, 1)): # relabel: swapping classes 1 and 2 swaps their entries, the mAP stays
+ mean_ap, ap = self._map(device, dtype, pred[0], [[0, c1, c2, c2]], pred[1], gt_boxes, [[0, c1, c2]], 3)
+ self.assert_close(mean_ap, torch.tensor(0.75, device=device, dtype=dtype))
+ self._assert_aps(ap, {c1: 1.0, c2: 0.5}, device, dtype)
+
+ def test_convention_mean_average_precision_missed_class_scores_zero(self, device, dtype):
+ """A class with ground truth and no detection has AP 0 and enters the mean, as in COCO."""
+ # COCO (pycocotools 2.0.11 via torchmetrics 1.9.0) gives the same (0.5, {1: 1.0, 2: 0.0})
+ mean_ap, ap = self._map(device, dtype, [[self.BOX_1]], [[1]], [[0.9]], [[self.BOX_1, self.BOX_2]], [[1, 2]], 3)
+ self.assert_close(mean_ap, torch.tensor(0.5, device=device, dtype=dtype))
+ self._assert_aps(ap, {1: 1.0, 2: 0.0}, device, dtype)
+
+ def test_convention_mean_average_precision_iou_must_exceed_threshold(self, device, dtype):
+ """A detection matches only when its IoU is strictly greater than threshold."""
+ # [0, 0, 10, 10] against the 10 x 20 box: IoU exactly 0.5. py-faster-rcnn's voc_eval uses the same `>`, but its
+ # +1 areas give this pair IoU 0.524, so py-faster-rcnn, the VOC devkit (VOCevaldet.m `ovmax >= minoverlap`) and
+ # COCO all count it as a match (AP 1).
+ half_box = [[[0.0, 0.0, 10.0, 10.0]]]
+ for threshold, expected in ((0.5, 0.0), (0.4999, 1.0)):
+ mean_ap, ap = self._map(device, dtype, half_box, [[1]], [[0.9]], [[self.BOX_1]], [[1]], 2, threshold)
+ self.assert_close(mean_ap, torch.tensor(expected, device=device, dtype=dtype))
+ self._assert_aps(ap, {1: expected}, device, dtype)
+
+ def test_convention_mean_average_precision_greedy_voc_matching(self, device, dtype):
+ """A detection takes its highest-IoU object; if that one is already matched, it is a false positive."""
+ objects = [[[0.0, 0.0, 10.0, 10.0], [0.0, 0.0, 10.0, 16.0]]]
+ # The second detection overlaps the first object (IoU 10/11) more than the second one (IoU 0.6875 > 0.5). The
+ # first object is taken, so it is a false positive: TP, FP over 2 objects -> recall 1/2 at precision 1 ->
+ # 6 of the 11 recall thresholds -> AP 6/11. COCO matches it to the free second object instead: AP 1.
+ detections = [[[0.0, 0.0, 10.0, 10.0], [0.0, 0.0, 10.0, 11.0]]]
+ mean_ap, _ = self._map(device, dtype, detections, [[1, 1]], [[0.9, 0.8]], objects, [[1, 1]], 2)
+ self.assert_close(mean_ap, torch.tensor(6.0 / 11.0, device=device, dtype=dtype))
+ # The highest-IoU object, not the first one above the threshold: each detection equals one object and overlaps
+ # the other at IoU 5/6, so both are true positives -> AP 1. Taking the first object above the threshold would
+ # match the second detection to the taken first object, a false positive -> AP 6/11.
+ objects = [[[0.0, 0.0, 10.0, 10.0], [0.0, 0.0, 10.0, 12.0]]]
+ mean_ap, _ = self._map(device, dtype, objects, [[1, 1]], [[0.9, 0.8]], objects, [[1, 1]], 2)
+ self.assert_close(mean_ap, torch.tensor(1.0, device=device, dtype=dtype))
+
+ def test_wart_mean_average_precision_drops_fractional_labels_5629(self, device, dtype):
+ """A fractional label passes the range check and matches no class, so its boxes are dropped (#5629)."""
+ boxes = [torch.tensor([self.BOX_1, self.BOX_2], device=device, dtype=dtype)]
+ scores = [torch.tensor([0.9, 0.8], device=device, dtype=dtype)]
+
+ def run(labels):
+ labels = [torch.tensor(labels, device=device, dtype=dtype)]
+ return kornia.metrics.mean_average_precision(boxes, labels, scores, boxes, labels, 3)
+
+ # control: integer-valued floating-point labels give the result of int64 labels, two perfect classes
+ expected_map, expected_ap = kornia.metrics.mean_average_precision(
+ boxes, [torch.tensor([1, 2], device=device)], scores, boxes, [torch.tensor([1, 2], device=device)], 3
+ )
+ mean_ap, ap = run([1.0, 2.0])
+ self.assert_close(mean_ap, expected_map)
+ self._assert_aps(ap, expected_ap, device, dtype)
+ self._assert_aps(ap, {1: 1.0, 2: 1.0}, device, dtype)
+ # label 1.25 (exact in every float dtype; rounding or truncating it gives class 1, so those changes flip this
+ # pin too): its detection and its object enter no class, so class 1 reads "no objects" (-1) and the mAP is
+ # class 2's alone, without an error
+ mean_ap, ap = run([1.25, 2.0])
+ self.assert_close(mean_ap, torch.tensor(1.0, device=device, dtype=dtype))
+ self._assert_aps(ap, {1: -1.0, 2: 1.0}, device, dtype)
diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.py
index ab30ca9b9..8ca5983f0 100644
--- a/tests/metrics/test_mean_iou.py
+++ b/tests/metrics/test_mean_iou.py
@@ -316,3 +316,68 @@ class TestMeanIoUBBox(BaseTester):
actual = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2)
assert actual.dtype == torch.float32
self.assert_close(actual, torch.tensor([[1.0]], device=device))
+
+
+class TestConventionsMeanIoU(BaseTester):
+ # The label maps of TestConventionsConfusionMatrix: confusion matrices [[2, 0, 1], [1, 3, 1], [0, 1, 3]] and
+ # [[3, 1, 0], [1, 2, 2], [0, 0, 3]] (rows = target).
+ PRED = [[[0, 0, 1, 2], [1, 1, 2, 2], [0, 2, 2, 1]], [[2, 2, 2, 2], [0, 1, 1, 0], [0, 0, 1, 2]]]
+ TARGET = [[[0, 1, 1, 2], [1, 1, 1, 2], [0, 0, 2, 2]], [[2, 2, 1, 1], [0, 0, 1, 0], [1, 0, 1, 2]]]
+
+ def test_convention_mean_iou_is_per_sample_per_class(self, device, dtype):
+ """mean_iou returns the IoU of every class in every sample, (B, K) float32; it averages neither axis."""
+ pred = torch.tensor(self.PRED, device=device)
+ target = torch.tensor(self.TARGET, device=device)
+ # IoU_k = TP / (TP + FP + FN) per sample: sample 0 gives 2/4, 3/6, 3/6; sample 1 gives 3/5, 2/6, 3/5
+ expected = torch.tensor([[0.5, 0.5, 0.5], [0.6, 1.0 / 3.0, 0.6]], device=device)
+ iou = kornia.metrics.mean_iou(pred, target, 3)
+ assert iou.shape == (2, 3)
+ assert iou.dtype == torch.float32
+ self.assert_close(iou, expected)
+ # relabel: renaming class c to perm[c] in both maps permutes the columns
+ perm = torch.tensor([2, 0, 1], device=device)
+ self.assert_close(kornia.metrics.mean_iou(perm[pred], perm[target], 3), expected[:, torch.argsort(perm)])
+
+ def test_convention_mean_iou_absent_class_scores_one(self, device, dtype):
+ """A class in neither map scores (0 + eps) / (0 + eps) = 1; a class only predicted scores about 0."""
+ pred = torch.tensor([[0, 0, 1, 1]], device=device)
+ target = torch.tensor([[0, 1, 1, 1]], device=device)
+ # classes 0 and 1: 1/2 and 2/3; class 2 is absent from both maps. scikit-learn 1.9.0 jaccard_score gives 0 there
+ # (with a warning) and torchmetrics 1.9.0 leaves it out of its macro average.
+ self.assert_close(
+ kornia.metrics.mean_iou(pred, target, 3), torch.tensor([[0.5, 2.0 / 3.0, 1.0]], device=device)
+ )
+ # a larger num_classes appends absent classes at 1, which raises the class average (0.7222 -> 0.7917)
+ self.assert_close(kornia.metrics.mean_iou(pred, target, 4)[0, 2:], torch.ones(2, device=device))
+ # the 1 comes from eps: eps=0 leaves 0 / 0
+ assert torch.isnan(kornia.metrics.mean_iou(pred, target, 3, eps=0.0)[0, 2])
+ # a class predicted once and never in the target scores eps / (1 + eps)
+ predicted_only = kornia.metrics.mean_iou(torch.tensor([[0, 2, 1, 1]], device=device), target, 3)
+ assert 0.0 < predicted_only[0, 2] < 1e-5
+
+ def test_convention_mean_iou_bbox_is_pairwise_and_exclusive(self, device, dtype):
+ """mean_iou_bbox returns the (N1, N2) IoU of every pair; boxes are exclusive, area (x2 - x1) * (y2 - y1)."""
+ boxes_1 = torch.tensor([[0.0, 0.0, 2.0, 2.0], [10.0, 20.0, 40.0, 30.0]], device=device, dtype=dtype)
+ boxes_2 = torch.tensor(
+ [[1.0, 1.0, 3.0, 3.0], [20.0, 20.0, 40.0, 30.0], [10.0, 20.0, 40.0, 25.0]], device=device, dtype=dtype
+ )
+ # [0, 0, 2, 2] and [1, 1, 3, 3] overlap in 1 of 4 + 4 - 1 = 7 (the VOC devkit's inclusive +1 areas give 4 / 14);
+ # the 30 x 10 box covers the 20 x 10 one (2 / 3) and the 30 x 5 one (1 / 2). torchvision 0.29.0
+ # box_iou(boxes_1, boxes_2) returns the same matrix.
+ expected = torch.tensor([[1.0 / 7.0, 0.0, 0.0], [0.0, 2.0 / 3.0, 0.5]], device=device, dtype=dtype)
+ iou = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2)
+ assert iou.shape == (2, 3)
+ assert iou.dtype == dtype
+ self.assert_close(iou, expected)
+ # swapping the two sets transposes the matrix
+ self.assert_close(kornia.metrics.mean_iou_bbox(boxes_2, boxes_1), expected.T)
+
+ # the same boxes in the two other formats give the same matrix
+ def to_xywh(boxes):
+ return torch.cat([boxes[:, :2], boxes[:, 2:] - boxes[:, :2]], 1)
+
+ def to_cxcywh(boxes):
+ return torch.cat([(boxes[:, :2] + boxes[:, 2:]) / 2, boxes[:, 2:] - boxes[:, :2]], 1)
+
+ self.assert_close(kornia.metrics.mean_iou_bbox(to_xywh(boxes_1), to_xywh(boxes_2), "xywh"), expected)
+ self.assert_close(kornia.metrics.mean_iou_bbox(to_cxcywh(boxes_1), to_cxcywh(boxes_2), "cxcywh"), expected)
diff --git a/tests/metrics/test_pose.py b/tests/metrics/test_pose.py
index bd54d37b5..8fad1e23e 100644
--- a/tests/metrics/test_pose.py
+++ b/tests/metrics/test_pose.py
@@ -320,3 +320,90 @@ class TestAucFromErrors(BaseTester):
expected = kornia.metrics.auc_from_errors(flat, thresholds=5.0)[5.0]
assert math.isclose(kornia.metrics.auc_from_errors(shuffled, thresholds=5.0)[5.0], expected, abs_tol=1e-3)
assert math.isclose(kornia.metrics.auc_from_errors(two_d, thresholds=5.0)[5.0], expected, abs_tol=1e-3)
+
+
+def _rotation(axis, degrees):
+ """Rotation matrix about ``axis`` by ``degrees`` (Rodrigues' formula), built in float64 on the CPU."""
+ a = torch.tensor(axis, dtype=torch.float64)
+ a = a / a.norm()
+ k = torch.tensor([[0.0, -a[2], a[1]], [a[2], 0.0, -a[0]], [-a[1], a[0], 0.0]], dtype=torch.float64)
+ theta = math.radians(degrees)
+ return torch.eye(3, dtype=torch.float64) + math.sin(theta) * k + (1.0 - math.cos(theta)) * (k @ k)
+
+
+class TestConventionsPose(BaseTester):
+ def test_convention_angle_errors_are_in_degrees(self, device, dtype):
+ """angle_error_mat is the geodesic angle of R1^T R2 in degrees, symmetric; angle_error_vec is in degrees too."""
+ R1 = _rotation([0.3, -0.5, 0.8], 40.0)
+ R2 = R1 @ _rotation([1.0, 2.0, -0.5], 60.0)
+ R1, R2 = R1.to(device, dtype), R2.to(device, dtype)
+ # glue-factory 2d17e3b and SuperGlue ddcf11f angle_error_mat compute it as arccos((trace(R1^T R2) - 1) / 2)
+ expected = torch.tensor(60.0, device=device, dtype=dtype)
+ angle = kornia.metrics.angle_error_mat(R1, R2)
+ assert angle.shape == ()
+ self.assert_close(angle, expected)
+ self.assert_close(kornia.metrics.angle_error_mat(R2, R1), expected)
+ # angle_error_vec: degrees between the directions, so 3 v1 and 0.1 v2 give the angle of v1 and v2; opposite
+ # vectors read 180, not 0
+ v1 = torch.tensor([1.0, 2.0, 2.0], device=device, dtype=dtype)
+ v2 = torch.tensor([2.0, -1.0, 0.5], device=device, dtype=dtype)
+ # math.degrees(math.acos(1.0 / (3.0 * math.sqrt(5.25)))) = 81.63500554645903
+ expected_vec = torch.tensor(81.63500554645903, device=device, dtype=dtype)
+ self.assert_close(kornia.metrics.angle_error_vec(3.0 * v1, 0.1 * v2), expected_vec)
+ self.assert_close(kornia.metrics.angle_error_vec(v1, -v1), torch.tensor(180.0, device=device, dtype=dtype))
+
+ def test_convention_pose_errors_fold_the_translation_angle(self, device, dtype):
+ """pose_errors gives (B,) degrees; t_err is the direction angle folded into [0, 90]; max_err the larger one."""
+ R_gt = _rotation([0.3, -0.5, 0.8], 40.0)
+ # rotation errors 45 and 135 deg: only the translation angle is folded, so 135 stays 135
+ R = torch.stack([R_gt @ _rotation([1.0, 2.0, -0.5], 45.0), R_gt @ _rotation([-0.2, 0.7, 1.0], 135.0)])
+ # pose 0: translations 116.39 deg apart (cos = -4/9), folded to 63.61; pose 1: same direction, 7 times longer
+ t_gt = torch.tensor([[2.0, -1.0, 2.0], [2.0, -1.0, 2.0]], dtype=torch.float64)
+ t = torch.tensor([[-2.0, 2.0, 1.0], [14.0, -7.0, 14.0]], dtype=torch.float64)
+ P = torch.cat([R, t[..., None]], -1).to(device, dtype)
+ P_gt = torch.cat([R_gt.expand(2, 3, 3), t_gt[..., None]], -1).to(device, dtype)
+ unfolded = math.degrees(math.acos(-4.0 / 9.0)) # 116.38779996124299
+ errors = kornia.metrics.pose_errors(P, P_gt)
+ assert errors["R_err"].shape == (2,)
+ self.assert_close(errors["R_err"], torch.tensor([45.0, 135.0], device=device, dtype=dtype))
+ self.assert_close(errors["t_err"], torch.tensor([180.0 - unfolded, 0.0], device=device, dtype=dtype))
+ self.assert_close(errors["max_err"], torch.tensor([180.0 - unfolded, 135.0], device=device, dtype=dtype))
+ # fold_translation=False keeps [0, 180]
+ raw = kornia.metrics.pose_errors(P, P_gt, fold_translation=False)["t_err"]
+ self.assert_close(raw, torch.tensor([unfolded, 0.0], device=device, dtype=dtype))
+ # an unbatched (3, 4) pose gives shape (1,)
+ assert kornia.metrics.pose_errors(P[0], P_gt[0])["R_err"].shape == (1,)
+ # only the top three rows are read: (4, 4) poses with arbitrary bottom rows give the (3, 4) result
+ square = kornia.metrics.pose_errors(
+ torch.cat([P[0], P.new_tensor([[0.5, -2.0, 3.0, 4.0]])]),
+ torch.cat([P_gt[0], P.new_tensor([[7.0, 1.0, -1.0, 2.0]])]),
+ )
+ for key, value in kornia.metrics.pose_errors(P[0], P_gt[0]).items():
+ self.assert_close(square[key], value)
+
+ def test_convention_translation_ate_is_the_raw_distance_per_sample(self, device, dtype):
+ """translation_ate is the Euclidean distance of every sample in the input units, with no alignment."""
+ trajectory = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 1.0, 0.0]], device=device, dtype=dtype)
+ shifted = trajectory + torch.tensor([5.0, 0.0, 0.0], device=device, dtype=dtype)
+ # a trajectory ATE after rigid alignment (TUM) would be 0 here; kornia keeps the offset of every pose
+ self.assert_close(
+ kornia.metrics.translation_ate(shifted, trajectory),
+ torch.tensor([5.0, 5.0, 5.0], device=device, dtype=dtype),
+ )
+ # not scale-invariant: twice the translation is off by its length
+ t_gt = torch.tensor([2.0, -1.0, 2.0], device=device, dtype=dtype)
+ self.assert_close(
+ kornia.metrics.translation_ate(2.0 * t_gt, t_gt), torch.tensor([3.0], device=device, dtype=dtype)
+ )
+
+ def test_convention_auc_from_errors_is_a_percentage(self, device, dtype):
+ """auc_from_errors maps each threshold to the area under the recall curve in percent, over all errors."""
+ errors = torch.tensor([0.5, 2.0, 4.0, 7.0, 30.0, float("inf")], device=device, dtype=dtype)
+ # Snippet used to generate expected (glue-factory 2d17e3b gluefactory/utils/tools.py; SuperGlue's pose_auc gives
+ # the same): cal_error_auc(np.array([0.5, 2, 4, 7, 30, np.inf]), [1, 3, 5, 10]) -> [0.125, 0.25, 0.35, 0.5],
+ # fractions where kornia returns percent. The inf error is a failure that never enters the area.
+ aucs = kornia.metrics.auc_from_errors(errors)
+ assert list(aucs) == [1.0, 3.0, 5.0, 10.0]
+ assert all(type(k) is float for k in aucs)
+ for threshold, expected in zip(aucs, (12.5, 25.0, 35.0, 50.0)):
+ assert math.isclose(aucs[threshold], expected, abs_tol=1e-3)