Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(metrics): compute mean_average_precision for integer boxes in float32 and name the mismatched lengths (#5556)

εŒΊζ’“η9957db1d0dcb
diff --git a/changelog.d/5556.breaking.md b/changelog.d/5556.breaking.md
new file mode 100644
index 000000000..e773c06d8
--- /dev/null
+++ b/changelog.d/5556.breaking.md
@@ -0,0 +1,8 @@
+`mean_average_precision` now computes the average precision of integer boxes in float32, and that of two box sets of
+different dtypes in their promoted floating dtype, with integer boxes counting as float32 as in `mean_iou_bbox`
+(#5551). Previously integer boxes raised torch's `mean(): could not infer output dtype`, and box sets of two floating
+dtypes kept the TP/FP counts and the result in the prediction dtype and the precisions in the ground-truth dtype:
+float16 predictions with float32 ground truth returned 0.8486 in float16 where float32 boxes give 0.8485, and they
+now return that float32 value. Boxes of one floating dtype give the same result as before. A mismatch of the five list
+lengths, or of the box, label and score counts, now raises kornia's `BaseError` naming the lengths or counts instead
+of a message-less `AssertionError`, so code that catches `AssertionError` there must catch `BaseError` instead.
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index 170dea209..109a15117 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -19,6 +19,8 @@ from typing import Dict, List, Tuple
import torch
+from kornia.core.check import KORNIA_CHECK
+
from .mean_iou import mean_iou_bbox
@@ -56,8 +58,12 @@ def mean_average_precision(
"""
# these are all lists of tensors of the same length, i.e. number of images
- if not len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels):
- raise AssertionError
+ KORNIA_CHECK(
+ len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels),
+ "The five per-image lists must have the same length. Got: "
+ f"pred_boxes {len(pred_boxes)}, pred_labels {len(pred_labels)}, pred_scores {len(pred_scores)}, "
+ f"gt_boxes {len(gt_boxes)}, gt_labels {len(gt_labels)}",
+ )
# Store all (true) objects in a single continuous torch.Tensor while keeping track of the image it is from
gt_images = []
@@ -68,8 +74,11 @@ def mean_average_precision(
_gt_labels = torch.cat(gt_labels, 0) # (n_objects)
_gt_images = torch.tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
- if not _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0):
- raise AssertionError
+ KORNIA_CHECK(
+ _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0),
+ f"gt_boxes and gt_labels must have one row per object. Got: {_gt_boxes.size(0)} boxes and "
+ f"{_gt_labels.size(0)} labels",
+ )
# Store all detections in a single continuous torch.Tensor while keeping track of the image it is from
pred_images = []
@@ -80,13 +89,21 @@ def mean_average_precision(
_pred_scores = torch.cat(pred_scores, 0) # (n_detections)
_pred_images = torch.tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
- if not _pred_images.size(0) == _pred_boxes.size(0) == _pred_labels.size(0) == _pred_scores.size(0):
- raise AssertionError
+ KORNIA_CHECK(
+ _pred_images.size(0) == _pred_boxes.size(0) == _pred_labels.size(0) == _pred_scores.size(0),
+ f"pred_boxes, pred_labels and pred_scores must have one row per detection. Got: {_pred_boxes.size(0)} boxes, "
+ f"{_pred_labels.size(0)} labels and {_pred_scores.size(0)} scores",
+ )
+
+ # The precisions need a floating dtype. Integer boxes count as float32, as mean_iou_bbox computes their overlaps,
+ # and the two sets meet in their promoted dtype: integer and float16 boxes give float32, not float16.
+ ap_dtype = torch.promote_types(
+ _pred_boxes.dtype if _pred_boxes.is_floating_point() else torch.float32,
+ _gt_boxes.dtype if _gt_boxes.is_floating_point() else torch.float32,
+ )
# Calculate APs for each class (except background)
- average_precisions = torch.zeros(
- (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype
- ) # (n_classes - 1)
+ average_precisions = torch.zeros((n_classes - 1), device=_pred_boxes.device, dtype=ap_dtype) # (n_classes - 1)
for c in range(1, n_classes):
# Extract only objects with this class
gt_class_images = _gt_images[_gt_labels == c] # (n_class_objects)
@@ -112,12 +129,8 @@ def mean_average_precision(
pred_class_boxes = pred_class_boxes[sort_ind] # (n_class_detections, 4)
# In the order of decreasing scores, check if true or false positive
- gt_positives = torch.zeros(
- (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
- ) # (n_class_detections)
- false_positives = torch.zeros(
- (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
- ) # (n_class_detections)
+ gt_positives = torch.zeros((n_class_detections,), dtype=ap_dtype, device=pred_class_boxes.device)
+ false_positives = torch.zeros((n_class_detections,), dtype=ap_dtype, device=pred_class_boxes.device)
for d in range(n_class_detections):
this_detection_box = pred_class_boxes[d].unsqueeze(0) # (1, 4)
this_image = pred_class_images[d] # (), scalar
@@ -165,7 +178,7 @@ def mean_average_precision(
# Exact tenths as Python floats: each comparison below casts them to the recall dtype. A float32 arange widened
# to Python floats gives 0.10000000149..., which a float64 recall of exactly 1/10 never reaches (#5083).
recall_thresholds = [i / 10 for i in range(11)] # (11)
- precisions = torch.zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
+ precisions = torch.zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=ap_dtype) # (11)
for i, t in enumerate(recall_thresholds):
recalls_above_t = cumul_recall >= t
if recalls_above_t.any():
diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.py
index d83aa9d3b..2d49e3d3f 100644
--- a/tests/metrics/test_map.py
+++ b/tests/metrics/test_map.py
@@ -19,6 +19,7 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import BaseError
from testing.base import BaseTester
@@ -93,9 +94,82 @@ class TestMeanAveragePrecision(BaseTester):
gt_boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
gt_labels = torch.tensor([1], device=device, dtype=torch.long)
- with pytest.raises(AssertionError):
+ with pytest.raises(BaseError, match="same length"):
_ = kornia.metrics.mean_average_precision(boxes[0], [labels], [scores], [gt_boxes], [gt_labels], 2)
+ def test_exception_list_lengths(self, device, dtype):
+ # A list-length mismatch names the five lengths; a per-image size mismatch names the sizes (#5551).
+ boxes = torch.tensor([[0.0, 0.0, 10.0, 20.0], [30.0, 5.0, 45.0, 12.0]], device=device, dtype=dtype)
+ labels = torch.tensor([1, 2], device=device, dtype=torch.long)
+ scores = torch.tensor([0.9, 0.8], device=device, dtype=dtype)
+
+ with pytest.raises(BaseError, match=r"same length.*pred_boxes 2.*gt_boxes 1"):
+ kornia.metrics.mean_average_precision([boxes] * 2, [labels] * 2, [scores] * 2, [boxes], [labels], 3)
+ with pytest.raises(BaseError, match=r"same length.*pred_scores 1"):
+ kornia.metrics.mean_average_precision([boxes] * 2, [labels] * 2, [scores], [boxes] * 2, [labels] * 2, 3)
+ with pytest.raises(BaseError, match=r"one row per object.*2 boxes and 1 labels"):
+ kornia.metrics.mean_average_precision([boxes], [labels], [scores], [boxes], [labels[:1]], 3)
+ with pytest.raises(BaseError, match=r"one row per detection.*2 boxes, 2 labels and 1 scores"):
+ kornia.metrics.mean_average_precision([boxes], [labels], [scores[:1]], [boxes], [labels], 3)
+ with pytest.raises(BaseError, match=r"one row per detection.*1 boxes, 2 labels and 2 scores"):
+ kornia.metrics.mean_average_precision([boxes[:1]], [labels], [scores], [boxes], [labels], 3)
+ # each of the five lists in turn one image short
+ lists = [[boxes] * 2, [labels] * 2, [scores] * 2, [boxes] * 2, [labels] * 2]
+ for i, name in enumerate(("pred_boxes", "pred_labels", "pred_scores", "gt_boxes", "gt_labels")):
+ args = [x[:1] if j == i else x for j, x in enumerate(lists)]
+ with pytest.raises(BaseError, match=rf"same length.*{name} 1"):
+ kornia.metrics.mean_average_precision(*args, 3)
+
+ @pytest.mark.parametrize("box_dtype", [torch.int64, torch.int32, torch.uint8])
+ def test_integer_boxes_match_the_float_result(self, device, box_dtype):
+ # Integer boxes give the AP of their float copies in float32, as mean_iou_bbox computes them (#5551). The
+ # ranked detections are TP, FP, TP: recall 0.5, 0.5, 1 at precision 1, 0.5, 2/3, so AP = (6 + 5 * 2 / 3) / 11.
+ gt_boxes = torch.tensor([[0, 0, 10, 20], [30, 5, 45, 12]], device=device, dtype=box_dtype)
+ gt_labels = torch.tensor([1, 1], device=device, dtype=torch.long)
+ boxes = torch.tensor([[0, 0, 10, 20], [100, 100, 120, 130], [30, 5, 45, 12]], device=device, dtype=box_dtype)
+ labels = torch.tensor([1, 1, 1], device=device, dtype=torch.long)
+ scores = torch.tensor([0.9, 0.8, 0.7], device=device)
+
+ mean_ap, ap = kornia.metrics.mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
+ expected, expected_ap = kornia.metrics.mean_average_precision(
+ [boxes.float()], [labels], [scores], [gt_boxes.float()], [gt_labels], 2
+ )
+
+ assert mean_ap.dtype == torch.float32
+ self.assert_close(mean_ap, torch.tensor((6 + 5 * 2 / 3) / 11, device=device))
+ self.assert_close(mean_ap, expected, rtol=0, atol=0)
+ assert ap == expected_ap
+
+ @pytest.mark.parametrize(
+ "pred_dtype, gt_dtype",
+ [
+ (torch.int64, torch.float16),
+ (torch.float16, torch.int64),
+ (torch.float16, torch.float32),
+ (torch.float32, torch.float16),
+ ],
+ )
+ def test_mixed_box_dtypes_compute_in_the_promoted_floating_dtype(self, device, pred_dtype, gt_dtype):
+ # Integer boxes count as float32, and the two box sets meet in their promoted dtype, as in mean_iou_bbox. The
+ # TP/FP counts used to take the prediction dtype and the precisions the ground-truth dtype, so float16 boxes
+ # with float32 ones gave a float16 AP. Same TP, FP, TP ranking as above.
+ gt_boxes = torch.tensor([[0, 0, 10, 20], [30, 5, 45, 12]], device=device)
+ gt_labels = torch.tensor([1, 1], device=device, dtype=torch.long)
+ boxes = torch.tensor([[0, 0, 10, 20], [100, 100, 120, 130], [30, 5, 45, 12]], device=device)
+ labels = torch.tensor([1, 1, 1], device=device, dtype=torch.long)
+ scores = torch.tensor([0.9, 0.8, 0.7], device=device)
+
+ mean_ap, ap = kornia.metrics.mean_average_precision(
+ [boxes.to(pred_dtype)], [labels], [scores], [gt_boxes.to(gt_dtype)], [gt_labels], 2
+ )
+ expected, expected_ap = kornia.metrics.mean_average_precision(
+ [boxes.float()], [labels], [scores], [gt_boxes.float()], [gt_labels], 2
+ )
+
+ assert mean_ap.dtype == torch.float32
+ self.assert_close(mean_ap, expected, rtol=0, atol=0)
+ assert ap == expected_ap
+
def test_recall_on_an_exact_tenth_reaches_its_threshold_5083(self, device, dtype):
# 10 objects, ranked detections TP, FP, then 9 TP: recall passes through every tenth, precision drops at the FP.
gt_boxes = torch.tensor([[i * 20.0, 0.0, i * 20.0 + 10.0, 10.0] for i in range(10)], device=device, dtype=dtype)