π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): check the box, label and score counts of mean_average_precision per image (#5582)
εΊζ’η39fedf40637c
diff --git a/changelog.d/5582.breaking.md b/changelog.d/5582.breaking.mdnew file mode 100644index 000000000..05bbd98ff--- /dev/null+++ b/changelog.d/5582.breaking.md@@ -0,0 +1,5 @@+`mean_average_precision` now checks in every image that the boxes, labels and, for detections, the scores have one row+each, and raises `BaseError` naming the image and its counts otherwise (#5580). Previously only the totals over all+images were compared, so mismatches that cancelled over the images passed the check and the boxes were paired with the+wrong image, which returned a wrong mAP with no error: in the issue's two-image example 0.5455 instead of an error.+Input whose counts agree in every image gives the same result as before.diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.pyindex 109a15117..0ad77332e 100644--- a/kornia/metrics/mean_average_precision.py+++ b/kornia/metrics/mean_average_precision.py@@ -65,36 +65,35 @@ def mean_average_precision(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+ # Store all (true) objects in a single continuous torch.Tensor while keeping track of the image it is from.+ # The counts are checked per image: totals that agree can still pair the rows of one image with another's.gt_images = []- for i, labels in enumerate(gt_labels):+ for i, (boxes, labels) in enumerate(zip(gt_boxes, gt_labels)):+ KORNIA_CHECK(+ boxes.size(0) == labels.size(0),+ f"gt_boxes and gt_labels must have one row per object in every image. Got image {i}: {boxes.size(0)} "+ f"boxes and {labels.size(0)} labels",+ )gt_images.extend([i] * labels.size(0))# (n_objects), n_objects is the total no. of objects across all images_gt_boxes = torch.cat(gt_boxes, 0) # (n_objects, 4)_gt_labels = torch.cat(gt_labels, 0) # (n_objects)_gt_images = torch.tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)- 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 frompred_images = []- for i, labels in enumerate(pred_labels):+ for i, (boxes, labels, scores) in enumerate(zip(pred_boxes, pred_labels, pred_scores)):+ KORNIA_CHECK(+ boxes.size(0) == labels.size(0) == scores.size(0),+ f"pred_boxes, pred_labels and pred_scores must have one row per detection in every image. Got image {i}: "+ f"{boxes.size(0)} boxes, {labels.size(0)} labels and {scores.size(0)} scores",+ )pred_images.extend([i] * labels.size(0))_pred_boxes = torch.cat(pred_boxes, 0) # (n_detections, 4)_pred_labels = torch.cat(pred_labels, 0) # (n_detections)_pred_scores = torch.cat(pred_scores, 0) # (n_detections)_pred_images = torch.tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)- 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(diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.pyindex 2d49e3d3f..e27e7092f 100644--- a/tests/metrics/test_map.py+++ b/tests/metrics/test_map.py@@ -120,6 +120,47 @@ class TestMeanAveragePrecision(BaseTester):with pytest.raises(BaseError, match=rf"same length.*{name} 1"):kornia.metrics.mean_average_precision(*args, 3)+ def test_exception_per_image_counts(self, device, dtype):+ # The counts are checked per image, so mismatches that cancel over the images do not pair the rows of one+ # image with another's (#5580).+ a = torch.tensor([[0.0, 0.0, 10.0, 10.0]], device=device, dtype=dtype)+ b = torch.tensor([[50.0, 50.0, 60.0, 60.0]], device=device, dtype=dtype)+ none = torch.zeros(0, 4, device=device, dtype=dtype)+ boxes = [torch.cat([a, b]), none]+ labels = [torch.tensor([1, 1], device=device), torch.tensor([], device=device, dtype=torch.long)]+ scores = [torch.tensor([0.9, 0.8], device=device, dtype=dtype), torch.zeros(0, device=device, dtype=dtype)]+ one_each = [torch.tensor([1], device=device), torch.tensor([1], device=device)]+ one_score_each = [+ torch.tensor([0.9], device=device, dtype=dtype),+ torch.tensor([0.8], device=device, dtype=dtype),+ ]++ mean_ap, _ = kornia.metrics.mean_average_precision(boxes, labels, scores, boxes, labels, 2)+ self.assert_close(mean_ap, torch.tensor(1.0, device=device, dtype=dtype))+ with pytest.raises(BaseError, match=r"one row per object in every image. Got image 0: 2 boxes and 1 labels"):+ kornia.metrics.mean_average_precision(boxes, labels, scores, boxes, one_each, 2)+ with pytest.raises(+ BaseError, match=r"one row per detection in every image. Got image 0: 2 boxes, 1 labels and 1 scores"+ ):+ kornia.metrics.mean_average_precision(boxes, one_each, one_score_each, boxes, labels, 2)+ # the first image is consistent, so the second is named+ with pytest.raises(BaseError, match=r"Got image 1: 2 boxes and 1 labels"):+ kornia.metrics.mean_average_precision(+ [a, a, b],+ one_each + one_each[:1],+ one_score_each + one_score_each[:1],+ [a, boxes[0], none],+ one_each + one_each[:1],+ 2,+ )+ # the first image holds the extra row, of each kind the checks compare in turn+ with pytest.raises(BaseError, match=r"Got image 0: 1 boxes and 2 labels"):+ kornia.metrics.mean_average_precision(boxes, labels, scores, [a, b], labels, 2)+ with pytest.raises(BaseError, match=r"Got image 0: 2 boxes, 1 labels and 2 scores"):+ kornia.metrics.mean_average_precision(boxes, one_each, scores, boxes, labels, 2)+ with pytest.raises(BaseError, match=r"Got image 0: 1 boxes, 1 labels and 2 scores"):+ kornia.metrics.mean_average_precision([a, b], one_each, scores, boxes, labels, 2)+@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