AI Logic

Evaluation Metrics

Mean Average Precision (mAP)

Updated:

Computing mAP. Left: a table that ranks 8 detections by confidence, judges each as TP or FP from IoU and duplicates, and gives the precision and recall at each rank. Right: the resulting precision-recall curve and the area under the interpolated step curve (AP 0.664). Bottom: the AP of the same detections under VOC2007 (0.695), VOC2010 and later (0.664), and COCO at IoU 0.5 (0.668)

Background and overview

mAP (mean Average Precision) is an evaluation metric that expresses, as a single number between 0 and 1, whether an object detection model finds objects without missing them and at accurate locations. The closer to 1, the better the model.

The computation has two stages. First, for each class (person, car, dog, etc.), the detections are sorted by confidence, the precision-recall curve is drawn, and the area under it is taken as the AP (Average Precision). Then the AP is averaged over all classes to give the mAP.

mAP=1K∑k=1KAPk\mathrm{mAP} = \frac{1}{K} \sum_{k=1}^{K} \mathrm{AP}_k

The F1 score is computed from the precision and recall obtained when positives and negatives are separated by a single threshold. AP summarizes how precision and recall change as the threshold moves from strict to lenient, so it is independent of the choice of threshold.

There are two commonly used definitions of mAP: the PASCAL VOC definition (the PASCAL VOC challenge, Everingham et al. 2010) and the COCO definition (the official COCO evaluation). The values differ greatly even though both are called "mAP", so always check which definition is used.

Definition and computation

The AP of one class is computed in the following steps.

  1. Sort all detections of that class (boxes and confidences) across the test images in descending order of confidence.
  2. Going down the list, match each detection against the ground-truth objects. If the overlap (IoU) between the detected box BpB_p and the ground-truth box BgtB_{gt} exceeds a threshold (0.5 in VOC), the detection is a true positive (TP).
IoU=area(Bp∩Bgt)area(Bp∪Bgt)\mathrm{IoU} = \frac{\mathrm{area}(B_p \cap B_{gt})}{\mathrm{area}(B_p \cup B_{gt})}
  1. Detections that overlap no ground-truth object, and second and later detections of an object already found, are false positives (FP). If one object is detected five times, one detection is a TP and four are FPs.
  2. Compute the precision (the fraction of TPs among the detections up to that rank) and recall (the fraction of all ground-truth objects found up to that rank) at each rank, and draw the curve.
  3. Interpolate the curve. Replace the precision at each recall rr with the maximum precision measured at any recall greater than or equal to rr: pinterp(r)=max⁡r~≥rp(r~)p_{\mathrm{interp}}(r) = \max_{\tilde{r} \ge r} p(\tilde{r}).
  4. Compute the AP from the interpolated curve (how depends on the definition; see the table below).

The interpolation in step 5 reduces the wiggles in the curve caused by small changes in the ranking. The interpolated curve takes the shape of a staircase that descends to the right.

DefinitionHow AP is computedIoU for a TPHow mAP is averaged
VOC2007Mean of pinterpp_{\mathrm{interp}} at 11 recall points 0, 0.1, …, 1Above 0.5Over 20 classes
VOC2010–2012Area under the interpolated curve (summed over segments split at every recall value)Above 0.5Over 20 classes
COCOMean of pinterpp_{\mathrm{interp}} at 101 recall points 0, 0.01, …, 110 levels: 0.50, 0.55, …, 0.95Over 80 classes and the 10 IoU levels

The 11-point formula of VOC2007 is as follows.

AP11=111∑r∈{0,0.1,…,1}pinterp(r)\mathrm{AP}_{11} = \frac{1}{11} \sum_{r \in \{0, 0.1, \dots, 1\}} p_{\mathrm{interp}}(r)

In the example in the figure at the top (5 ground-truth objects, 8 detections), the same detections give an AP of 0.695 with the VOC2007 11-point method, 0.664 with the area method of VOC2010 and later, and 0.668 with the COCO 101-point method (at IoU 0.5 only). VOC2010 changed the computation to make AP more precise and to be able to measure differences between methods with low AP.

The COCO evaluation page writes "AP" to mean the value averaged over all classes. It does not distinguish AP from mAP, so "AP" in a COCO paper corresponds to mAP in other literature. COCO's primary metric is also averaged over the 10 IoU levels from 0.50 to 0.95, and is written as "AP@[.5:.95]" or "mAP50-95". The value at IoU 0.5 alone is AP50 (equivalent to the VOC criterion), and the value at 0.75 alone is AP75 (a strict criterion).

What it measures and its limitations

AP evaluates, based on the confidence ranking, how well the model finds the objects it should find without missing them and without making extra detections. The VOC paper states that a high AP requires high precision at all levels of recall, which penalizes methods that retrieve only a subset of objects (for example, only side views of cars) with high precision.

The COCO definition averages over 10 IoU levels from 0.50 to 0.95, so it also rewards accurate box localization more strongly. According to the COCO evaluation page, averaging over IoU rewards detectors with better localization.

mAP also has the following limitations.

  • Values differ greatly between definitions: the VOC mAP (IoU 0.5) and the COCO AP (averaged over IoU 0.50–0.95) differ greatly even for the same model. The stricter the IoU criterion, the lower the value.
  • The IoU threshold is arbitrary: VOC set the threshold relatively low at 0.5 because the ground-truth boxes themselves are ambiguous (such as the box of a person with outstretched arms and legs). The paper shows that raising the threshold above 0.5 makes AP drop sharply (see the next section).
  • Confidence values themselves are not evaluated: AP looks only at the ranking. It does not tell whether the confidences match the actual probability of being correct (calibration).
  • Classes are averaged, so frequent and rare classes have equal weight: performance on a rare class can move the mAP considerably.

When comparing mAP values, make sure they were computed with the same definition (VOC2007, VOC2010 onward, or COCO) and the same IoU criterion. COCO evaluates only the top 100 detections by confidence per image, so outputting more detections does not raise the value. In VOC, objects marked "difficult" are excluded from evaluation and count toward neither precision nor recall, whether detected or missed.

Validation in the original paper

The VOC paper (Everingham et al. 2010) also validates the evaluation method itself.

  • Switching from ROC AUC: the VOC2006 classification task used the area under the ROC curve (ROC AUC), but many methods exceeded 95%, making differences hard to see. So from VOC2007 the challenge switched to precision-recall curves and AP, to increase sensitivity and to make performance at low recall visible. When compared on VOC2006, the rankings of participants were largely consistent, and AP showed larger differences between methods.
  • Effect of the IoU threshold: measuring AP at different IoU thresholds for the "car" class, which had the best results in VOC2007, showed that AP drops sharply above 0.5. None of the methods could produce very precise boxes. Conversely, lowering the threshold to 0.1 raised AP by about 7.5%. In the range 0 to 0.5, the ranking of methods did not change except for one pair.

The COCO evaluation page includes an error analysis of the ResNet detector that won the 2015 COCO detection challenge. Its AP at IoU 0.75 is 0.399, but removing localization errors raises it to 0.682, and further removing background false positives raises it to 0.870. This detector's errors came mainly from inaccurate localization and background false positives. Looking at AP under different IoU criteria in this way reveals which kinds of errors dominate.

Where it is used

mAP is mainly used in the following settings.

  • Object detection: it is the standard metric for comparing models such as Faster R-CNN, YOLO, SSD and DETR on VOC and COCO.
  • Instance segmentation: for models that output a region per object, such as Mask R-CNN, AP is computed in the same way using the IoU between masks instead of boxes. The COCO evaluation is identical except for the IoU computation.
  • Evaluating improvements to detector training: the effect of methods that improve detector training, such as Focal Loss, is also shown with COCO AP.
  • Information retrieval and image classification: for search result rankings and multi-label classification, where one image can have several labels, mAP is used as the mean of per-class or per-query AP. The VOC2007 classification task was also evaluated with AP.

Comparison with similar metrics

The table compares mAP with related metrics from the same viewpoints.

MetricWhat it countsThresholdsLocalization accuracyTypical task
mAP (VOC, IoU 0.5)Class mean of the area under the precision-recall curveConfidence: independent / IoU: 0.5CoarseObject detection (VOC)
AP (COCO, IoU 0.50–0.95)Same as above, also averaged over 10 IoU levelsConfidence: independent / IoU: 10 levelsStrictObject detection (COCO)
F1 scoreHarmonic mean of precision and recall at one thresholdConfidence: one fixed value—Evaluating an operating point in classification or detection
ROC AUCArea under the curve of true positive rate vs. false positive rateConfidence: independent—Binary classification
mIoUClass mean of per-pixel overlap (IoU)Confidence: not usedPixel levelSemantic segmentation

Rough guidelines for choosing:

  • Comparing object detection models with prior work: use the dataset's official definition (for COCO, AP@[.5:.95] together with AP50 and AP75).
  • Knowing performance at the threshold actually used: in addition to mAP, check precision, recall and the F1 score at the confidence threshold used in deployment.
  • Tasks with a very large number of negatives (background): with many negatives, the false positive rate looks small and ROC AUC tends to be high, so AP, which uses precision, shows differences more clearly.

PyTorch example

Show code
python
import torch


def average_precision(scores, is_tp, num_gt):
  """AP of one class (VOC2010+ definition: area under the interpolated precision-recall curve).
  scores: (D,) confidence of each detection
  is_tp:  (D,) True if the detection is a TP (IoU-based matching already done)
  num_gt: number of ground-truth objects (excluding difficult ones)
  """
  order = torch.argsort(scores, descending=True)
  tp = is_tp[order].float()
  cum_tp = torch.cumsum(tp, dim=0)
  cum_fp = torch.cumsum(1 - tp, dim=0)
  recall = cum_tp / num_gt
  precision = cum_tp / (cum_tp + cum_fp)
  # add the endpoints, then take the cumulative max from the right so the curve descends to the right (interpolation)
  r = torch.cat([torch.tensor([0.0]), recall, torch.tensor([1.0])])
  p = torch.cat([torch.tensor([0.0]), precision, torch.tensor([0.0])])
  p = torch.flip(torch.cummax(torch.flip(p, [0]), dim=0).values, [0])
  # sum width × interpolated precision only where recall increases
  idx = torch.nonzero(r[1:] != r[:-1]).squeeze(1) + 1
  return torch.sum((r[idx] - r[idx - 1]) * p[idx]).item()


# Example from the figure at the top: 5 ground-truth objects, 8 detections (by descending confidence: TP, TP, FP, TP, FP, FP, TP, FP)
scores = torch.tensor([0.95, 0.91, 0.88, 0.80, 0.74, 0.62, 0.55, 0.40])
is_tp = torch.tensor([True, True, False, True, False, False, True, False])
print(round(average_precision(scores, is_tp, num_gt=5), 3))  # 0.664

# For the COCO definition, use torchmetrics (it uses pycocotools internally)
from torchmetrics.detection import MeanAveragePrecision

metric = MeanAveragePrecision(box_format="xyxy", iou_type="bbox")  # defaults: IoU 0.50:0.05:0.95, 101 points, top 100 detections
preds = [dict(boxes=torch.tensor([[258.0, 41.0, 606.0, 285.0]]), scores=torch.tensor([0.536]), labels=torch.tensor([0]))]
target = [dict(boxes=torch.tensor([[214.0, 41.0, 562.0, 285.0]]), labels=torch.tensor([0]))]
metric.update(preds, target)  # a list of dicts, one per image. Call update on the whole evaluation set, then compute
result = metric.compute()
print(result["map"], result["map_50"], result["map_75"])  # tensor(0.6000) tensor(1.) tensor(1.)

FAQ

Q. Are "AP" and "mAP" in papers different things?
A.

It depends on the literature. In the VOC convention, the per-class value is called AP and its mean is called mAP. The COCO evaluation page does not distinguish them and also calls the class-averaged value AP. "AP" in a COCO paper usually means the value averaged over all classes and IoU 0.50–0.95.

Q. Should I report mAP@0.5 or mAP@[.5:.95]?
A.

Follow the conventions of the work you compare with and of the dataset. On COCO, it is common to use the average over IoU 0.50–0.95 as the primary metric, together with AP50 and AP75. To compare with VOC, use mAP at IoU 0.5. If localization accuracy matters for the application, also check the values at high IoU criteria.

Q. Does outputting more detections raise mAP?
A.

AP computed from the interpolated curve does not decrease when low-confidence detections are appended at the end, and it increases if they find new objects and recall grows. Precision drops only at the right end of the curve, and the interpolated values to the left do not change. This is why COCO limits evaluation to the top 100 detections per image; in practice, also check precision and recall at the threshold used in deployment.

References

  1. Everingham, M., Van Gool, L., Williams, C. K. I., Winn, J., & Zisserman, A. (2010). The PASCAL Visual Object Classes (VOC) Challenge. International Journal of Computer Vision, 88(2), 303–338.
  2. Everingham, M., & Winn, J. The PASCAL Visual Object Classes Challenge 2012 (VOC2012) Development Kit (Section 3.4.1 Average Precision).
  3. COCO Consortium. Detection Evaluation (the official COCO evaluation page).
  4. Lin, T.-Y., et al. (2014). Microsoft COCO: Common Objects in Context. ECCV 2014.
  5. Lightning AI. torchmetrics.detection.MeanAveragePrecision (API reference).