Sub topic 6
Building the Precision-Recall Curve
In the previous chapter, matching turned every detection into a true positive (TP) or a false positive (FP). This chapter turns that ranked list of outcomes into a precision-recall (PR) curve. The curve is the object that average precision (AP) measures in the next chapter.
What you need before this chapter
This chapter assumes you can do the following:
- Read and write basic Python (lists, loops,
sortedwith a key function). - Compute IoU for two boxes.
- Match detections to ground truth at an IoU threshold, so that each detection is a TP or an FP.
- Define precision as TP / (TP + FP) and recall as TP / (TP + FN) for a classifier.
From a ranked list to a curve
A detector returns a confidence score with each box. A score threshold decides which detections you keep: raise it and you keep fewer, lower it and you keep more. The PR curve shows what happens to precision and recall as the threshold sweeps from high to low.
You do not need to rerun the detector for each threshold. Sort all detections of one class by score, highest first. Keeping every detection with score at least s is the same as keeping a prefix of that sorted list. So the curve has one point per prefix.
For the first k detections in the ranked list:
TP(k)is the number of TPs among them, andFP(k) = k - TP(k).precision(k) = TP(k) / k.recall(k) = TP(k) / G, whereGis the total number of ground-truth boxes of this class across the whole dataset.
Detections that match nothing are FPs, and ground-truth boxes that are never matched are the false negatives (FN). The denominator of recall is TP + FN, which is always G. This is why the number of ground-truth boxes must be counted separately and never inferred from the detections.
A worked example
Suppose one image has three ground-truth boxes of one class, so G = 3:
- A = (0, 0, 10, 10)
- B = (20, 20, 30, 30)
- C = (40, 40, 50, 50)
The detector returns five boxes. After sorting by score and matching at IoU 0.5, we get this table.
| Rank | Score | Detection | Outcome | Cum. TP | Cum. FP | Precision | Recall |
|---|---|---|---|---|---|---|---|
| 1 | 0.95 | Exactly on A | TP | 1 | 0 | 1.000 | 0.333 |
| 2 | 0.90 | Empty background | FP | 1 | 1 | 0.500 | 0.333 |
| 3 | 0.80 | Exactly on B | TP | 2 | 1 | 0.667 | 0.667 |
| 4 | 0.70 | On C, IoU 0.81 | TP | 3 | 1 | 0.750 | 1.000 |
| 5 | 0.60 | Repeats A | FP | 3 | 2 | 0.600 | 1.000 |
Rank 5 is a duplicate. A was already claimed by rank 1, so the second box on A counts as an FP. It lowers precision and cannot raise recall.
The same numbers as two lines over rank:
Plotted as recall on the x-axis and precision on the y-axis, the curve passes through (0.333, 1.0), (0.333, 0.5), (0.667, 0.667), (1.0, 0.75), and (1.0, 0.6).
Computing the curve in code
The code below is self-contained. It includes IoU and a matching function that follows the Pascal VOC convention. Each detection is compared with its best-overlapping ground-truth box. If that box is already taken, the detection is an FP.
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)
] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_ter / union if union > 0 else 0.0
def match(detections, ground_truths, iou_threshold=0.5):
"""Return (scores, flending score order.
detections: list of (image_id, score, box)
ground_truths: dict mapping image_id -> list of boxes
flags[i] is 1 forfor a false positive.
"""
matched = {img: [False] * len(boxes) for img, boxes in ground_truths.items()}
scores, flags = [], []
orted(detections, key=lambda d: -d[1]):
best_iou, best_j = 0.0, -1
for j, gt in enumerate(ground_truths.
v = iou(box, gt)
if v > best_iou:
best_iou, best_j = v, j
if best_j >= 0 and best_iou >= iched[img][best_j]:
matched[img][best_j] = True
flags.append(1)
else:
flags.append(0)
scores.append(score)
returnr_curve(detections, ground_truths, iou_threshold=0.5):
"""Return (thresholds, precisions, recalls), one point per dist_gt = sum(len(boxes) for boxes in ground_truths.values())
scores, flags = match(detections, ground_truths, iou_threshold)
thresalls = [], [], []
cum_tp = 0
for k, (score, flag) in enumerate(zip(scores, flags), start=1):
cum_tp += flag
# Emit a point only after the last detection of a group of tied scores.
if k == len(scores) or scores[k] != score:
thresholds.append(score)
precisions.append(cum_tp / k)
recalls.append(cum_tp / n_gt if n_gt else 0.0)
return thresholds, precisions, recalls
gts = {"img1": [(0, 0, 10, 10), (20, 20, 30, 30), (40, 40, 50, 50)]}
dets = [
("img1", 0.95, (0, 0, 10, 10)),
("img1", 0.90, (60, 60, 70, 70)),
("img1", 0.80, (20, 20, 30, 30)),
("img1", 0.70, (41, 41, 50, 50)),
("img1", 0.60, (0, 0, 10, 10)),
]
th, p, r = pr_curve(dets, gts, 0.5)
print(th) # [0.95, 0.9, 0.8, 0.7, 0.6]
print([round(x, 3) for x in p]) # [1.0, 0.5, 0.667, 0.75, 0.6]
print([round(x, 3) for x in r]) # [0.333, 0.333, 0.667, 1.0, 1.0]The output matches the table. Two details are worth noting:
matchedis created fromground_truths, so an image with no ground truth still works, becauseground_truths.get(img, [])returns an empty list. All its detections become FPs.n_gtcounts boxes from the ground-truth dictionary, so images where the detector found nothing still contribute to the recall denominator.
Reading the shape of the curve
Recall as a function of rank never decreases. Each new detection either adds a TP, which increases recall, or an FP, which leaves it unchanged. Precision can move in both directions:
- An FP lowers precision, because
kgrows andTPdoes not. - A TP raises precision, because
TPandkboth grow by one and the ratio moves toward 1.
So the raw curve is a sawtooth. Each FP is a vertical drop at constant recall, and each TP is a move right and up. The small dips are one reason AP uses an interpolated precision envelope (next chapter), which replaces each precision with the maximum precision at any equal or higher recall.
Four shapes are worth recognizing:
- A curve that stays near precision 1.0 until recall is high belongs to a detector whose high-scoring boxes are almost all correct.
- A curve that drops early has confident false positives, often caused by duplicates or by background clutter.
- A curve that stops before recall 1.0 means some ground-truth boxes are never detected at any threshold, because the detector missed them or localized them below the IoU threshold.
- A curve with a long, flat precision plateau and a late cliff usually means the detector's scores are well calibrated. The cliff marks where the true objects run out.
Ties in the scores
When two detections have the same score, no threshold can separate them, so a single point should represent both. The code above emits a point only after the last detection of a tied group. If it emitted a point after every detection, the result would depend on the arbitrary order of the tied items. For example, a tie between one TP and one FP would give a curve that goes up first or down first depending on the input order.
With 16-bit or rounded scores, ties are common. Saturated detectors that output 1.000 for many boxes are the extreme case. Collapsing ties makes the curve deterministic.
Edge cases
| Situation | What happens to the curve | Usual convention |
|---|---|---|
| No detections for the class | The curve is empty | AP is 0 when ground truth exists |
| No ground truth for the class | Recall has a zero denominator | Skip the class, or report it as undefined (COCO tooling excludes it) |
| Every detection is an FP | Precision is 0 and recall stays 0 | AP is 0 |
| Detector never finds some boxes | The curve ends at recall below 1.0 | Missing recall counts as zero precision in AP |
| Duplicate detections | Extra FPs, with no gain in recall | No special handling, unless NMS removes them first |
| Boxes marked "difficult" or "crowd" | Not counted as ground truth, and matches to them are ignored | Defined by the dataset protocol |
One difference between protocols matters here. The code above follows the VOC convention, where a detection's best-overlapping ground-truth box decides its outcome. If that box is already taken, the detection is an FP even if another unmatched box also overlaps it. COCO tooling instead picks the best unmatched ground-truth box above the threshold. The two conventions give slightly different TP counts in crowded scenes.
Choosing an operating point
The PR curve is the whole trade-off. A deployed system uses one point on it, which is one score threshold. The thresholds list from pr_curve tells you which score produces each point, so you can pick one by a rule:
- Pick the first threshold where precision falls below a target, such as 0.9, if false alarms are costly.
- Pick the threshold with the highest recall at a minimum precision, if misses are costly.
- Pick the threshold that maximizes F1, where F1 = 2PR / (P + R), if you have no stronger preference.
AP does not tell you which threshold to use. It summarizes the curve across all thresholds, which is useful for comparing detectors but not for deployment.
Common errors
- Computing recall from detected images only. The denominator must be all ground-truth boxes of the class in the dataset, including those in images where the detector returned nothing.
- Mixing classes in one curve. Build one curve per class. A class-agnostic curve hides classes the detector handles badly.
- Pooling detections across images without keeping image IDs. Matching is per image. A detection in image 1 must never match a box in image 2.
- Counting duplicates as TPs. A ground-truth box can be matched once. Without the
matchedflags, a detector that outputs ten copies of one correct box would score ten TPs. - Filtering by a score threshold before building the curve. Dropping low-score detections truncates the curve and lowers the maximum recall. Evaluate with a very low threshold, such as 0.001, and let the sweep do the work.
- Using a different IoU threshold than you report. Each IoU threshold gives its own matching and so its own curve. A curve built at 0.5 says nothing about 0.75.
Summary of the procedure
- Collect all detections for one class across the dataset.
- Count the ground-truth boxes for that class, excluding any the protocol ignores.
- Sort the detections by score, descending.
- Match them one by one at the chosen IoU threshold, marking each ground-truth box as used once.
- Take cumulative TP and FP counts, and compute precision as TP / k and recall as TP / G at each rank (collapsing ties).
The result is the raw PR curve. The next chapter turns it into a single number by taking the area under its interpolated version.
Exercise
A class has 4 ground-truth boxes in the dataset. After sorting by score and matching, the outcomes by rank are TP, TP, FP, TP, FP, FP (no ties). Give precision and recall at rank 4 and at rank 6, and state the highest recall the curve reaches.
Show answer
At rank 4 the cumulative TP count is 3, so precision = 3/4 = 0.75 and recall = 3/4 = 0.75. At rank 6 the cumulative TP count is still 3, so precision = 3/6 = 0.5 and recall = 3/4 = 0.75. The highest recall reached is 0.75. One ground-truth box is never detected at an acceptable IoU, so the curve ends before recall 1.0.
Exercise
A colleague computes recall as TP(k) divided by the number of ground-truth boxes in images where the detector produced at least one detection. Why does this inflate the curve, and how do you fix it?
Show answer
Images where the detector found nothing contain ground-truth boxes that are false negatives, but this denominator leaves them out. The denominator is therefore too small and recall is too high. The fix is to use G, the total number of ground-truth boxes of the class across the whole dataset, regardless of whether any detection landed in that image.