Sub topic 3
Mean average precision across classes
Prerequisites: you can write Python lists and dictionaries, compute IoU between two boxes, and compute average precision (AP) for one class from a precision-recall curve.
Mean average precision across classes
Mean average precision (mAP) is the unweighted mean of the per-class AP values. Each class counts equally, so a detector that misses a rare class scores lower even if it handles common classes well.
ap_by_class = {"person": 0.62, "car": 0.40, "dog": 0.90}
def mean_average_precision(ap_by_class):
return sum(ap_by_class.values()) / len(ap_by_class)
print(round(mean_average_precision(ap_by_class), 4)) # 0.64COCO-style mAP: averaging over IoU thresholds and object sizes
Pascal VOC reports AP at one IoU threshold, usually 0.5, written [email protected]. The COCO protocol averages AP over ten thresholds, from 0.50 to 0.95 in steps of 0.05, written mAP@[.5:.95]. Boxes that are slightly off still pass at 0.5 but fail at 0.9, so COCO rewards tight localization. COCO also reports AP for small, medium, and large objects, and it caps detections at 100 per image.
thresholds = [round(0.5 + 0.05 * i, 2) for i in range(10)]
print(thresholds) # [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]Pitfalls: thresholds, duplicates, class imbalance, and comparing numbers
- Thresholds: [email protected] and mAP@[.5:.95] are different numbers. Check which one a paper reports before comparing.
- Duplicates: Without non-maximum suppression, several boxes on one object count as false positives and lower precision.
- Class imbalance: A class with few ground-truth boxes gives a noisy AP, yet it has the same weight as any other class in mAP.
- Comparing numbers: Max detections per image, the image set, and the interpolation method all change the score.
Beyond IoU: GIoU, DIoU, and CIoU
IoU is zero for any two non-overlapping boxes, so it gives no training signal when a prediction misses. Generalized IoU (GIoU) subtracts the fraction of the smallest enclosing box that covers neither box. DIoU and CIoU add penalties for center distance and aspect ratio. These variants are training losses. They do not change how mAP is scored.
def giou(a, b):
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
enclose = (max(a[2], b[2]) - min(a[0], b[0])) * (max(a[3], b[3]) - min(a[1], b[1]))
return inter / union - (enclose - union) / enclose
print(round(giou((0, 0, 10, 10), (5, 5, 15, 15)), 4)) # -0.0794Exercise
Detector A and detector B both score [email protected] of 0.70. Detector A scores 0.35 on mAP@[.5:.95], and detector B scores 0.50. Which detector localizes more precisely, and why?
Show answer
Detector B. Its higher average over the stricter thresholds means its boxes overlap the ground truth more tightly at IoU 0.75 and above.