Sub topic 12
Evaluating a detector with precision, recall and mAP
This chapter assumes you can compute intersection over union (IoU), you know how non-maximum suppression (NMS) removes duplicate boxes, and you have trained or run a YOLO model. Here you will learn how to turn a model's boxes into numbers that say how good it is.
Why accuracy does not work for detection
A classifier gets one label per image, so "percent correct" makes sense. A detector returns a variable number of boxes per image. Each box can be wrong in three ways: wrong class, wrong place, or not there at all. The detector can also miss objects entirely. Detection metrics therefore need a rule for deciding when a predicted box counts as correct, and they need to handle both false alarms and misses.
Matching predictions to ground truth
Every metric in this chapter starts from the same step: matching predicted boxes to ground-truth boxes. For one class at a chosen IoU threshold, the usual procedure is:
- Sort the predictions by confidence, highest first.
- For each prediction, find the unmatched ground-truth box of the same class with the highest IoU.
- If that IoU is at least the threshold, the prediction is a true positive (TP), and that ground-truth box is marked as used.
- Otherwise the prediction is a false positive (FP).
- Any ground-truth box left unmatched at the end is a false negative (FN).
Each ground-truth box can be matched only once. If two predictions cover the same object, the first one (higher confidence) is a TP and the second is an FP. This is why duplicate boxes that survive NMS lower your precision.
The IoU threshold is part of the definition of "correct". A box with IoU 0.6 is a TP at threshold 0.5 and an FP at threshold 0.75.
Precision and recall
Once you have counts of TP, FP and FN, two ratios describe the result.
- Precision = TP / (TP + FP). Of the boxes the model drew, the fraction that were right.
- Recall = TP / (TP + FN). Of the real objects, the fraction the model found.
They pull against each other. A high confidence cutoff keeps only certain predictions, so precision rises and recall falls. A low cutoff finds more objects but adds false alarms.
| Situation | Precision | Recall |
|---|---|---|
| Model draws many spurious boxes | Low | Often high |
| Model draws only a few, very safe boxes | High | Low |
| Model draws exact boxes for every object | High | High |
True negatives (background regions with no box) are not counted. There are effectively unlimited places where no box should be, so metrics that use them would be meaningless.
The precision-recall curve and average precision
A single precision and recall pair depends on one confidence cutoff. To remove that dependence, sweep the cutoff from high to low. Walking down the sorted predictions, you recompute cumulative TP and FP after each box, which gives a precision and a recall value at each step. Plotting precision against recall gives the precision-recall (PR) curve.
Average precision (AP) is the area under that curve for one class. A model with high precision at every recall level has an AP near 1.0. A model whose precision collapses as soon as recall grows has a small AP.
Implementations differ in how they compute the area. Older Pascal VOC used 11 sample points. COCO uses 101 recall points. Ultralytics uses the 101-point interpolated method, after making the precision curve monotonically non-increasing (each point takes the maximum precision at any higher recall).
The code below computes AP for a single class from predictions that have already been marked TP or FP. It is a teaching version of the same idea.
import numpy as np
def average_precision(scores, is_tp, n_gt):
# scores: confidence per prediction; is_tp: 1 if matched, else 0
# n_gt: number of ground-truth boxes for this class
order = np.argsort(-np.asarray(scores))
tp = np.asarray(is_tp, dtype=float)[order]
fp = 1.0 - tp
tp_cum = np.cumsum(tp)
fp_cum = np.cumsum(fp)
recall = tp_cum / n_gt
precision = tp_cum / (tp_cum + fp_cum)
# Make precision non-increasing as recall grows.
precision = np.maximum.accumulate(precision[::-1])[::-1]
# 101-point interpolation, as in COCO.
grid = np.linspace(0, 1, 101)
ap = 0.0
for r in grid:
idx = np.searchsorted(recall, r, side="left")
ap += precision[idx] if idx < len(precision) else 0.0
return ap / 101
scores = [0.95, 0.90, 0.80, 0.70, 0.60]
is_tp = [1, 1, 0, 1, 0]
print(round(average_precision(scores, is_tp, n_gt=4), 3))Here four objects exist but the model found only three, so recall never exceeds 0.75. Recall points above 0.75 contribute zero, which caps the AP below 1.
From AP to mAP
Mean average precision (mAP) is the mean of AP over all classes. If you have a cat class with AP 0.80 and a dog class with AP 0.60, mAP is 0.70. Averaging per class stops a common class from hiding poor results on a rare one.
You will see two variants on YOLO reports.
- mAP50 (also written [email protected]): AP computed with a match threshold of IoU 0.5, then averaged over classes. It is forgiving about box placement.
- mAP50-95: AP computed at ten thresholds, 0.50, 0.55, up to 0.95, then averaged. It rewards tight boxes. This is the main COCO metric.
The two numbers answer different questions. A model with mAP50 of 0.90 and mAP50-95 of 0.50 finds objects reliably but localizes them loosely. If your application only needs to know whether something is present, mAP50 matters more. If you measure sizes or crop the boxes, watch mAP50-95.
Evaluating with Ultralytics
You do not need to write this yourself in practice. The val method runs the model on the validation split and reports all of these numbers.
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
metrics = model.val(data="my_data.yaml", conf=0.001, iou=0.6)
print("precision:", metrics.box.mp)
print("recall:", metrics.box.mr)
print("mAP50:", metrics.box.map50)
print("mAP50-95:", metrics.box.map)
for i, ap in zip(metrics.box.ap_class_index, metrics.box.maps[metrics.box.ap_class_index]):
print(model.names[int(i)], round(float(ap), 3))metrics.box.mp and metrics.box.mr are mean precision and mean recall across classes at the confidence that maximizes F1. The last loop prints mAP50-95 per class, which shows where the model is weak.
Note the low conf=0.001. Validation should use a very low confidence cutoff so the PR curve reaches high recall. If you validate at conf=0.25, the curve is cut short and mAP is underestimated. This setting is the default in val, so only change it on purpose.
Reading the results
Look at more than one number.
- Per-class AP. A low mean can come from one class. Check it before changing anything global.
- Confusion matrix. Ultralytics saves one in the run folder. It shows whether errors are class confusions (cat predicted as dog), missed objects (ground truth with no prediction), or background false alarms.
- F1 curve. F1 is the harmonic mean of precision and recall. The confidence value where the F1 curve peaks is a good starting point for your deployment threshold. The next chapter covers threshold choice.
- Train versus validation gap. High training mAP with low validation mAP suggests overfitting.
Pitfalls
- Evaluating on training data. The numbers look excellent and mean nothing. Keep a validation split the model never trained on, and ideally a separate test split for the final report.
- Comparing across different settings. mAP changes with the IoU threshold, image size and NMS settings. Compare models only under identical conditions.
- Tiny validation sets. A class with five validation instances gives a very noisy AP. One missed box can change it by 0.2.
- Label errors. If ground truth is missing or wrong, correct detections count as false positives. Low precision with plausible-looking boxes often points to bad labels, not a bad model.
- Confusing mAP with accuracy. mAP of 0.5 does not mean "half the boxes are right". It is an area under curves averaged across classes and thresholds.
Exercise
A detector has three ground-truth cats in an image. It outputs four cat boxes with confidences 0.9, 0.8, 0.7 and 0.6. The boxes with 0.9 and 0.7 match two different cats at IoU above 0.5. The 0.8 box overlaps the same cat as the 0.9 box (IoU 0.7 with it). The 0.6 box lies on the background. At a confidence cutoff of 0.5, what are the precision and recall?
Show answer
Ground truth for the 0.8 box: the cat it overlaps is already matched to the 0.9 box, so the 0.8 box is a false positive (duplicate). The 0.6 box is also a false positive. So TP = 2, FP = 2, FN = 1 (one cat was never matched). Precision = 2 / (2 + 2) = 0.5. Recall = 2 / (2 + 1) = 0.67.
Exercise
A model reports mAP50 of 0.88 and mAP50-95 of 0.41. What does the gap tell you, and what would you inspect next?
Show answer
The model finds and classifies objects well, since boxes pass the loose 0.5 IoU test. It fails the stricter thresholds, so its boxes are loosely placed. Inspect the box labeling quality (are annotations tight and consistent?), the image size used for training and validation (small objects lose precision at low resolution), and the box loss during training.