Sub topic 5
Precision and recall from a ranked list of detections
This chapter assumes you can read basic Python and know what a detector outputs: a box, a class label, and a confidence score. It also assumes you know precision and recall from classification, and that you have seen the matching step from the previous chapter, which marks each detection as a true positive or a false positive. Here we turn those marks into precision and recall values. The next chapter plots them as a curve.
Why detection needs a different treatment
In classification, every example gets one prediction, so precision and recall come from a single confusion matrix. Detection differs in three ways.
- Each image has a variable number of predictions. A detector may output 0 or 300 boxes for one image.
- There are no true negatives. The number of possible boxes that correctly contain nothing is effectively unbounded, so metrics that need true negatives, such as accuracy and the false positive rate, are not used.
- Confidence scores can be swept. Raising or lowering a score threshold changes which detections count at all. A detector is therefore a family of operating points, not one set of predictions.
The ranked list is how we handle this. We pool all detections of one class from the whole dataset, sort them by score from highest to lowest, and then ask what precision and recall would be if we kept only the top k detections, for every k.
Definitions for detection
After matching, every detection of a class is either a true positive (TP) or a false positive (FP). Ground-truth boxes that no detection matched are false negatives (FN).
- A true positive is a detection that overlaps an unmatched ground-truth box of the same class at or above the IoU threshold.
- A false positive is any other detection. This includes boxes on background, boxes with the wrong class, boxes with IoU below the threshold, and duplicates of an object that a higher-scored detection already matched.
- A false negative is a ground-truth box that no detection matched.
Precision and recall then take their usual form:
- Precision = TP / (TP + FP) = TP / (number of detections kept)
- Recall = TP / (TP + FN) = TP / (number of ground-truth boxes)
Both denominators are simple. The precision denominator is how many detections you kept. The recall denominator is the number of ground-truth boxes for the class across the whole dataset. It does not depend on the detector at all.
From matching to a cumulative sweep
Suppose matching has produced a list of detections for one class, already sorted by score. Keeping the top k detections gives:
- TP(k): the number of true positives among the first k.
- FP(k): k minus TP(k).
- Precision(k) = TP(k) / k.
- Recall(k) = TP(k) / n_gt.
You compute these in one pass with a running count. The diagram shows the data flow.
The order of the first two steps matters. Matching must be done in descending score order, so that a high-confidence detection claims a ground-truth box before a lower-confidence duplicate can. If you match in file order instead, a low-scoring box can steal the match from a high-scoring one, and the flags change.
A worked example
Take one class with n_gt = 4 ground-truth boxes across the dataset. After matching, the six detections in descending score order are:
| Rank | Score | Flag | Cumulative TP | Cumulative FP | Precision | Recall |
|---|---|---|---|---|---|---|
| 1 | 0.95 | TP | 1 | 0 | 1.000 | 0.25 |
| 2 | 0.90 | TP | 2 | 0 | 1.000 | 0.50 |
| 3 | 0.80 | FP | 2 | 1 | 0.667 | 0.50 |
| 4 | 0.70 | TP | 3 | 1 | 0.750 | 0.75 |
| 5 | 0.60 | FP | 3 | 2 | 0.600 | 0.75 |
| 6 | 0.50 | FP | 3 | 3 | 0.500 | 0.75 |
Three things stand out in this table.
- Recall never decreases. It changes only at a TP row, where it rises by 1 / n_gt. At an FP row it stays flat.
- Precision moves both ways. It drops at each FP row and recovers at a TP row. The sequence 1.0, 1.0, 0.667, 0.75, 0.6, 0.5 is not monotone, and the next chapters deal with that.
- Recall stops at 0.75. One ground-truth box was never matched, so even if we keep every detection, recall cannot reach 1.0. That box is a false negative, and nothing in the detection list shows it.
Computing it in code
The function below takes the TP and FP flags in ranked order and returns precision and recall at every rank.
def precision_recall_points(tp_flags, n_gt):
"""Precision and recall after keeping the top k detections, for k = 1..N.
tp_flags: list of 1 (true positive) or 0 (false positive), in descending
score order.
n_gt: total number of ground-truth boxes for this class in the dataset.
Returns a list of (rank, precision, recall) tuples.
"""
points = []
cum_tp = 0
for rank, flag in enumerate(tp_flags, start=1):
cum_tp += flag
points.append((rank, cum_tp / rank, cum_tp / n_gt))
return points
tp_flags = [1, 1, 0, 1, 0, 0]
for rank, p, r in precision_recall_points(tp_flags, n_gt=4):
print(f"rank={rank} precision={p:.3f} recall={r:.3f}")Running it prints the same six rows as the table:
rank=1 precision=1.000 recall=0.250
rank=2 precision=1.000 recall=0.500
rank=3 precision=0.667 recall=0.500
rank=4 precision=0.750 recall=0.750
rank=5 precision=0.600 recall=0.750
rank=6 precision=0.500 recall=0.750The same numbers can be computed for a score threshold instead of a rank. This is closer to how a deployed system works: you choose a confidence cutoff, and everything scoring at or above it is kept.
def precision_recall_at(detections, n_gt, score_threshold):
"""Precision and recall when keeping detections with score >= threshold.
detections: list of (score, is_tp) pairs, is_tp being 1 or 0.
"""
kept = [d for d in detections if d[0] >= score_threshold]
tp = sum(is_tp for _, is_tp in kept)
precision = tp / len(kept) if kept else 0.0 # convention: nothing kept
recall = tp / n_gt
return precision, recall
detections = [(0.95, 1), (0.90, 1), (0.80, 0), (0.70, 1), (0.60, 0), (0.50, 0)]
for t in (0.99, 0.75, 0.55, 0.0):
p, r = precision_recall_at(detections, n_gt=4, score_threshold=t)
print(f"threshold={t:.2f} precision={p:.3f} recall={r:.3f}")This prints:
threshold=0.99 precision=0.000 recall=0.000
threshold=0.75 precision=0.667 recall=0.500
threshold=0.55 precision=0.600 recall=0.750
threshold=0.00 precision=0.500 recall=0.750At threshold 0.99 nothing is kept, so precision is 0/0. Libraries disagree on this case. Some return 0, some return 1, and some skip the point. The convention only matters at the edges, and the interpolation step in the average precision chapter makes it irrelevant for AP.
Plotting both quantities against rank
The following chart shows the two columns from the table. The first line is precision and the second is recall. Recall climbs in steps and flattens at 0.75. Precision falls at each false positive.
The trade-off and the operating point
Keeping more detections can only raise recall, because the list of TPs only grows. It tends to lower precision, because the low-scored tail contains proportionally more false positives. This is the same trade-off as in classification, but here the knob is the score threshold.
A common way to pick one threshold is to maximize F1, the harmonic mean of precision and recall:
F1 = 2 P R / (P + R)
In the worked example, F1 at rank 4 is 2 0.75 0.75 / 1.5 = 0.75, which is the highest value in the table. Rank 2 gives 2 1.0 0.5 / 1.5 = 0.667. If a missed object is much more costly than a false alarm, as in a safety system, choose a threshold with higher recall. If false alarms are expensive, as in automatic moderation, choose a threshold with higher precision. Mean average precision does not choose for you. It summarizes all the thresholds at once.
Edge cases and common errors
Ties in score
If several detections share a score, the order among them is arbitrary, and the cumulative values between them depend on that arbitrary order. A deployed system cannot split ties either: a threshold keeps all of them or none. Mature evaluators sort with a stable sort so that results are reproducible. For a faithful threshold-based curve, evaluate only at the end of each group of tied scores.
Pooling across images before ranking
Rank detections across the whole dataset, not per image. If you compute precision and recall per image and then average them, an image with one object and one detection counts as much as an image with fifty objects. Average precision is defined on the pooled ranked list, with n_gt summed over all images.
Computing per class
Precision and recall are computed separately for each class. A detection of class "dog" is matched only to ground-truth boxes of class "dog". A well-localized box with the wrong label is a false positive for the predicted class and also leaves the true class with a false negative.
Images with no ground truth for a class
Detections of a class on an image that has no boxes of that class are all false positives. They must stay in the pooled list. Dropping those images hides exactly the false alarms that precision is meant to count.
Ignored regions and difficult objects
Some datasets mark boxes as difficult, truncated, or crowd regions. Pascal VOC's difficult flag and COCO's crowd flag mean that a detection on such an object is neither a TP nor an FP, and the object is left out of n_gt. If your evaluator ignores these flags, your numbers will not match the official ones.
Using the wrong denominator for recall
The recall denominator is the number of ground-truth boxes, not the number of detections and not the number of images. A frequent bug is dividing by len(detections), which turns recall into precision.
Treating the score threshold and the IoU threshold as one thing
They do different jobs. The IoU threshold decides whether a single detection is a TP or an FP, and it is fixed before the sweep starts. The score threshold decides which detections are kept, and it is what the sweep varies. Changing the IoU threshold changes the TP and FP flags themselves, so it changes the whole table.
What this chapter sets up
You now have, for each class, a list of (precision, recall) pairs indexed by rank. The next chapter treats these pairs as points of a precision-recall curve, and the one after that integrates the curve into AP.
Exercise
A class has n_gt = 5 ground-truth boxes. After matching, the ranked flags are [1, 0, 1, 1, 0] (1 is a TP). What are the precision and recall after keeping the top 4 detections, and what is the highest recall this detector can reach on this class?
Show answer
After 4 detections there are 3 TPs (flags 1, 0, 1, 1). Precision is 3 / 4 = 0.75 and recall is 3 / 5 = 0.6. With all 5 detections the TP count is still 3, so the highest reachable recall is 3 / 5 = 0.6. The other 2 ground-truth boxes are false negatives.
Exercise
In the ranked list, recall can only stay the same or increase as you keep more detections, but precision can go up or down. Explain why, and say what happens to each when the next detection is a duplicate of an object that is already matched.
Show answer
Recall is TP / ngt, where ngt is fixed and TP never decreases as detections are added, so recall cannot fall. It rises only when the added detection is a TP. Precision is TP / k, and k grows by one at every step, so precision rises after a TP (if the new detection's TP raises the ratio) and falls after an FP. A duplicate of an already matched object is an FP: recall stays the same and precision drops, since TP is unchanged and k increases by one.