Sub topic 9
COCO-style mAP: averaging over IoU thresholds and object sizes
This chapter assumes you can compute IoU for two boxes. It also assumes you know how detections are ranked by score and matched to ground truth, and how a precision-recall curve gives average precision (AP) for one class at one IoU threshold. Here we build the COCO protocol on top of that. It changes the evaluation in four ways: it averages over many IoU thresholds, it reports results by object size, it caps detections per image, and it samples the curve at 101 recall points.
What COCO changes compared with Pascal VOC
The Pascal VOC protocol scores each class at a single IoU threshold of 0.5. The COCO protocol repeats the same computation under many conditions and averages or reports the results.
| Aspect | Pascal VOC | COCO |
|---|---|---|
| IoU threshold | 0.5 only | 0.50, 0.55, ..., 0.95 (10 values) |
| Curve interpolation | 11-point (VOC07) or all-point (VOC10 and later) | 101 recall points |
| Object sizes | Not split | Small, medium, large reported separately |
| Detections per image | Not capped | Capped at 100 (also reported at 1 and 10 for recall) |
| Hard cases | `difficult` flag is ignored | `iscrowd` regions and out-of-range sizes are ignored |
| Naming | mAP | AP (the mean over classes is implied) |
The main headline number, written AP or mAP@[.5:.95], is the mean over all classes and all ten thresholds. The mean over classes at IoU 0.5 alone is reported separately as AP50.
Averaging over IoU thresholds
A detector can find every object and still draw loose boxes. At IoU 0.5 a box only has to overlap the object by half to count. At 0.95 it has to be nearly pixel-exact. Averaging over ten thresholds rewards detectors whose boxes are tight.
The procedure is mechanical. For each threshold, redo the matching, because a different threshold changes which detections are true positives. Then recompute the precision-recall curve and the AP. A detection that is a true positive at 0.5 may be a false positive at 0.75. A false positive also blocks nothing. A ground-truth box that stays unmatched at a stricter threshold simply lowers recall.
Compare three detectors with the same AP50 of 0.70:
- Detector A has AP75 of 0.65. Its boxes are tight.
- Detector B has AP75 of 0.40. Its boxes are loose.
- Detector C has AP75 of 0.15. It mostly finds the objects but localizes them badly.
AP50 cannot tell these apart. The averaged AP can.
Splitting by object size
COCO defines size by the pixel area of the object in the original image:
- Small: area up to 32² = 1024 pixels.
- Medium: area from 1024 up to 96² = 9216 pixels.
- Large: area above 9216 pixels.
Detectors usually do much worse on small objects, so the overall number can hide this. Reporting APs, APm and APl exposes it.
Evaluating one size range is not a matter of filtering the data. If you simply deleted the other-sized ground truths, detections of those objects would become false positives. COCO uses an ignore rule instead:
- Ground-truth boxes outside the size range are marked as ignored. They do not count toward the number of positives.
- A detection that matches an ignored ground truth is dropped. It is neither a true nor a false positive.
- A detection that matches nothing and whose own area is outside the range is also dropped.
- A detection that matches nothing and whose area is inside the range is a false positive.
- During matching, non-ignored ground truths are preferred over ignored ones.
Capping detections per image
COCO keeps only the highest-scoring detections for each image and class, 100 by default. Without a cap, a detector could emit thousands of low-score boxes. These barely hurt AP, because they sit at the end of the ranking, but they can raise recall. The cap makes the numbers comparable. It also means that on a crowded image, correct objects ranked below 100 are lost.
The official tool also reports average recall (AR) with caps of 1, 10 and 100 detections per image. AR is recall averaged over the same ten thresholds. AR1 and AR10 show how much of the recall you keep when only the top few detections are allowed.
The full loop
A self-contained implementation
The code below is a compact COCO-style evaluator for plain boxes. It does not handle iscrowd regions. It uses the ignore rule, a cap on detections, and 101-point interpolation. A class with no non-ignored ground truth returns None and is left out of the mean, as in the official tool, which marks such cells as -1.
from bisect import bisect_left
INF = 1e10
SIZE_RANGES = {
"all": (0, INF),
"small": (0, 32 ** 2),
"medium": (32 ** 2, 96 ** 2),
"large": (96 ** 2, INF),
}
COCO_THRESHOLDS = [round(0.5 + 0.05 * i, 2) for i in range(10)]
def iou(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 = box_area(a) + box_area(b) - inter
return inter / union if union > 0 else 0.0
def box_area(b):
return (b[2] - b[0]) * (b[3] - b[area, rng):
return rng[0] <= area <= rng[1]
def ap_101(dets, gts, iou_thr, area_rng, max_dets):
"""A one class. dets: [(image_id, score, box)], gts: {image_id: [box]}."""
by_, score, box in dets:
by_image.setdefault(img, []).append((score, box))
n_gt = 0
records = [] # (score, positive or 0 for false positive)
for img in set(gts) | set(by_image):
gt_boxes = gts.get(img, [])
ignored_area(g), area_rng) for g in gt_boxes]
n_gt += ignored.count(False)
taken = [False] * len(gt_boxes)_image.get(img, []), key=lambda d: -d[0])[:max_dets]
for score, box in top:
best, best_key = -1, None
for j, g inboxes):
if taken[j]:
continue
v = iou(box, g)
if v < iou_thr:
continue
key = (not ignored[j non-ignored, then higher IoU
if best_key is None or key > best_key:
best, best_key = j, key
if best >= 0: True
if not ignored[best]:
records.append((score, 1))
elif in_range(box_area(box), area_rng):
records.append((score, 0))
:
return None
records.sort(key=lambda r: -r[0])
prec, rec, tp = [], [], 0
for i, (__tp) in enumerate(records, start=1):
tp += is_tp
prec.append(tp / i)
rec.append(tp / n_gt)
for i in range(len(prec) - 2, -1, -1):
prec[i] = max(prec[i], prec[i + 1])
total = 0.0
for k in range(101):
i = bisect_left(rec, k / 100)
if i < len(prec):
total += prec[i]
return total / 101
def coco_ap(dets_by_class, gts_by_class, area="all", max_dets=100,
thresholds=COCO_THRESHOLDS):
aps = []
for t in thresholds:
for cls, gts in gts_by_class.items():
ap = ap_101(dets_by_class.get(cls, []), gts, t, SIZE_RANGES[area], max_dets)
if ap is not None:
aps.append(ap)
return sum(aps) / len(aps) if aps else -1.0
gts = {"car": {"img1": [(0, 0, 100, 100), (200, 200, 220, 220)]}}
dets = {"car": [("img1", 0.9, (5, 0, 105, 100)),
("img1", 0.8, (202, 202, 222, 222))]}
print(f"AP {coco_ap(dets, gts):.4f}")
print(f"AP50 {coco_ap(dets, gts, thresholds=[0.5]):.4f}")
print(f"AP75 {coco_ap(dets, gts, thresholds=[0.75]):.4f}")
print(f"APs {coco_ap(dets, gts, area='small'):.4f}")
print(f"APm {coco_ap(dets, gts, area='medium'):.4f}")
print(f"APl {coco_ap(dets, gts, area='large'):.4f}")Running it prints:
AP 0.6525
AP50 1.0000
AP75 0.5050
APs 0.4000
APm -1.0000
APl 0.9000You can check these by hand:
- The large box has IoU 9500 / 10500 ≈ 0.905 with its detection. It is a true positive at every threshold up to 0.90 and a false positive at 0.95.
- The small box has IoU 324 / 476 ≈ 0.681. It is a true positive at the four thresholds 0.50 to 0.65 and a false positive at the other six.
- At 0.70 to 0.90 the ranked list is true positive, then false positive. The precision envelope is 1.0 up to recall 0.5 and 0 after it. That covers 51 of the 101 recall points, so AP = 51/101 ≈ 0.505.
- Averaging the ten thresholds gives (4 × 1.0 + 5 × 0.505 + 0) / 10 ≈ 0.6525.
- No ground truth is medium, so APm has nothing to average and returns -1.
Reading the numbers
- AP50 high and AP75 low means the detector finds objects but localizes them loosely.
- APs far below APl means small objects are the bottleneck. Higher input resolution or finer feature maps are common fixes.
- AP computed with
max_detsof 100 compared with AR at 1, 10 and 100 tells you how many boxes per image you need before recall saturates.
Common mistakes
- Using the VOC 11-point or all-point formula and calling the result COCO AP. The values differ slightly, so numbers are not comparable.
- Filtering ground truth by size instead of ignoring it. This turns correct detections of other sizes into false positives and understates APs and APl.
- Averaging per-image AP instead of pooling detections across images before building the curve. The curve must be built from the global ranking for each class.
- Averaging all ten thresholds into one number and forgetting that a single threshold such as 0.75 can behave differently.
- Counting classes with no ground truth as AP = 0 instead of leaving them out. That drags the mean down for no reason.
- Reporting results without stating the cap on detections or the area definition.
Exercise
A detector has AP50 = 0.80 and AP75 = 0.30. A second detector has AP50 = 0.72 and AP75 = 0.55. Without knowing the other thresholds, which one is likely to have the higher headline AP (mean over 0.50 to 0.95), and why?
Show answer
The second detector is likely to have the higher headline AP. Its AP drops by only 0.17 between thresholds 0.50 and 0.75, while the first drops by 0.50. Thresholds from 0.55 to 0.95 weigh the strict end heavily, with six of the ten at 0.70 or above. The first detector's accuracy collapses quickly as the threshold rises, which shows loose localization. The second detector holds up better, so its average is likely higher despite the lower AP50.
Exercise
You evaluate for "small" objects only. A detector outputs a box of area 5000 pixels that overlaps no ground truth at all. Does it count as a false positive in this evaluation? What if its area were 500 pixels?
Show answer
At 5000 pixels the box is outside the small range (above 1024) and matches nothing, so it is ignored and is not a false positive. At 500 pixels it is inside the small range and matches nothing, so it is a false positive.
Exercise
In the code above, why does coco_ap skip classes whose AP is None instead of counting them as 0?
Show answer
None means the class has no non-ignored ground truth under the current size range, so AP is undefined for it. Counting it as 0 would lower the mean for a reason unrelated to detector quality. The official tool marks these cells -1 and leaves them out of the mean.