Sub topic 7
Average precision: area under the interpolated curve
This chapter turns a ranked list of detections into one number for one class. It assumes you can already compute IoU, mark each detection as a true positive (TP) or false positive (FP) against a threshold, and read a precision-recall curve. Basic Python is enough for the code.
What AP measures
A detector outputs boxes with confidence scores. Precision and recall depend on the score cutoff you choose. A high cutoff gives few detections that are mostly right (high precision, low recall). A low cutoff finds more objects but adds false alarms (higher recall, lower precision).
Average precision (AP) summarizes the whole trade-off for one class at one IoU threshold. It is the area under the precision-recall curve. Because the curve is traced by sweeping the cutoff from high to low, AP does not depend on any single cutoff. A detector is rewarded for ranking its correct boxes above its wrong ones.
AP is a number between 0 and 1. A value of 1 means every ground-truth object was found and no false positive ranked above a true positive.
Step 1: precision and recall at every rank
Sort the detections by score, highest first. Walk down the list. After each detection, compute:
- precision = cumulative TP / number of detections so far
- recall = cumulative TP / total ground-truth objects (TP + FN)
The recall denominator is the number of ground-truth boxes, not the number of detections. Ground-truth objects that no detection ever matches are false negatives, and they cap the maximum recall below 1.
Here is a worked example. A class has 2 ground-truth boxes. The three highest-scoring detections come out as FP, TP, TP.
| Rank | Label | Cumulative TP | Precision | Recall |
|---|---|---|---|---|
| 1 | FP | 0 | 0/1 = 0.000 | 0.0 |
| 2 | TP | 1 | 1/2 = 0.500 | 0.5 |
| 3 | TP | 2 | 2/3 = 0.667 | 1.0 |
Precision goes up from rank 2 to rank 3. Real curves are saw-toothed: precision falls after every FP and jumps after each TP. That raises the question of how to take an area under such a curve.
Step 2: the interpolated curve
The raw curve is not monotonic, and its exact shape depends on tiny ordering changes. The standard fix is the precision envelope. At each recall level r, you replace the precision with the highest precision found at any recall greater than or equal to r:
p_interp(r) = max of p(r') over all r' ≥ r
The justification is practical. If you can reach recall 1.0 with precision 0.667, then for any lower recall you could also choose that operating point and get at least 0.667. The envelope reports the best precision available at that recall or higher. It also removes the zigzags, so the curve becomes a non-increasing staircase.
Computing the envelope takes one pass from the end of the list to the start, keeping a running maximum. In the table above, the precision at rank 2 (0.5) is replaced by 0.667, and the precision at rank 1 (0.0) is replaced by 0.667 too.
Step 3: sentinels and the area
To integrate, add a point at each end of the curve:
- A recall of 0.0 at the start, with precision 0.0 before the envelope.
- A recall of 1.0 at the end, with precision 0.0.
The start sentinel gives the first rectangle a left edge. The end sentinel handles detectors that never reach full recall. If the detector's highest recall is 0.75, the segment from 0.75 to 1.0 gets precision 0, so the missed objects count against the AP. Without this sentinel, a detector that finds one object perfectly and ignores the rest would score 1.0.
After the envelope pass, the area is a sum of rectangles. For each point i, take the recall gained since the previous point and multiply it by the envelope precision at point i:
AP = sum over i of (ri − r(i−1)) × p_interp(i)
Points where recall does not change (consecutive FPs) contribute zero width, so only the TP steps add area.
Applying this to the table: the padded recalls are [0, 0, 0.5, 1.0, 1.0] and the envelope precisions are [0.667, 0.667, 0.667, 0.667, 0.0]. The rectangles are 0 × 0.667, 0.5 × 0.667, 0.5 × 0.667 and 0 × 0, so AP = 0.667.
Code: AP from a list of TP flags
This version works from the TP/FP flags of the ranked list, so you can check your hand calculations. It also has a switch to turn the envelope off, so you can see its effect.
def pr_from_flags(tp_flags, n_gt):
"""Cumulative precision and recall for a ranked list.
tp_flags: list of 1 (TP) or 0 (FP), already sorted by score descending.
n_gt: total number of ground-truth boxes for the class.
"""
precisions, recalls = [], []
cum_tp = 0
for rank, flag in enumerate(tp_flags, start=1):
cum_tp += flag
precisions.append(cum_tp / rank)
recalls.append(cum_tp / n_gt)
return recalls, precisions
def ap_from_pr(recalls, precisions, envelope=True):
"""Area under the precision-recall step curve with sentinel points."""
r = [0.0] + list(recalls) + [1.0]
p = [0.0] + list(precisions) + [0.0]
if envelope:
for i in range(len(p) - 2, -1, -1):
p[i] = max(p[i], p[i + 1])
return sum((r[i] - r[i - 1]) * p[i] for i in range(1, len(r)))
def eleven_point_ap(recalls, precisions):
"""Pascal VOC 2007 metric: mean of the best precision at 11 recall levels."""
total = 0.0
for k in range(11):
t = k / 10
total += max((p for r, p in zip(recalls, precisions) if r >= t), default=0.0)
return total / 11
recalls, precisions = pr_from_flags([0, 1, 1], n_gt=2)
print(round(ap_from_pr(recalls, precisions), 4)) # 0.6667
print(round(ap_from_pr(recalls, precisions, envelope=False), 4)) # 0.5833
print(round(eleven_point_ap(recalls, precisions), 4)) # 0.6667
# One ground-truth object is never found, so recall stops at 0.5.
recalls, precisions = pr_from_flags([1, 0, 0], n_gt=2)
print(round(ap_from_pr(recalls, precisions), 4)) # 0.5The second line shows what the envelope does. Without it, the precision of 0.5 at rank 2 is used for the first recall step, and the area drops to 0.5833. The last case shows the end sentinel: the detector's first detection is perfect, but the second object is never found, so AP is 0.5 instead of 1.0.
Interpolation variants
Three versions of "area under the interpolated curve" are in common use. They give different numbers for the same detections, so you need to know which one a paper or tool used.
| Variant | Used by | How it samples the curve |
|---|---|---|
| 11-point | Pascal VOC 2007 | Average the envelope precision at recall 0.0, 0.1, ..., 1.0 |
| All-point | Pascal VOC 2010 and later | Exact area under the envelope staircase, as in this chapter |
| 101-point | COCO | Average the envelope precision at recall 0.00, 0.01, ..., 1.00 |
The 11-point method is a coarse approximation of the area. It also has a quirk: because recall 0.0 is always one of the sample points, even a detector with a single correct detection gets credit at that point. The all-point method removes the sampling error. COCO's 101-point method is close to the exact area but uses a fixed grid, so it is fast to compute and easy to compare across implementations.
The numbers differ only slightly for a well-populated class. They can differ noticeably for a class with very few ground-truth boxes, where each TP is a big recall step.
Edge cases that change AP
- No ground truth for the class. Recall is undefined (division by zero). Pick a convention and state it. The reference code in this tutorial returns 0.0, while COCO tools skip the class entirely so it does not drag down the mean.
- No detections for a class that has ground truth. The curve has no points, only the sentinels, so AP is 0.
- Tied scores. The order of equal-score detections changes the sequence of TP and FP flags, and so the curve. Use a stable sort so results are reproducible. Better still, make sure your detector does not emit large groups of identical scores.
- Duplicate detections. A second box on an already-matched object is an FP, as the matching chapter showed. Duplicates that rank above true positives lower precision at the recall levels that follow them, so suppress them with NMS first.
- Very low score cutoffs. Evaluate with a low confidence threshold, such as 0.001, and let AP do the thresholding. If you pre-filter at 0.5 before evaluation, you cut the curve off early, recall stops short, and the end sentinel gives you a lower AP than the detector deserves.
- Floating-point comparisons. The 11-point code compares recall to k/10. Ground-truth counts that are not factors of 10 produce recalls such as 0.30000000000000004, which can fall just on the wrong side of a threshold. Add a small tolerance if you need bit-exact agreement with a reference implementation.
Common mistakes
- Skipping the sort. Precision and recall are only meaningful along a ranking. Unsorted detections give an arbitrary curve.
- Forgetting the envelope. The raw area is lower and noisier than the standard AP, so your result will not match the official tools.
- Missing the end sentinel. Detectors that miss objects get inflated scores.
- Using detection count as the recall denominator. Recall is relative to ground truth.
- Mixing variants. Comparing an 11-point VOC 2007 number with a COCO 101-point number is not a like-for-like comparison.
- Pooling classes. AP is computed for each class from its own ranked list. Pooling all classes into one list and computing one AP lets a class with many confident detections hide the others. The next chapter covers how per-class AP values are averaged.
Checking the repository-style function
The spine's reference function average_precision performs all of the steps in this chapter in one place: it sorts, matches, builds the cumulative lists, pads with sentinels, applies the backward envelope loop and sums the rectangles. For the three detections in its example (one exact match, one duplicate with IoU 0.81 against an already matched box, one exact match of the second object), the TP flags are [1, 0, 1]. Precisions are 1.0, 0.5, 0.667 and recalls are 0.5, 0.5, 1.0. The envelope keeps 1.0 for the first segment and lifts 0.5 to 0.667, so AP = 0.5 × 1.0 + 0.5 × 0.667 = 0.833. You can confirm it with ap_from_pr on the same flags:
recalls, precisions = pr_from_flags([1, 0, 1], n_gt=2)
print(round(ap_from_pr(recalls, precisions), 4)) # 0.8333The duplicate cost about 0.17 of AP even though it overlapped a real object well. Its high score put an FP ahead of the second true positive.
Exercise
A class has 4 ground-truth boxes. After sorting by score, the detections are labeled TP, FP, TP, FP, TP, and the fourth object is never detected. Compute the precision and recall at each rank, apply the envelope, and compute the all-point AP.
Show answer
Precisions are 1/1 = 1.0, 1/2 = 0.5, 2/3 = 0.667, 2/4 = 0.5, 3/5 = 0.6. Recalls are 0.25, 0.25, 0.5, 0.5, 0.75. Padded recalls are [0, 0.25, 0.25, 0.5, 0.5, 0.75, 1.0] and padded precisions are [0, 1.0, 0.5, 0.667, 0.5, 0.6, 0]. Running the envelope from the end gives [1.0, 1.0, 0.667, 0.667, 0.6, 0.6, 0]. The areas are 0.25 × 1.0 + 0 + 0.25 × 0.667 + 0 + 0.25 × 0.6 + 0.25 × 0 = 0.25 + 0.1667 + 0.15 = 0.5667. The last 0.25 of recall contributes nothing because the fourth object was missed.
Exercise
Why does the envelope replace each precision with the maximum precision at any higher recall, and what happens to AP if you skip it?
Show answer
At recall r, any operating point with recall of at least r is available by lowering the score cutoff, so the best precision you can get at that recall or higher is the maximum over the later points. The envelope removes the zigzag caused by FPs that fall between TPs. Skipping it lowers AP whenever precision rises after a dip. In the chapter's example, flags [0, 1, 1] with 2 ground-truth boxes give 0.6667 with the envelope and 0.5833 without it.
Exercise
A detector's output is filtered to keep only boxes with a score of at least 0.5 before evaluation. Why can this lower AP, and what threshold should be used instead?
Show answer
Filtering removes the low-score tail of the ranking, which holds the detections that would have raised recall. The curve then stops at a lower maximum recall, and the end sentinel assigns zero precision to the rest of the recall range. For evaluation, keep detections down to a very low threshold such as 0.001 so that the full curve is traced, and let AP integrate over the score cutoffs.