From 0ddbcb2010131973c377e47a60cb3d3ccea5c3f3 Mon Sep 17 00:00:00 2001 From: Balthasar Date: Thu, 17 Jul 2025 09:49:21 +0200 Subject: [PATCH 1/8] fix: start id with 1 because 0 means no match --- supervision/metrics/mean_average_precision.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index 5100f39a..e22eb322 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -1237,7 +1237,7 @@ class MeanAveragePrecision(Metric): "image_id": image_id, "bbox": xywh, "category_id": category_id, - "id": len(annotations), # incrementally increase the id + "id": len(annotations) + 1, # incrementally increase the id } annotations.append(dict_annotation) # Category list From 2c67cee720b39cbc26d5b1143aedb572e889d493 Mon Sep 17 00:00:00 2001 From: Balthasar Date: Thu, 17 Jul 2025 09:57:55 +0200 Subject: [PATCH 2/8] fix: tests and adjust comment --- supervision/metrics/mean_average_precision.py | 2 +- test/metrics/test_mean_average_precision.py | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 test/metrics/test_mean_average_precision.py diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index e22eb322..f5fa3159 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -1237,7 +1237,7 @@ class MeanAveragePrecision(Metric): "image_id": image_id, "bbox": xywh, "category_id": category_id, - "id": len(annotations) + 1, # incrementally increase the id + "id": len(annotations) + 1, # Start IDs from 1 (0 means no match) } annotations.append(dict_annotation) # Category list diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py new file mode 100644 index 00000000..b3b68249 --- /dev/null +++ b/test/metrics/test_mean_average_precision.py @@ -0,0 +1,66 @@ +""" +Tests for Mean Average Precision ID=0 bug fix +""" +import numpy as np +import pytest + +from supervision.detection.core import Detections +from supervision.metrics.mean_average_precision import MeanAveragePrecision + + +def test_single_perfect_detection(): + """Test that single perfect detection gets 1.0 mAP (not 0.0 due to ID=0 bug)""" + # Perfect detection (identical prediction and target) + detection = Detections( + xyxy=np.array([[10, 10, 50, 50]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.9]) + ) + + metric = MeanAveragePrecision() + metric.update([detection], [detection]) + result = metric.compute() + + # Should be perfect 1.0 mAP, not 0.0 due to ID=0 bug + assert abs(result.map50_95 - 1.0) < 1e-6 + + +def test_multiple_perfect_detections(): + """Test that multiple perfect detections get 1.0 mAP""" + # Multiple perfect detections in one image + detections = Detections( + xyxy=np.array([ + [10, 10, 50, 50], + [100, 100, 140, 140], + [200, 200, 240, 240] + ], dtype=np.float64), + class_id=np.array([0, 0, 0]), + confidence=np.array([0.9, 0.9, 0.9]) + ) + + metric = MeanAveragePrecision() + metric.update([detections], [detections]) + result = metric.compute() + + # Should be perfect 1.0 mAP + assert abs(result.map50_95 - 1.0) < 1e-6 + + +def test_batch_updates_perfect_detections(): + """Test that batch updates with perfect detections get 1.0 mAP""" + # Single perfect detection for multiple batch updates + detection = Detections( + xyxy=np.array([[10, 10, 50, 50]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.9]) + ) + + metric = MeanAveragePrecision() + # Add 3 batch updates + metric.update([detection], [detection]) + metric.update([detection], [detection]) + metric.update([detection], [detection]) + result = metric.compute() + + # Should be perfect 1.0 mAP across all batches + assert abs(result.map50_95 - 1.0) < 1e-6 \ No newline at end of file From 2907c40ecce4a5d9e8e957da08fc636c2d6af804 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 07:59:58 +0000 Subject: [PATCH 3/8] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto=20?= =?UTF-8?q?format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/metrics/test_mean_average_precision.py | 31 ++++++++++----------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py index b3b68249..bb0f91ef 100644 --- a/test/metrics/test_mean_average_precision.py +++ b/test/metrics/test_mean_average_precision.py @@ -1,8 +1,8 @@ """ Tests for Mean Average Precision ID=0 bug fix """ + import numpy as np -import pytest from supervision.detection.core import Detections from supervision.metrics.mean_average_precision import MeanAveragePrecision @@ -14,13 +14,13 @@ def test_single_perfect_detection(): detection = Detections( xyxy=np.array([[10, 10, 50, 50]], dtype=np.float64), class_id=np.array([0]), - confidence=np.array([0.9]) + confidence=np.array([0.9]), ) - + metric = MeanAveragePrecision() metric.update([detection], [detection]) result = metric.compute() - + # Should be perfect 1.0 mAP, not 0.0 due to ID=0 bug assert abs(result.map50_95 - 1.0) < 1e-6 @@ -29,19 +29,18 @@ def test_multiple_perfect_detections(): """Test that multiple perfect detections get 1.0 mAP""" # Multiple perfect detections in one image detections = Detections( - xyxy=np.array([ - [10, 10, 50, 50], - [100, 100, 140, 140], - [200, 200, 240, 240] - ], dtype=np.float64), + xyxy=np.array( + [[10, 10, 50, 50], [100, 100, 140, 140], [200, 200, 240, 240]], + dtype=np.float64, + ), class_id=np.array([0, 0, 0]), - confidence=np.array([0.9, 0.9, 0.9]) + confidence=np.array([0.9, 0.9, 0.9]), ) - + metric = MeanAveragePrecision() metric.update([detections], [detections]) result = metric.compute() - + # Should be perfect 1.0 mAP assert abs(result.map50_95 - 1.0) < 1e-6 @@ -52,15 +51,15 @@ def test_batch_updates_perfect_detections(): detection = Detections( xyxy=np.array([[10, 10, 50, 50]], dtype=np.float64), class_id=np.array([0]), - confidence=np.array([0.9]) + confidence=np.array([0.9]), ) - + metric = MeanAveragePrecision() # Add 3 batch updates metric.update([detection], [detection]) metric.update([detection], [detection]) metric.update([detection], [detection]) result = metric.compute() - + # Should be perfect 1.0 mAP across all batches - assert abs(result.map50_95 - 1.0) < 1e-6 \ No newline at end of file + assert abs(result.map50_95 - 1.0) < 1e-6 From 2e72e7089392f9aa2151288262f92abd77bcee1e Mon Sep 17 00:00:00 2001 From: Balthasar Date: Fri, 18 Jul 2025 09:04:41 +0200 Subject: [PATCH 4/8] basic fix --- supervision/metrics/mean_average_precision.py | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index f5fa3159..9e9952ed 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -57,7 +57,11 @@ class MeanAveragePrecisionResult: @property def map50_95(self) -> float: - return self.mAP_scores.mean() + valid_scores = self.mAP_scores[self.mAP_scores > -1] + if len(valid_scores) > 0: + return valid_scores.mean() + else: + return -1 @property def map50(self) -> float: @@ -917,35 +921,38 @@ class COCOEvaluator: :, :, :, area_range_idx, max_100_dets_idx ] # mAP over thresholds (dimension=num_thresholds) - mAP_scores_all_sizes = average_precision_all_sizes.mean(axis=(1, 2)) + # Use masked array to exclude -1 values when computing mean + masked = np.ma.masked_equal(average_precision_all_sizes, -1) + mAP_scores_all_sizes = np.ma.filled(masked.mean(axis=(1, 2)), -1) # AP per class - ap_per_class_all_sizes = average_precision_all_sizes.mean(axis=1).transpose( - 1, 0 - ) + ap_per_class_all_sizes = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) # Average precision for SMALL objects and 100 max detections small_area_range_idx = list(ObjectSize).index(ObjectSize.SMALL) average_precision_small = precision[ :, :, :, small_area_range_idx, max_100_dets_idx ] - mAP_scores_small = average_precision_small.mean(axis=(1, 2)) - ap_per_class_small = average_precision_small.mean(axis=1).transpose(1, 0) + masked_small = np.ma.masked_equal(average_precision_small, -1) + mAP_scores_small = np.ma.filled(masked_small.mean(axis=(1, 2)), -1) + ap_per_class_small = np.ma.filled(masked_small.mean(axis=1), -1).transpose(1, 0) # Average precision for MEDIUM objects and 100 max detections medium_area_range_idx = list(ObjectSize).index(ObjectSize.MEDIUM) average_precision_medium = precision[ :, :, :, medium_area_range_idx, max_100_dets_idx ] - mAP_scores_medium = average_precision_medium.mean(axis=(1, 2)) - ap_per_class_medium = average_precision_medium.mean(axis=1).transpose(1, 0) + masked_medium = np.ma.masked_equal(average_precision_medium, -1) + mAP_scores_medium = np.ma.filled(masked_medium.mean(axis=(1, 2)), -1) + ap_per_class_medium = np.ma.filled(masked_medium.mean(axis=1), -1).transpose(1, 0) # Average precision for LARGE objects and 100 max detections large_area_range_idx = list(ObjectSize).index(ObjectSize.LARGE) average_precision_large = precision[ :, :, :, large_area_range_idx, max_100_dets_idx ] - mAP_scores_large = average_precision_large.mean(axis=(1, 2)) - ap_per_class_large = average_precision_large.mean(axis=1).transpose(1, 0) + masked_large = np.ma.masked_equal(average_precision_large, -1) + mAP_scores_large = np.ma.filled(masked_large.mean(axis=(1, 2)), -1) + ap_per_class_large = np.ma.filled(masked_large.mean(axis=1), -1).transpose(1, 0) self.results = { "params": self.params, From 001a4254f80726e75af73ec48b5f8008e1ba0cb1 Mon Sep 17 00:00:00 2001 From: Balthasar Date: Fri, 18 Jul 2025 09:24:00 +0200 Subject: [PATCH 5/8] fix: improve code, more fixes and add tests --- supervision/metrics/mean_average_precision.py | 40 ++- test/metrics/test_mean_average_precision.py | 254 ++++++++++++++++++ 2 files changed, 285 insertions(+), 9 deletions(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index 9e9952ed..fc0e0572 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -425,6 +425,11 @@ class EvaluationDataset: if not isinstance(predictions, list): raise ValueError("results must be a list") + # Handle empty predictions + if len(predictions) == 0: + predictions_dataset.dataset["annotations"] = [] + return predictions_dataset + ids = [pred["image_id"] for pred in predictions] # Make sure the image ids from predictions exist in the current dataset @@ -923,9 +928,14 @@ class COCOEvaluator: # mAP over thresholds (dimension=num_thresholds) # Use masked array to exclude -1 values when computing mean masked = np.ma.masked_equal(average_precision_all_sizes, -1) - mAP_scores_all_sizes = np.ma.filled(masked.mean(axis=(1, 2)), -1) - # AP per class - ap_per_class_all_sizes = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) + # Check if all values are masked (empty array) + if masked.count() == 0: + mAP_scores_all_sizes = np.full(num_iou_thresholds, -1) + ap_per_class_all_sizes = np.full((num_categories, num_iou_thresholds), -1) + else: + mAP_scores_all_sizes = np.ma.filled(masked.mean(axis=(1, 2)), -1) + # AP per class + ap_per_class_all_sizes = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) # Average precision for SMALL objects and 100 max detections small_area_range_idx = list(ObjectSize).index(ObjectSize.SMALL) @@ -933,8 +943,12 @@ class COCOEvaluator: :, :, :, small_area_range_idx, max_100_dets_idx ] masked_small = np.ma.masked_equal(average_precision_small, -1) - mAP_scores_small = np.ma.filled(masked_small.mean(axis=(1, 2)), -1) - ap_per_class_small = np.ma.filled(masked_small.mean(axis=1), -1).transpose(1, 0) + if masked_small.count() == 0: + mAP_scores_small = np.full(num_iou_thresholds, -1) + ap_per_class_small = np.full((num_categories, num_iou_thresholds), -1) + else: + mAP_scores_small = np.ma.filled(masked_small.mean(axis=(1, 2)), -1) + ap_per_class_small = np.ma.filled(masked_small.mean(axis=1), -1).transpose(1, 0) # Average precision for MEDIUM objects and 100 max detections medium_area_range_idx = list(ObjectSize).index(ObjectSize.MEDIUM) @@ -942,8 +956,12 @@ class COCOEvaluator: :, :, :, medium_area_range_idx, max_100_dets_idx ] masked_medium = np.ma.masked_equal(average_precision_medium, -1) - mAP_scores_medium = np.ma.filled(masked_medium.mean(axis=(1, 2)), -1) - ap_per_class_medium = np.ma.filled(masked_medium.mean(axis=1), -1).transpose(1, 0) + if masked_medium.count() == 0: + mAP_scores_medium = np.full(num_iou_thresholds, -1) + ap_per_class_medium = np.full((num_categories, num_iou_thresholds), -1) + else: + mAP_scores_medium = np.ma.filled(masked_medium.mean(axis=(1, 2)), -1) + ap_per_class_medium = np.ma.filled(masked_medium.mean(axis=1), -1).transpose(1, 0) # Average precision for LARGE objects and 100 max detections large_area_range_idx = list(ObjectSize).index(ObjectSize.LARGE) @@ -951,8 +969,12 @@ class COCOEvaluator: :, :, :, large_area_range_idx, max_100_dets_idx ] masked_large = np.ma.masked_equal(average_precision_large, -1) - mAP_scores_large = np.ma.filled(masked_large.mean(axis=(1, 2)), -1) - ap_per_class_large = np.ma.filled(masked_large.mean(axis=1), -1).transpose(1, 0) + if masked_large.count() == 0: + mAP_scores_large = np.full(num_iou_thresholds, -1) + ap_per_class_large = np.full((num_categories, num_iou_thresholds), -1) + else: + mAP_scores_large = np.ma.filled(masked_large.mean(axis=(1, 2)), -1) + ap_per_class_large = np.ma.filled(masked_large.mean(axis=1), -1).transpose(1, 0) self.results = { "params": self.params, diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py index bb0f91ef..931b1bb4 100644 --- a/test/metrics/test_mean_average_precision.py +++ b/test/metrics/test_mean_average_precision.py @@ -63,3 +63,257 @@ def test_batch_updates_perfect_detections(): # Should be perfect 1.0 mAP across all batches assert abs(result.map50_95 - 1.0) < 1e-6 + + +def test_scenario_1_success_case_imperfect_match(): + """Scenario 1: Success Case with imperfect match""" + # Small object (class 0) - area = 30*30 = 900 < 1024 + small_perfect = Detections( + xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.95]), + data={"area": np.array([900])} + ) + + # Medium object (class 1) - area = 50*50 = 2500 (between 1024 and 9216) + medium_target = Detections( + xyxy=np.array([[10, 10, 60, 60]], dtype=np.float64), + class_id=np.array([1]), + data={"area": np.array([2500])} + ) + medium_pred = Detections( + xyxy=np.array([[12, 12, 60, 60]], dtype=np.float64), # Slightly off + class_id=np.array([1]), + confidence=np.array([0.9]), + data={"area": np.array([2304])} # 48*48 + ) + + # Large objects (classes 0, 1, 2) - area = 100*100 = 10000 > 9216 + large_targets = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + [230, 230, 330, 330] + ], dtype=np.float64), + class_id=np.array([2, 0, 1]), + data={"area": np.array([10000, 10000, 10000])} + ) + large_preds = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + [230, 230, 330, 330] + ], dtype=np.float64), + class_id=np.array([2, 0, 1]), + confidence=np.array([0.9, 0.9, 0.9]), + data={"area": np.array([10000, 10000, 10000])} + ) + + metric = MeanAveragePrecision() + metric.update([small_perfect], [small_perfect]) + metric.update([medium_pred], [medium_target]) + metric.update([large_preds], [large_targets]) + result = metric.compute() + + # Should be close to 0.9 (slightly less than perfect due to medium object) + assert 0.85 < result.map50_95 < 0.98 # Adjusted upper bound + assert result.medium_objects.map50_95 < 1.0 # Medium should be less than perfect + + +def test_scenario_2_missed_detection(): + """Scenario 2: GT Present, No Prediction (Missed Detection)""" + # Small object - area = 30*30 = 900 < 1024 + small_detection = Detections( + xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.95]), + data={"area": np.array([900])} + ) + + # Medium object - area = 50*50 = 2500 (between 1024 and 9216) - no prediction (missed) + medium_target = Detections( + xyxy=np.array([[10, 10, 60, 60]], dtype=np.float64), + class_id=np.array([1]), + data={"area": np.array([2500])} + ) + no_medium_pred = Detections.empty() + + # Large objects - area = 100*100 = 10000 > 9216 + large_detections = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + [230, 230, 330, 330] + ], dtype=np.float64), + class_id=np.array([2, 0, 1]), + confidence=np.array([0.9, 0.9, 0.9]), + data={"area": np.array([10000, 10000, 10000])} + ) + + metric = MeanAveragePrecision() + metric.update([small_detection], [small_detection]) + metric.update([no_medium_pred], [medium_target]) + metric.update([large_detections], [large_detections]) + result = metric.compute() + + # Medium objects should have 0.0 mAP (missed detection) + assert abs(result.medium_objects.map50_95 - 0.0) < 1e-6 + + +def test_scenario_3_false_positive(): + """Scenario 3: No GT, Prediction Present (False Positive)""" + # Small object - area = 30*30 = 900 < 1024 + small_detection = Detections( + xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.95]), + data={"area": np.array([900])} + ) + + # Medium object - area = 50*50 = 2500 - false positive (no GT) + medium_pred = Detections( + xyxy=np.array([[12, 12, 62, 62]], dtype=np.float64), + class_id=np.array([1]), + confidence=np.array([0.9]), + data={"area": np.array([2500])} + ) + no_medium_target = Detections.empty() + + # Large objects - area = 100*100 = 10000 > 9216 + large_detections = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + [230, 230, 330, 330] + ], dtype=np.float64), + class_id=np.array([2, 0, 1]), + confidence=np.array([0.9, 0.9, 0.9]), + data={"area": np.array([10000, 10000, 10000])} + ) + + metric = MeanAveragePrecision() + metric.update([small_detection], [small_detection]) + metric.update([medium_pred], [no_medium_target]) + metric.update([large_detections], [large_detections]) + result = metric.compute() + + # Medium objects should have -1 mAP (false positive, matching pycocotools) + assert result.medium_objects.map50_95 == -1 + + +def test_scenario_4_no_data(): + """Scenario 4: No GT, No Prediction (Category has no data)""" + # Small object - area = 30*30 = 900 < 1024 + small_detection = Detections( + xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.95]), + data={"area": np.array([900])} + ) + + # Medium object - no data at all + no_medium = Detections.empty() + + # Large objects - area = 100*100 = 10000 > 9216 - only classes 0 and 2 (no class 1) + large_targets = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + ], dtype=np.float64), + class_id=np.array([2, 0]), + data={"area": np.array([10000, 10000])} + ) + large_preds = Detections( + xyxy=np.array([ + [10, 10, 110, 110], + [120, 120, 220, 220], + ], dtype=np.float64), + class_id=np.array([2, 0]), + confidence=np.array([0.9, 0.9]), + data={"area": np.array([10000, 10000])} + ) + + metric = MeanAveragePrecision() + metric.update([small_detection], [small_detection]) + metric.update([no_medium], [no_medium]) + metric.update([large_preds], [large_targets]) + result = metric.compute() + + # Should NOT have negative mAP values for overall + assert result.map50_95 >= 0.0 + # Medium objects should have -1 mAP (no data, matching pycocotools) + assert result.medium_objects.map50_95 == -1 + + +def test_scenario_5_only_one_class_present(): + """Scenario 5: Only 1 of 3 Classes Present (Perfect Match)""" + # Only class 0 objects with perfect matches + detections_class_0 = [ + Detections( + xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.95]), + ), + Detections( + xyxy=np.array([[20, 20, 230, 130]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.9]), + ), + ] + + metric = MeanAveragePrecision() + for det in detections_class_0: + metric.update([det], [det]) + + result = metric.compute() + + # Should be 1.0 mAP (perfect match for the only class present) + assert abs(result.map50_95 - 1.0) < 1e-6 + assert abs(result.map50 - 1.0) < 1e-6 + assert abs(result.map75 - 1.0) < 1e-6 + + +def test_mixed_classes_with_missing_detections(): + """Test mixed scenario with some classes having no detections""" + # Class 0: Perfect detection + class_0_det = Detections( + xyxy=np.array([[10, 10, 50, 50]], dtype=np.float64), + class_id=np.array([0]), + confidence=np.array([0.9]), + ) + + # Class 1: GT exists but no prediction + class_1_target = Detections( + xyxy=np.array([[60, 60, 100, 100]], dtype=np.float64), + class_id=np.array([1]), + ) + class_1_pred = Detections.empty() + + # Class 2: Prediction exists but no GT (false positive) + class_2_pred = Detections( + xyxy=np.array([[110, 110, 150, 150]], dtype=np.float64), + class_id=np.array([2]), + confidence=np.array([0.8]), + ) + class_2_target = Detections.empty() + + metric = MeanAveragePrecision() + metric.update([class_0_det], [class_0_det]) + metric.update([class_1_pred], [class_1_target]) + metric.update([class_2_pred], [class_2_target]) + result = metric.compute() + + # Should not have negative mAP + assert result.map50_95 >= 0.0 + # Should be less than 1.0 due to missed detection and false positive + assert result.map50_95 < 1.0 + + +def test_empty_predictions_and_targets(): + """Test completely empty predictions and targets""" + metric = MeanAveragePrecision() + metric.update([Detections.empty()], [Detections.empty()]) + result = metric.compute() + + # Should handle empty case gracefully + assert result.map50_95 >= -1.0 # Can be -1 to indicate no data From afdbb0a75c6a6f35f0ea8b15f3d5dff93a28a6e1 Mon Sep 17 00:00:00 2001 From: Balthasar Date: Fri, 18 Jul 2025 09:36:59 +0200 Subject: [PATCH 6/8] fix: keep it DRY --- supervision/metrics/mean_average_precision.py | 55 +++++++++---------- test/metrics/test_mean_average_precision.py | 11 +++- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index fc0e0572..640e028c 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -918,6 +918,27 @@ class COCOEvaluator: np.array(score_at_recall) ) + self.results = { + "params": self.params, + "counts": [num_iou_thresholds, num_recall_thresholds, num_categories, num_area_ranges, num_max_detections], + "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "precision": precision, + "recall": recall, + "scores": scores, + } + + # Helper function to compute average precision while handling -1 sentinel values + def compute_average_precision(precision_slice): + """Helper function to compute average precision while handling -1 sentinel values.""" + masked = np.ma.masked_equal(precision_slice, -1) + if masked.count() == 0: + # All values are -1 (no data) + return np.full(num_iou_thresholds, -1), np.full((num_categories, num_iou_thresholds), -1) + else: + mAP_scores = np.ma.filled(masked.mean(axis=(1, 2)), -1) + ap_per_class = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) + return mAP_scores, ap_per_class + # Average precision over all sizes, 100 max detections area_range_idx = list(ObjectSize).index(ObjectSize.ALL) max_100_dets_idx = self.params.max_dets.index(100) @@ -927,54 +948,28 @@ class COCOEvaluator: ] # mAP over thresholds (dimension=num_thresholds) # Use masked array to exclude -1 values when computing mean - masked = np.ma.masked_equal(average_precision_all_sizes, -1) - # Check if all values are masked (empty array) - if masked.count() == 0: - mAP_scores_all_sizes = np.full(num_iou_thresholds, -1) - ap_per_class_all_sizes = np.full((num_categories, num_iou_thresholds), -1) - else: - mAP_scores_all_sizes = np.ma.filled(masked.mean(axis=(1, 2)), -1) - # AP per class - ap_per_class_all_sizes = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) + mAP_scores_all_sizes, ap_per_class_all_sizes = compute_average_precision(average_precision_all_sizes) # Average precision for SMALL objects and 100 max detections small_area_range_idx = list(ObjectSize).index(ObjectSize.SMALL) average_precision_small = precision[ :, :, :, small_area_range_idx, max_100_dets_idx ] - masked_small = np.ma.masked_equal(average_precision_small, -1) - if masked_small.count() == 0: - mAP_scores_small = np.full(num_iou_thresholds, -1) - ap_per_class_small = np.full((num_categories, num_iou_thresholds), -1) - else: - mAP_scores_small = np.ma.filled(masked_small.mean(axis=(1, 2)), -1) - ap_per_class_small = np.ma.filled(masked_small.mean(axis=1), -1).transpose(1, 0) + mAP_scores_small, ap_per_class_small = compute_average_precision(average_precision_small) # Average precision for MEDIUM objects and 100 max detections medium_area_range_idx = list(ObjectSize).index(ObjectSize.MEDIUM) average_precision_medium = precision[ :, :, :, medium_area_range_idx, max_100_dets_idx ] - masked_medium = np.ma.masked_equal(average_precision_medium, -1) - if masked_medium.count() == 0: - mAP_scores_medium = np.full(num_iou_thresholds, -1) - ap_per_class_medium = np.full((num_categories, num_iou_thresholds), -1) - else: - mAP_scores_medium = np.ma.filled(masked_medium.mean(axis=(1, 2)), -1) - ap_per_class_medium = np.ma.filled(masked_medium.mean(axis=1), -1).transpose(1, 0) + mAP_scores_medium, ap_per_class_medium = compute_average_precision(average_precision_medium) # Average precision for LARGE objects and 100 max detections large_area_range_idx = list(ObjectSize).index(ObjectSize.LARGE) average_precision_large = precision[ :, :, :, large_area_range_idx, max_100_dets_idx ] - masked_large = np.ma.masked_equal(average_precision_large, -1) - if masked_large.count() == 0: - mAP_scores_large = np.full(num_iou_thresholds, -1) - ap_per_class_large = np.full((num_categories, num_iou_thresholds), -1) - else: - mAP_scores_large = np.ma.filled(masked_large.mean(axis=(1, 2)), -1) - ap_per_class_large = np.ma.filled(masked_large.mean(axis=1), -1).transpose(1, 0) + mAP_scores_large, ap_per_class_large = compute_average_precision(average_precision_large) self.results = { "params": self.params, diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py index 931b1bb4..1345b0a7 100644 --- a/test/metrics/test_mean_average_precision.py +++ b/test/metrics/test_mean_average_precision.py @@ -315,5 +315,12 @@ def test_empty_predictions_and_targets(): metric.update([Detections.empty()], [Detections.empty()]) result = metric.compute() - # Should handle empty case gracefully - assert result.map50_95 >= -1.0 # Can be -1 to indicate no data + # Should return -1 for no data (matching pycocotools behavior) + assert result.map50_95 == -1 + assert result.map50 == -1 + assert result.map75 == -1 + + # All object size categories should also be -1 + assert result.small_objects.map50_95 == -1 + assert result.medium_objects.map50_95 == -1 + assert result.large_objects.map50_95 == -1 From a139fb0b49d5c7942331256ee0259b79931fc7fe Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 18 Jul 2025 08:00:32 +0000 Subject: [PATCH 7/8] =?UTF-8?q?fix(pre=5Fcommit):=20=F0=9F=8E=A8=20auto=20?= =?UTF-8?q?format=20pre-commit=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- supervision/metrics/mean_average_precision.py | 28 +++- test/metrics/test_mean_average_precision.py | 136 +++++++++--------- 2 files changed, 91 insertions(+), 73 deletions(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index 640e028c..4c8c3532 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -920,7 +920,13 @@ class COCOEvaluator: self.results = { "params": self.params, - "counts": [num_iou_thresholds, num_recall_thresholds, num_categories, num_area_ranges, num_max_detections], + "counts": [ + num_iou_thresholds, + num_recall_thresholds, + num_categories, + num_area_ranges, + num_max_detections, + ], "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "precision": precision, "recall": recall, @@ -933,7 +939,9 @@ class COCOEvaluator: masked = np.ma.masked_equal(precision_slice, -1) if masked.count() == 0: # All values are -1 (no data) - return np.full(num_iou_thresholds, -1), np.full((num_categories, num_iou_thresholds), -1) + return np.full(num_iou_thresholds, -1), np.full( + (num_categories, num_iou_thresholds), -1 + ) else: mAP_scores = np.ma.filled(masked.mean(axis=(1, 2)), -1) ap_per_class = np.ma.filled(masked.mean(axis=1), -1).transpose(1, 0) @@ -948,28 +956,36 @@ class COCOEvaluator: ] # mAP over thresholds (dimension=num_thresholds) # Use masked array to exclude -1 values when computing mean - mAP_scores_all_sizes, ap_per_class_all_sizes = compute_average_precision(average_precision_all_sizes) + mAP_scores_all_sizes, ap_per_class_all_sizes = compute_average_precision( + average_precision_all_sizes + ) # Average precision for SMALL objects and 100 max detections small_area_range_idx = list(ObjectSize).index(ObjectSize.SMALL) average_precision_small = precision[ :, :, :, small_area_range_idx, max_100_dets_idx ] - mAP_scores_small, ap_per_class_small = compute_average_precision(average_precision_small) + mAP_scores_small, ap_per_class_small = compute_average_precision( + average_precision_small + ) # Average precision for MEDIUM objects and 100 max detections medium_area_range_idx = list(ObjectSize).index(ObjectSize.MEDIUM) average_precision_medium = precision[ :, :, :, medium_area_range_idx, max_100_dets_idx ] - mAP_scores_medium, ap_per_class_medium = compute_average_precision(average_precision_medium) + mAP_scores_medium, ap_per_class_medium = compute_average_precision( + average_precision_medium + ) # Average precision for LARGE objects and 100 max detections large_area_range_idx = list(ObjectSize).index(ObjectSize.LARGE) average_precision_large = precision[ :, :, :, large_area_range_idx, max_100_dets_idx ] - mAP_scores_large, ap_per_class_large = compute_average_precision(average_precision_large) + mAP_scores_large, ap_per_class_large = compute_average_precision( + average_precision_large + ) self.results = { "params": self.params, diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py index 1345b0a7..8bee7b53 100644 --- a/test/metrics/test_mean_average_precision.py +++ b/test/metrics/test_mean_average_precision.py @@ -72,49 +72,47 @@ def test_scenario_1_success_case_imperfect_match(): xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), class_id=np.array([0]), confidence=np.array([0.95]), - data={"area": np.array([900])} + data={"area": np.array([900])}, ) - + # Medium object (class 1) - area = 50*50 = 2500 (between 1024 and 9216) medium_target = Detections( xyxy=np.array([[10, 10, 60, 60]], dtype=np.float64), class_id=np.array([1]), - data={"area": np.array([2500])} + data={"area": np.array([2500])}, ) medium_pred = Detections( xyxy=np.array([[12, 12, 60, 60]], dtype=np.float64), # Slightly off class_id=np.array([1]), confidence=np.array([0.9]), - data={"area": np.array([2304])} # 48*48 + data={"area": np.array([2304])}, # 48*48 ) - + # Large objects (classes 0, 1, 2) - area = 100*100 = 10000 > 9216 large_targets = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - [230, 230, 330, 330] - ], dtype=np.float64), + xyxy=np.array( + [[10, 10, 110, 110], [120, 120, 220, 220], [230, 230, 330, 330]], + dtype=np.float64, + ), class_id=np.array([2, 0, 1]), - data={"area": np.array([10000, 10000, 10000])} + data={"area": np.array([10000, 10000, 10000])}, ) large_preds = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - [230, 230, 330, 330] - ], dtype=np.float64), + xyxy=np.array( + [[10, 10, 110, 110], [120, 120, 220, 220], [230, 230, 330, 330]], + dtype=np.float64, + ), class_id=np.array([2, 0, 1]), confidence=np.array([0.9, 0.9, 0.9]), - data={"area": np.array([10000, 10000, 10000])} + data={"area": np.array([10000, 10000, 10000])}, ) - + metric = MeanAveragePrecision() metric.update([small_perfect], [small_perfect]) metric.update([medium_pred], [medium_target]) metric.update([large_preds], [large_targets]) result = metric.compute() - + # Should be close to 0.9 (slightly less than perfect due to medium object) assert 0.85 < result.map50_95 < 0.98 # Adjusted upper bound assert result.medium_objects.map50_95 < 1.0 # Medium should be less than perfect @@ -127,35 +125,34 @@ def test_scenario_2_missed_detection(): xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), class_id=np.array([0]), confidence=np.array([0.95]), - data={"area": np.array([900])} + data={"area": np.array([900])}, ) - + # Medium object - area = 50*50 = 2500 (between 1024 and 9216) - no prediction (missed) medium_target = Detections( xyxy=np.array([[10, 10, 60, 60]], dtype=np.float64), class_id=np.array([1]), - data={"area": np.array([2500])} + data={"area": np.array([2500])}, ) no_medium_pred = Detections.empty() - + # Large objects - area = 100*100 = 10000 > 9216 large_detections = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - [230, 230, 330, 330] - ], dtype=np.float64), + xyxy=np.array( + [[10, 10, 110, 110], [120, 120, 220, 220], [230, 230, 330, 330]], + dtype=np.float64, + ), class_id=np.array([2, 0, 1]), confidence=np.array([0.9, 0.9, 0.9]), - data={"area": np.array([10000, 10000, 10000])} + data={"area": np.array([10000, 10000, 10000])}, ) - + metric = MeanAveragePrecision() metric.update([small_detection], [small_detection]) metric.update([no_medium_pred], [medium_target]) metric.update([large_detections], [large_detections]) result = metric.compute() - + # Medium objects should have 0.0 mAP (missed detection) assert abs(result.medium_objects.map50_95 - 0.0) < 1e-6 @@ -167,36 +164,35 @@ def test_scenario_3_false_positive(): xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), class_id=np.array([0]), confidence=np.array([0.95]), - data={"area": np.array([900])} + data={"area": np.array([900])}, ) - + # Medium object - area = 50*50 = 2500 - false positive (no GT) medium_pred = Detections( xyxy=np.array([[12, 12, 62, 62]], dtype=np.float64), class_id=np.array([1]), confidence=np.array([0.9]), - data={"area": np.array([2500])} + data={"area": np.array([2500])}, ) no_medium_target = Detections.empty() - + # Large objects - area = 100*100 = 10000 > 9216 large_detections = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - [230, 230, 330, 330] - ], dtype=np.float64), + xyxy=np.array( + [[10, 10, 110, 110], [120, 120, 220, 220], [230, 230, 330, 330]], + dtype=np.float64, + ), class_id=np.array([2, 0, 1]), confidence=np.array([0.9, 0.9, 0.9]), - data={"area": np.array([10000, 10000, 10000])} + data={"area": np.array([10000, 10000, 10000])}, ) - + metric = MeanAveragePrecision() metric.update([small_detection], [small_detection]) metric.update([medium_pred], [no_medium_target]) metric.update([large_detections], [large_detections]) result = metric.compute() - + # Medium objects should have -1 mAP (false positive, matching pycocotools) assert result.medium_objects.map50_95 == -1 @@ -208,37 +204,43 @@ def test_scenario_4_no_data(): xyxy=np.array([[10, 10, 40, 40]], dtype=np.float64), class_id=np.array([0]), confidence=np.array([0.95]), - data={"area": np.array([900])} + data={"area": np.array([900])}, ) - + # Medium object - no data at all no_medium = Detections.empty() - + # Large objects - area = 100*100 = 10000 > 9216 - only classes 0 and 2 (no class 1) large_targets = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - ], dtype=np.float64), + xyxy=np.array( + [ + [10, 10, 110, 110], + [120, 120, 220, 220], + ], + dtype=np.float64, + ), class_id=np.array([2, 0]), - data={"area": np.array([10000, 10000])} + data={"area": np.array([10000, 10000])}, ) large_preds = Detections( - xyxy=np.array([ - [10, 10, 110, 110], - [120, 120, 220, 220], - ], dtype=np.float64), + xyxy=np.array( + [ + [10, 10, 110, 110], + [120, 120, 220, 220], + ], + dtype=np.float64, + ), class_id=np.array([2, 0]), confidence=np.array([0.9, 0.9]), - data={"area": np.array([10000, 10000])} + data={"area": np.array([10000, 10000])}, ) - + metric = MeanAveragePrecision() metric.update([small_detection], [small_detection]) metric.update([no_medium], [no_medium]) metric.update([large_preds], [large_targets]) result = metric.compute() - + # Should NOT have negative mAP values for overall assert result.map50_95 >= 0.0 # Medium objects should have -1 mAP (no data, matching pycocotools) @@ -260,13 +262,13 @@ def test_scenario_5_only_one_class_present(): confidence=np.array([0.9]), ), ] - + metric = MeanAveragePrecision() for det in detections_class_0: metric.update([det], [det]) - + result = metric.compute() - + # Should be 1.0 mAP (perfect match for the only class present) assert abs(result.map50_95 - 1.0) < 1e-6 assert abs(result.map50 - 1.0) < 1e-6 @@ -281,14 +283,14 @@ def test_mixed_classes_with_missing_detections(): class_id=np.array([0]), confidence=np.array([0.9]), ) - + # Class 1: GT exists but no prediction class_1_target = Detections( xyxy=np.array([[60, 60, 100, 100]], dtype=np.float64), class_id=np.array([1]), ) class_1_pred = Detections.empty() - + # Class 2: Prediction exists but no GT (false positive) class_2_pred = Detections( xyxy=np.array([[110, 110, 150, 150]], dtype=np.float64), @@ -296,13 +298,13 @@ def test_mixed_classes_with_missing_detections(): confidence=np.array([0.8]), ) class_2_target = Detections.empty() - + metric = MeanAveragePrecision() metric.update([class_0_det], [class_0_det]) metric.update([class_1_pred], [class_1_target]) metric.update([class_2_pred], [class_2_target]) result = metric.compute() - + # Should not have negative mAP assert result.map50_95 >= 0.0 # Should be less than 1.0 due to missed detection and false positive @@ -314,12 +316,12 @@ def test_empty_predictions_and_targets(): metric = MeanAveragePrecision() metric.update([Detections.empty()], [Detections.empty()]) result = metric.compute() - + # Should return -1 for no data (matching pycocotools behavior) assert result.map50_95 == -1 assert result.map50 == -1 assert result.map75 == -1 - + # All object size categories should also be -1 assert result.small_objects.map50_95 == -1 assert result.medium_objects.map50_95 == -1 From 118e3a496c3360af049d0d75969a185ebabe6c58 Mon Sep 17 00:00:00 2001 From: Balthasar Date: Fri, 18 Jul 2025 10:09:53 +0200 Subject: [PATCH 8/8] fix: line length --- supervision/metrics/mean_average_precision.py | 2 +- test/metrics/test_mean_average_precision.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/supervision/metrics/mean_average_precision.py b/supervision/metrics/mean_average_precision.py index 4c8c3532..bc6d0af8 100644 --- a/supervision/metrics/mean_average_precision.py +++ b/supervision/metrics/mean_average_precision.py @@ -935,7 +935,7 @@ class COCOEvaluator: # Helper function to compute average precision while handling -1 sentinel values def compute_average_precision(precision_slice): - """Helper function to compute average precision while handling -1 sentinel values.""" + """Compute average precision while handling -1 sentinel values.""" masked = np.ma.masked_equal(precision_slice, -1) if masked.count() == 0: # All values are -1 (no data) diff --git a/test/metrics/test_mean_average_precision.py b/test/metrics/test_mean_average_precision.py index 8bee7b53..f17cb1ce 100644 --- a/test/metrics/test_mean_average_precision.py +++ b/test/metrics/test_mean_average_precision.py @@ -128,7 +128,7 @@ def test_scenario_2_missed_detection(): data={"area": np.array([900])}, ) - # Medium object - area = 50*50 = 2500 (between 1024 and 9216) - no prediction (missed) + # Medium object - area = 50*50 = 2500 (between 1024 and 9216) - missed medium_target = Detections( xyxy=np.array([[10, 10, 60, 60]], dtype=np.float64), class_id=np.array([1]),