π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): reject fractional mAP labels (#5638)
Puttala Jeevan Kumarcc05e5d609b6
diff --git a/changelog.d/5638.breaking.md b/changelog.d/5638.breaking.mdnew file mode 100644index 000000000..579c329fe--- /dev/null+++ b/changelog.d/5638.breaking.md@@ -0,0 +1,6 @@+`mean_average_precision` now raises kornia's `BaseError`, naming `pred_labels` or `gt_labels`, when a floating-point+label is not a whole number (#5629). Previously a fractional label such as `1.5` passed the range check and matched no+class, so the call returned a value without an error: a detection with such a label was dropped, and an object with+such a label was not counted (with two perfect detections labelled `[1.5, 2.0]`, class 1 read `-1.0` and the mAP was+the AP of class 2 alone). Integer, `bool` and integer-valued floating-point labels such as `1.0` give the same results+as before.diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.pyindex 96a067769..c4ec07f98 100644--- a/kornia/metrics/mean_average_precision.py+++ b/kornia/metrics/mean_average_precision.py@@ -40,7 +40,8 @@ def mean_average_precision(Convention:- Every argument but ``n_classes`` and ``threshold`` is a list with one tensor per image. The call raises whenthe 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+ rows, or when a label lies outside ``[0, n_classes)`` or is not a whole number: a floating-point label+ such as ``1.0`` counts as class 1, and ``1.5`` raises. 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 theclasses ``1`` to ``n_classes - 1`` are scored.@@ -58,9 +59,6 @@ def mean_average_precision(and ground-truth boxes of different dtypes give the promotion of those two floating dtypes (float32 when oneset is integer and the other float16). :ref:`Losses and metrics <losses-metrics-conventions>` compares thematch 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.@@ -130,6 +128,8 @@ def mean_average_precision(bool(((labels >= 0) & (labels < n_classes)).all()),f"{name} must satisfy 0 <= label < n_classes ({n_classes}).",)+ if labels.is_floating_point():+ KORNIA_CHECK(bool((labels == labels.round()).all()), f"{name} must contain integer-valued labels.")# Calculate APs for each class (except background)average_precisions = torch.zeros((n_classes - 1), device=_pred_boxes.device, dtype=ap_dtype) # (n_classes - 1)diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.pyindex 30741c1b4..279890f76 100644--- a/tests/metrics/test_map.py+++ b/tests/metrics/test_map.py@@ -165,6 +165,50 @@ class TestMeanAveragePrecision(BaseTester):with pytest.raises(BaseError, match=rf"{label_source} must satisfy 0 <= label < n_classes \(3\)"):kornia.metrics.mean_average_precision([boxes] * 2, pred_labels, [scores] * 2, [boxes] * 2, gt_labels, 3)+ @pytest.mark.parametrize("label_source", ["pred_labels", "gt_labels"])+ def test_fractional_labels_5629(self, device, dtype, label_source):+ boxes = torch.tensor([[0.0, 0.0, 10.0, 20.0]], device=device, dtype=dtype)+ labels = torch.tensor([1], device=device, dtype=torch.long)+ invalid = torch.tensor([1.5], device=device, dtype=dtype)+ scores = torch.tensor([0.9], device=device, dtype=dtype)+ pred_labels = [labels, invalid if label_source == "pred_labels" else labels]+ gt_labels = [labels, invalid if label_source == "gt_labels" else labels]++ with pytest.raises(BaseError, match=rf"{label_source} must contain integer-valued labels"):+ kornia.metrics.mean_average_precision([boxes] * 2, pred_labels, [scores] * 2, [boxes] * 2, gt_labels, 3)++ @pytest.mark.parametrize("label_source", ["pred_labels", "gt_labels", "both"])+ def test_integer_valued_float_labels_5629(self, device, dtype, label_source):+ 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)+ expected_map, expected_ap = kornia.metrics.mean_average_precision(+ [boxes], [labels], [scores], [boxes], [labels], 3+ )+ pred_labels = labels.to(dtype) if label_source in ("pred_labels", "both") else labels+ gt_labels = labels.to(dtype) if label_source in ("gt_labels", "both") else labels++ mean_ap, ap = kornia.metrics.mean_average_precision([boxes], [pred_labels], [scores], [boxes], [gt_labels], 3)++ self.assert_close(expected_map, boxes.new_tensor(1.0))+ self.assert_close(expected_ap[1], 1.0)+ self.assert_close(expected_ap[2], 1.0)+ self.assert_close(mean_ap, expected_map)+ assert ap == expected_ap++ @pytest.mark.parametrize("invalid_label", [-1.0, 3.0, -0.5, 3.5])+ @pytest.mark.parametrize("label_source", ["pred_labels", "gt_labels"])+ def test_float_label_range_5629(self, device, dtype, invalid_label, label_source):+ boxes = torch.tensor([[0.0, 0.0, 10.0, 20.0]], device=device, dtype=dtype)+ labels = torch.tensor([1.0], device=device, dtype=dtype)+ invalid = torch.tensor([invalid_label], device=device, dtype=dtype)+ scores = torch.tensor([0.9], device=device, dtype=dtype)+ pred_labels = [invalid if label_source == "pred_labels" else labels]+ gt_labels = [invalid if label_source == "gt_labels" else labels]++ with pytest.raises(BaseError, match=rf"{label_source} must satisfy 0 <= label < n_classes \(3\)"):+ kornia.metrics.mean_average_precision([boxes], pred_labels, [scores], [boxes], gt_labels, 3)+def test_background_is_excluded(self, device, dtype):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([0, 1], device=device, dtype=torch.long)@@ -446,26 +490,31 @@ class TestConventionsMeanAveragePrecision(BaseTester):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)."""+ def test_convention_mean_average_precision_labels_are_whole_numbers_5629(self, device, dtype):+ """Integer-valued float labels score like int64 ones; a fractional label raises, naming its argument (#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)+ int_labels = [torch.tensor([1, 2], device=device)]+ float_labels = [torch.tensor([1.0, 2.0], device=device, dtype=dtype)]# control: integer-valued floating-point labels give the result of int64 labels, two perfect classesexpected_map, expected_ap = kornia.metrics.mean_average_precision(- boxes, [torch.tensor([1, 2], device=device)], scores, boxes, [torch.tensor([1, 2], device=device)], 3+ boxes, int_labels, scores, boxes, int_labels, 3)- mean_ap, ap = run([1.0, 2.0])+ mean_ap, ap = kornia.metrics.mean_average_precision(boxes, float_labels, scores, boxes, float_labels, 3)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])+ # bool labels are accepted too (True is class 1): torch.round has no bool kernel, so the whole-number check+ # must only look at floating-point labels+ bool_labels = [torch.tensor([True, True], device=device)]+ mean_ap, ap = kornia.metrics.mean_average_precision(boxes, bool_labels, scores, boxes, bool_labels, 2)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)+ self._assert_aps(ap, {1: 1.0}, device, dtype)+ # label 1.25 (exact in every float dtype; rounding or truncating it gives class 1) raises instead of matching+ # no class, which dropped its detection or object without an error+ fractional = [torch.tensor([1.25, 2.0], device=device, dtype=dtype)]+ with pytest.raises(BaseError, match="pred_labels must contain integer-valued labels"):+ kornia.metrics.mean_average_precision(boxes, fractional, scores, boxes, float_labels, 3)+ with pytest.raises(BaseError, match="gt_labels must contain integer-valued labels"):+ kornia.metrics.mean_average_precision(boxes, float_labels, scores, boxes, fractional, 3)