Sub topic 2
Precision and recall from a ranked list of detections
This chapter assumes you can write basic Python with lists and loops, that you know what a bounding box and an IoU score are, and that you understand true positives (TP) and false positives (FP) from the matching step. Precision and recall are the only metrics used here, so no other background is needed.
Precision and recall per rank
A detector outputs many boxes, each with a confidence score. Sort them from highest to lowest score. Then walk down the list and mark each detection as TP or FP. Detections that match an unmatched ground-truth box at IoU ≥ 0.5 count as TP.
At each rank k, two values follow from the running counts:
- Precision = TP so far / k (how many of the top k predictions were correct)
- Recall = TP so far / total ground-truth boxes (how many real objects have been found)
Building the precision-recall curve
Compute one (recall, precision) pair per rank. Plotting these pairs gives the precision-recall curve. Recall never decreases as you move down the list, but precision can go up or down.
def pr_points(tp_flags, n_gt):
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 precisions, recalls
def average_precision(tp_flags, n_gt):
precisions, recalls = pr_points(tp_flags, n_gt)
# Interpolate: each precision becomes the max precision at equal or higher recall.
for i in range(len(precisions) - 2, -1, -1):
precisions[i] = max(precisions[i], precisions[i + 1])
ap = 0.0
prev_recall = 0.0
for p, r in zip(precisions, recalls):
ap += (r - prev_recall) * p
prev_recall = r
return ap
tp = [1, 0, 1, 1, 0] # ranked TP (1) and FP (0) flags
print(average_precision(tp, n_gt=4)) # 0.625Average precision as area under the interpolated curve
After interpolation, AP is the area under the precision-recall curve. The code above uses all-point interpolation: it multiplies each recall increase by the interpolated precision at that step and adds the results.
For the example list, recall rises 0 → 0.25 → 0.50 → 0.75. The interpolated precisions are 1.0, 0.75, and 0.75. The area is 0.25 × 1.0 + 0.25 × 0.75 + 0.25 × 0.75 = 0.625.
Exercise
Using tp = [1, 1, 0, 0] and n_gt = 2, what are the precision and recall at rank 4, and what is the AP?
Show answer
At rank 4, precision is 2/4 = 0.5 and recall is 2/2 = 1.0. The interpolated precisions are 1.0, 1.0, 0.5, 0.5. Recall steps are 0.5 and 0.5, so AP = 0.5 × 1.0 + 0.5 × 0.5 = 0.75.