Sub topic 8
Mean Average Precision Across Classes
Prerequisites
This chapter assumes you can compute IoU between two boxes and that you have seen how a ranked list of detections for one class becomes a precision-recall curve and an average precision (AP) value. It also assumes you can read short Python functions that use lists, dictionaries and tuples. If AP still feels shaky, review the previous chapter first. This chapter takes per-class AP as given and focuses on what happens when you combine many of them.
From one AP to many
An object detector rarely predicts one kind of object. A street-scene model might output car, person, bicycle and traffic light. AP is defined for a single class, so one AP number describes how well the detector finds only cars, or only people.
Mean average precision (mAP) is the arithmetic mean of the per-class AP values:
mAP = (AP1 + AP2 + ... + AP_C) / C
Here C is the number of classes in the evaluation. Each class counts the same, whether it has ten ground-truth boxes or ten thousand. This is a macro average. The detail is easy to state, and it drives most of the interpretation problems later in this chapter.
How the computation is organized
The key rule is that classes are evaluated independently. A detection labeled dog can only be matched to a ground-truth box labeled dog. A well-placed cat box that overlaps a ground-truth dog is a false positive for cat and has no effect on the dog evaluation.
The steps for each class are:
- Collect all detections of that class across every image in the dataset.
- Collect all ground-truth boxes of that class, grouped by image.
- Rank the detections by confidence score, highest first, across the whole dataset.
- Match each detection to an unmatched ground-truth box with IoU at or above the threshold.
- Compute precision and recall at each rank, then AP from the interpolated curve.
After every class has an AP, you average them.
A worked example
The code below is self-contained. It repeats iou and average_precision from earlier chapters, then adds the mean over classes. The data has three classes, and one of them (bird) has a ground-truth box but no detections at all.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) with x1 < x2 and y1 < y2."""
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def average_precision(detections, ground_truths, iou_threshold=0.5):
"""AP for one class.
detections: list of (image_id, score, box)
ground_truths: dict mapping image_id -> list of boxes
Uses all-point interpolation (the precision envelope).
"""
n_gt = sum(len(boxes) for boxes in ground_truths.values())
if n_gt == 0:
return 0.0
matched = {img: [False] * len(boxes) for img, boxes in ground_truths.items()}
tp = []
for img, score, box in sorted(detections, key=lambda d: -d[1]):
best_iou, best_j = 0.0, -1
for j, gt in enumerate(ground_truths.get(img, [])):
v = iou(box, gt)
if v > best_iou:
best_iou, best_j = v, j
if best_j >= 0 and best_iou >= iou_threshold and not matched[img][best_j]:
matched[img][best_j] = True
tp.append(1)
else:
tp.append(0)
precisions, recalls = [], []
cum_tp = 0
for i, t in enumerate(tp, start=1):
cum_tp += t
precisions.append(cum_tp / i)
recalls.append(cum_tp / n_gt)
recalls = [0.0] + recalls + [1.0]
precisions = [0.0] + precisions + [0.0]
for i in range(len(precisions) - 2, -1, -1):
precisions[i] = max(precisions[i], precisions[i + 1])
ap = 0.0
for i in range(1, len(recalls)):
ap += (recalls[i] - recalls[i - 1]) * precisions[i]
return ap
def mean_average_precision(dets_by_class, gts_by_class, thresholds=(0.5,)):
"""Mean of per-class AP, averaged over the given IoU thresholds."""
scores = []
for t in thresholds:
for cls, gts in gts_by_class.items():
scores.append(average_precision(dets_by_class.get(cls, []), gts, t))
return sum(scores) / len(scores)
gts_by_class = {
"cat": {"img1": [(0, 0, 10, 10), (20, 20, 30, 30)]},
"dog": {"img2": [(0, 0, 10, 10)]},
"bird": {"img3": [(5, 5, 15, 15)]},
}
dets_by_class = {
"cat": [
("img1", 0.9, (0, 0, 10, 10)),
("img1", 0.8, (1, 1, 10, 10)), # duplicate of the first box
("img1", 0.7, (20, 20, 30, 30)),
],
"dog": [
("img2", 0.6, (50, 50, 60, 60)), # wrong place
("img2", 0.5, (0, 0, 10, 10)),
],
# no detections for "bird"
}
for cls, gts in gts_by_class.items():
ap = average_precision(dets_by_class.get(cls, []), gts, 0.5)
print(f"{cls}: {ap:.4f}")
print(f"[email protected]: {mean_average_precision(dets_by_class, gts_by_class):.4f}")Running it prints:
cat: 0.8333
dog: 0.5000
bird: 0.0000
[email protected]: 0.4444The table shows where each number comes from.
| Class | Ground-truth boxes | Ranked outcomes (1 = true positive) | AP at IoU 0.5 |
|---|---|---|---|
| cat | 2 | 1, 0, 1 | 0.8333 |
| dog | 1 | 0, 1 | 0.5000 |
| bird | 1 | none | 0.0000 |
| Mean | 0.4444 |
For cat, the second box has IoU 0.81 with a ground-truth box that the first detection already claimed. It is a duplicate and counts as a false positive. For dog, the top-scored detection misses, so precision at the first rank is 0, and the correct box at rank 2 gives precision 0.5 at full recall. For bird, the detector never fired, so there is no curve and AP is 0.
Edge cases in the class loop
Several decisions in mean_average_precision look minor but change the number you report.
The ground truth defines the class list. The function loops over gts_by_class. A class with ground truth but no detections still contributes an AP of 0, which is what bird did above. This is correct, because a detector that never finds birds should not get credit for ignoring them. If you looped over dets_by_class instead, bird would disappear and mAP would rise to 0.6667. That mistake is easy to make and flatters the model.
Detections of unknown classes are ignored. If the detector outputs a horse box and the ground truth has no horse key, the loop never looks at it. Those detections are effectively false positives that nobody counts. Check that your detector's label set and your dataset's label set match before trusting the result.
A class with no ground truth in the evaluated split. The function returns 0 for a class whose ground-truth dictionary holds no boxes. If such a class is present in gts_by_class, it drags the mean down for a reason unrelated to model quality. Established toolkits handle this by excluding the class from the average, because AP is undefined when there is nothing to find. Filter these classes out before averaging, or at least report how many you dropped.
Ranking is dataset-wide per class. Scores from all images are sorted together. Ranking inside each image and averaging would give a different, less meaningful number.
Matching never crosses classes. Matching happens inside average_precision, which only sees one class's detections and ground truth. A detector that confuses two similar classes is penalized twice: once as a missed detection for the true class, and once as a false positive for the predicted class.
Macro averaging and what it hides
Because each class counts equally, mAP is sensitive to rare classes. Suppose a detector has these results:
| Class | Ground-truth boxes | AP |
|---|---|---|
| car | 1000 | 0.90 |
| scooter | 5 | 0.10 |
The mAP is (0.90 + 0.10) / 2 = 0.50, even though 99.5 percent of the objects are cars. If you instead pooled every detection into one ranking, the result would be close to the car AP. Neither number is wrong. They answer different questions. mAP asks how well the detector works on an average class. A pooled score asks how well it works on an average object.
Two consequences follow:
- A high mAP can hide a class with near-zero AP when there are many classes. With 80 classes, one failed class costs only 1.25 points.
- A low mAP can come from a handful of rare, ambiguous classes with only a few ground-truth boxes. AP for those classes is noisy because one or two matches change the curve a lot.
For this reason, always inspect the per-class table next to the mean, and report the ground-truth count for each class.
Averaging over IoU thresholds
The function above accepts a thresholds argument. With a single threshold, you get mAP at that IoU, for example [email protected]. With several thresholds, it computes AP for every class at every threshold and averages all of them. Since every threshold has the same number of classes, this equals the mean of the per-threshold mAP values.
coco_thresholds = [0.5 + 0.05 * i for i in range(10)] # 0.50, 0.55, ..., 0.95
# map_50_95 = mean_average_precision(dets_by_class, gts_by_class, coco_thresholds)This is the COCO-style headline number, written mAP@[.5:.95]. Pascal VOC reports a single threshold of 0.5. A model that draws loose boxes can score well on the VOC number and poorly on the COCO number. The next chapter covers the COCO protocol, including object-size breakdowns and detection limits.
Common errors in the class loop
- Reporting mAP without naming the IoU threshold. "mAP 0.62" is meaningless until you say whether it is at 0.5 or averaged over 0.5 to 0.95.
- Dropping classes with no detections. This inflates the score, as shown above.
- Averaging per-image AP. AP is a dataset-level quantity. Averaging per-image values gives a different number.
- Mixing label sets. Differences in label spelling (
Personversusperson) silently create empty classes on one side. - Comparing numbers from different interpolation rules. All-point interpolation, used here, differs from the 11-point rule in the original VOC 2007 protocol. The same detections give slightly different mAP under each.
Exercise
A detector is evaluated at IoU 0.5 on three classes. The per-class AP values are 0.80, 0.60 and 0.20. A fourth class, "kite", appears in the ground truth, but the detector never outputs a kite box. What is the mAP if you evaluate over the ground-truth classes, and what would it be if you wrongly looped over only the classes the detector predicted?
Show answer
Over the ground-truth classes, kite gets AP 0, so mAP = (0.80 + 0.60 + 0.20 + 0.00) / 4 = 0.40. Looping over only the predicted classes drops kite and gives (0.80 + 0.60 + 0.20) / 3 = 0.5333. The second figure is inflated because the model's complete failure on kite is hidden.
Exercise
Class A has 500 ground-truth boxes and AP 0.9. Class B has 4 ground-truth boxes and AP 0.3. What is the mAP, and why might you hesitate to trust the AP of class B?
Show answer
mAP = (0.9 + 0.3) / 2 = 0.6. Class B has only four ground-truth boxes, so each match moves its recall by 0.25 and the AP curve has very few points. A single extra true positive or false positive near the top of the ranking can shift AP by a large amount, so the value is noisy.
Exercise
In the worked example, change the dog detections so that the correct box has score 0.9 and the wrong box has score 0.6. What are the new dog AP and the new [email protected]?
Show answer
The ranked outcomes become 1, 0. Precision is 1.0 at rank 1 with recall 1.0, then 0.5 at rank 2. The envelope keeps 1.0 up to recall 1.0, so the dog AP is 1.0. The mAP is (0.8333 + 1.0 + 0.0) / 3 = 0.6111.