Sub topic 13
Evaluating detectors with AP and mAP
This chapter assumes you know how IoU is computed, what NMS does, and how a detector produces scored boxes with class labels. It also assumes basic NumPy. Here you will learn how a set of scored boxes becomes a single number such as "AP 42.0", and which details change that number.
What evaluation has to decide
A detector outputs boxes with a class and a confidence score. Ground truth is a set of boxes with classes. Accuracy does not apply, because there are no fixed "correct answers" to count and no natural negative class. You must first decide which predictions count as correct, then summarize how well the ranking of predictions by score separates correct from incorrect ones.
Each prediction ends up as one of three things:
- A true positive (TP) is a prediction that matches a previously unmatched ground-truth box of the same class with IoU at or above a threshold.
- A false positive (FP) is any other prediction. It may be badly localized, wrongly classified, or a duplicate of a box that was already matched.
- A false negative (FN) is a ground-truth box that no prediction matched.
The duplicate rule is why NMS matters for evaluation. Two boxes on one object give one TP and one FP. DETR-style detectors avoid this through one-to-one matching during training. Anchor-based detectors rely on NMS at inference.
Precision and recall along the score ranking
Sort all predictions for one class, across the whole dataset, by descending score. Walk down the list and keep running counts of TP and FP. After each prediction:
- Precision is TP / (TP + FP), the fraction of predictions so far that are correct.
- Recall is TP / (number of ground-truth boxes), the fraction of objects found so far.
Plotting precision against recall gives the precision-recall curve. Going down the list, recall never decreases, while precision goes up and down. A confidence threshold picks one point on this curve. Average precision (AP) summarizes the whole curve, so it does not depend on any one threshold.
Computing AP
The precision curve is jagged. The standard fix is to replace each precision value with the maximum precision at any equal or higher recall. This gives a monotone envelope. AP is the area under that envelope.
The function below handles one class. It follows the Pascal VOC "all-point" convention. A detection whose best-IoU ground truth is already matched counts as an FP.
import numpy as np
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2)."""
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)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def average_precision(detections, gts, iou_thr=0.5):
"""Single-class AP.
detections: list of (image_id, score, box)
gts: dict image_id -> list of boxes
"""
n_gt = sum(len(v) for v in gts.values())
detections = sorted(detections, key=lambda d: d[1], reverse=True)
matched = {img: [False] * len(b) for img, b in gts.items()}
tp = np.zeros(len(detections))
fp = np.zeros(len(detections))
for k, (img, score, box) in enumerate(detections):
best_iou, best_j = 0.0, -1
for j, g in enumerate(gts.get(img, [])):
o = iou(box, g)
if o > best_iou:
best_iou, best_j = o, j
if best_iou >= iou_thr and not matched[img][best_j]:
matched[img][best_j] = True
tp[k] = 1
else:
fp[k] = 1
tp_c, fp_c = np.cumsum(tp), np.cumsum(fp)
recall = tp_c / n_gt
precision = tp_c / (tp_c + fp_c)
mrec = np.concatenate(([0.0], recall, [1.0]))
mpre = np.concatenate(([0.0], precision, [0.0]))
for i in range(len(mpre) - 2, -1, -1):
mpre[i] = max(mpre[i], mpre[i + 1])
idx = np.where(mrec[1:] != mrec[:-1])[0]
return float(np.sum((mrec[idx + 1] - mrec[idx]) * mpre[idx + 1]))
gts = {0: [(0, 0, 10, 10), (20, 20, 30, 30)], 1: [(0, 0, 10, 10)]}
dets = [
(0, 0.9, (0, 0, 10, 10)), # TP
(0, 0.8, (1, 1, 11, 11)), # duplicate of the same object: FP
(1, 0.7, (0, 0, 10, 10)), # TP
(0, 0.6, (20, 20, 30, 30)), # TP
(1, 0.5, (40, 40, 50, 50)), # no object there: FP
]
print(round(average_precision(dets, gts), 4)) # 0.8333Walking the example by hand shows the mechanism. After sorting, the sequence is TP, FP, TP, TP, FP. Recall rises to 1/3, 1/3, 2/3, 1, 1. Precision is 1, 0.5, 0.667, 0.75, 0.6. The envelope lifts the early dips to 0.75, so each of the three recall steps of size 1/3 contributes heights 1, 0.75 and 0.75. The sum is (1 + 0.75 + 0.75) / 3 = 0.8333.
Note that the late FP at score 0.5 costs nothing. It comes after full recall, so the envelope ignores it. Errors hurt AP only when they rank above true positives.
From AP to mAP
mAP is the mean of per-class AP. The details differ by benchmark:
| Benchmark | IoU threshold | Interpolation | Reported as |
|---|---|---|---|
| Pascal VOC 2007 | 0.5 | 11 recall points | mAP |
| Pascal VOC 2010+ | 0.5 | all points | mAP |
| COCO | 0.50 to 0.95 in steps of 0.05 | 101 recall points | AP (also called mAP) |
COCO's headline number averages over 10 IoU thresholds and all classes, so it rewards tight localization. A detector with good recall at IoU 0.5 but sloppy boxes loses a lot at 0.9. COCO also reports these variants:
- AP50 and AP75 use a single IoU threshold of 0.5 or 0.75.
- APs, APm and APl restrict to small (area under 32² pixels), medium, and large objects.
- AR (average recall) is measured at a fixed number of detections per image.
COCO also caps detections at 100 per image and matches each detection to the best still-unmatched ground truth. VOC-style code matches to the single best-IoU box. Ground-truth boxes marked as crowds are ignored rather than counted as FN. In COCO, "AP" and "mAP" mean the same thing.
You can approximate the COCO averaging over thresholds with the function above:
thresholds = np.arange(0.5, 1.0, 0.05) # 0.50, 0.55, ..., 0.95
ap_coco_style = np.mean([average_precision(dets, gts, t) for t in thresholds])This sketch only shows the structure. Use pycocotools for any reported number, since its matching and area rules are the reference.
Common errors
- Filtering by confidence before evaluation. Evaluate with a very low score threshold (for example 0.001) and keep the top 100 per image. A threshold of 0.5 truncates the curve and removes high-recall points.
- Comparing numbers across protocols. A VOC mAP at IoU 0.5 and a COCO AP cannot be compared. Neither can two COCO runs with different NMS settings or detection caps.
- Wrong box format. COCO JSON stores boxes as
[x, y, width, height], while the IoU code above expects corners. A format mismatch produces low AP with no error message. - Forgetting that scores must be comparable across images. AP ranks detections from the whole dataset together. If scores are calibrated differently per image, the ranking mixes them poorly.
- Reading AP as accuracy at deployment. AP does not say which threshold to use. Choose a threshold from the precision-recall curve for your cost of FP versus FN.
Exercise
In the example above, remove the duplicate detection with score 0.8 and keep the other four. What is the AP at IoU 0.5? Explain why.
Show answer
AP is 1.0. The ranking becomes TP, TP, TP, FP. Precision is 1, 1, 1, 0.75 and recall reaches 1 after the third detection. The only FP comes after full recall, so the monotone envelope gives precision 1 across all three recall steps of size 1/3, and 1/3 + 1/3 + 1/3 = 1.0.
Exercise
A detector has AP50 of 60 but AP75 of 25. What does this say about its errors, and which part of the pipeline would you inspect first?
Show answer
It finds most objects but its boxes are loosely localized, since matches fail once the IoU requirement tightens. Inspect the box regression branch: the box loss, the encoding and decoding of offsets, and the quality of label assignment for positives.