Sub topic 10
Pitfalls: thresholds, duplicates, class imbalance, and comparing numbers
This chapter assumes you can already compute IoU, match detections to ground truth, and turn a ranked list into a precision-recall curve and an AP value. Those are the iou and average_precision functions from the earlier chapters. Here the focus is on how a correct implementation still produces numbers that are misleading or not comparable.
Most evaluation errors fall into four groups:
- Where you cut the ranked list.
- How you treat several detections of the same object.
- How you average over classes.
- Which protocol produced a number you are comparing against.
Pitfall 1: the score threshold
AP is computed from the whole ranked list of detections, so the list must be long. The detector should output everything above a very low confidence, typically 0.001, and the metric then decides which operating points matter.
If you filter at the deployment threshold first (say 0.5), you cut the right side of the precision-recall curve. Recall can never exceed the fraction of objects the surviving detections cover, and the area beyond that point counts as zero. The result is an AP that measures your threshold choice, not your detector.
The script below builds four ground-truth objects and five detections. One detection is a false positive, scored between the true positives. It computes AP on the full list, then again after filtering at 0.5.
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 = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
return inter / union if union > 0 else 0.0
def average_precision(detections, ground_truths, iou_threshold=0.5):
n_gt = sum(len(boxes) for boxes in ground_truths.values())
if n_gt == 0:
return 0.0
matched = {img: [False] * len(b) for img, b in ground_truths.items()}
tp = []
for img, score, box in sorted(detections, key=lambda d: -d[1]):
best_iou, best_j = 0.0, -1
for j, gt in enumerate(ground_truths.get(img, [])):
v = iou(box, gt)
if v > best_iou:
best_iou, best_j = v, j
if best_j >= 0 and best_iou > not matched[img][best_j]:
matched[img][best_j] = True
tp.append(1)
else:
tp.append(0)
precisions, recalls, [], 0
for i, t in enumerate(tp, start=1):
cum_tp += t
precisions.append(cum_tp / i)
recalls.append(gt)
recalls = [0.0] + recalls + [1.0]
precisions = [0.0] + precisions + [0.0]
for i in range(len(precis, -1):
precisions[i] = max(precisions[i], precisions[i + 1])
return sum((recalls[i] - recalls[i - 1]) * precis in range(1, len(recalls)))
gts = {"img1": [(0, 0, 10, 10), (20, 0, 30, 10), (40, 0, 50, 70, 10)]}
dets = [
("img1", 0.95, (0, 0, 10, 10)),
("img1", 0.85, (20, 0, 30, 10)),
("img1", 0.60, (0, 50, 10, 60)), # false positive
("img1", 0.45, (40, 0, 50, 10)),
("img1", 0.30, (60, 0, 70, 10)),
]
full = average_precision(dets, gts)
filtered = average_precision([d for d in dets if d[1] >= 0.5], gts)
print(f"AP, all detections: {full:.3f}") # 0.900
print(f"AP, filtered at 0.5: {filtered:.3f}") # 0.500Filtering drops AP from 0.900 to 0.500 although the detector did not change. The two low-scored true positives were discarded, so recall stopped at 0.5.
The opposite mistake also exists. Tuning a deployment threshold from the AP number alone is wrong, because AP does not say which threshold to use. Pick the threshold from the precision-recall curve at the precision or recall your application needs.
Pitfall 2: duplicate detections
A detector usually proposes several overlapping boxes around one object. The matching rule treats every box after the first as a false positive, because each ground-truth box can be matched only once. Non-maximum suppression (NMS) removes most of these duplicates before evaluation.
Three things can go wrong.
- No NMS, or NMS applied across classes by mistake. Without NMS the evaluation counts the duplicates as false positives and precision drops. Running NMS across all classes at once instead of per class suppresses valid boxes. A person sitting on a horse produces overlapping boxes that are both correct.
- NMS IoU threshold too low. A threshold of 0.3 removes true detections in crowded scenes, where genuine objects overlap. This lowers recall in exactly the images that are hardest. A threshold of 0.5 to 0.7 is common, and the right value depends on how crowded your data is.
- Duplicates that rank low. A duplicate's cost depends on where it falls in the ranking. A duplicate scored above a later true positive pushes precision down at every recall level the later true positive could have reached. A duplicate scored below every true positive can cost nothing in AP, because the precision envelope only looks at precision to the right of each recall value.
The last point means AP can hide a duplicate problem that a fixed-threshold metric exposes. Report precision and recall at your deployment threshold alongside AP.
A subtle matching difference
The matching code in this tutorial follows the Pascal VOC rule. Each detection finds the ground-truth box with the highest IoU. If that box is already matched, the detection is a false positive, even when a second, unmatched ground-truth box also overlaps it above the threshold.
The COCO tools use a different rule. A detection is matched to the best unmatched ground-truth box above the threshold. In crowded scenes the two rules give different true-positive counts. This is one reason you should not mix evaluators when comparing numbers.
Pitfall 3: class imbalance
mAP is a macro average. Each class contributes its own AP, and the classes are weighted equally.
- A class with 3 ground-truth boxes counts as much as a class with 30,000. Its AP is also much noisier, because one extra match shifts recall by a third.
- A class absent from the test set has no recall. The code in this tutorial returns 0.0 for it, which drags the mean down. Many libraries skip such classes instead. Decide this on purpose, and check which behavior your library uses.
- A frequent class can dominate the error budget in practice, while mAP barely moves if it is one class among eighty.
Average precision is also not a function of class frequency alone, so you cannot recover an overall detection rate from it. When classes matter unevenly, report the per-class table next to the mean. Look at the number of ground-truth boxes per class, so you can tell a weak class from a noisy one.
The diagram shows where each pitfall enters the evaluation pipeline.
Pitfall 4: comparing numbers that are not comparable
Two papers can both report "mAP" and mean different things. Before comparing, check each item in the table.
| Setting | Common variants | Effect on the number |
|---|---|---|
| IoU threshold | 0.5 only, or the mean over 0.50 to 0.95 | AP at 0.50:0.95 is much lower than AP at 0.5, since strict thresholds punish loose boxes |
| AP interpolation | 11-point (old VOC), all-point envelope (VOC 2010 onward), 101-point (COCO) | Differences are usually small, but they can reorder close results |
| Max detections per image | 100 in COCO, unlimited elsewhere | Capping detections can reduce recall in dense images |
| Object size | all, small, medium, large | Small-object AP is usually the lowest and may be hidden by the all-sizes number |
| Ignored boxes | VOC "difficult" flags, COCO crowd regions | Detections on ignored objects are not counted as false positives |
| Box coordinates | pixel or normalized, xyxy or xywh | A format mix-up silently yields wrong IoU |
| Test split | val or test, with or without server evaluation | Tuning on the evaluation split inflates the number |
| Image resolution | training and test sizes, test-time augmentation | A better result may come from more computation, not a better model |
Two further traps are worth naming.
- Mixing the box formats. If the ground truth is
(x, y, w, h)and the predictions are(x1, y1, x2, y2), the code still runs and returns plausible-looking IoU values. Convert both to one format at the boundary and assertx1 < x2andy1 < y2there. - Different evaluators. The same predictions give a slightly different mAP in the official COCO tools, a reimplementation, and a training framework's built-in validation. Report which tool you used, with its version.
Reading mAP honestly
A single mAP value hides the structure of the errors. A short checklist for a report you can trust:
- State the protocol: IoU thresholds, interpolation, max detections, and the tool and version.
- Give AP at 0.5 and at 0.75 as well as the average over thresholds. A large gap between them means the boxes are found but poorly localized.
- Give per-class AP with ground-truth counts.
- Give precision and recall at the threshold you will deploy.
- Evaluate on data the model never trained or tuned on.
- Say how much AP varies. Differences smaller than the run-to-run spread are not evidence that one model is better.
Summary of the pitfalls
- Evaluate with a very low score threshold, then choose a deployment threshold from the precision-recall curve.
- Apply NMS per class with a threshold suited to how crowded the scenes are.
- Know which matching rule your evaluator uses.
- Treat per-class AP for rare classes as noisy, and decide how classes with no ground truth are handled.
- Compare mAP values only when the protocol, tool, and data split are the same.
Exercise
A test image has one ground-truth box. The detector outputs two boxes on it, both with IoU above 0.5. The scores are 0.9 and 0.8. What is the AP at IoU 0.5 using the all-point envelope, and what is the precision of the full list?
Show answer
The 0.9 box is a true positive and the 0.8 box is a false positive, because the ground-truth box is already matched. The precision values are 1.0 and 0.5, and the recall values are 1.0 and 1.0. After padding and applying the envelope, the precision at recall 1.0 is 1.0, so AP is 1.0. The precision of the full list is 0.5. The duplicate costs nothing in AP because it ranks after the point where recall reached 1.0, but it halves precision at a deployment threshold of 0.8 or lower.
Exercise
You evaluate a model after discarding all detections with score below 0.3 and get an AP of 0.62. A colleague evaluates the same model with a score floor of 0.001 and gets 0.71. Which number should you report for mAP, and why do they differ?
Show answer
Report the 0.71, which comes from the low floor. The 0.3 filter removes low-scored true positives, so recall stops early and the precision-recall area beyond that recall counts as zero. The model is the same, so the gap comes from the filter alone. The 0.62 reflects one operating point, and the better way to show it is as precision and recall at that threshold.