Algorithm Search⌘K

Definitioncore

Mean average precision for detection

Also called detection mAP, COCO mAP.

For each class, the area under the precision-recall curve of detections matched to objects at an IoU threshold, averaged over classes and often over thresholds.

Mean average precision (mAP) for detection is one number that scores a program that finds objects in images and reports each one as a box with a class name and a confidence. For each class, the reports are sorted by confidence and each is judged right or wrong, which gives a precision and recall value after every report; the average precision (AP) is the area under this precision-recall curve, and mAP is the mean of AP over the classes. What makes the detection version different from the mean average precision of information retrieval is the judging step: a reported box counts as right only if its intersection over union with a true object box is above a threshold and no better-ranked box has already claimed that object. PASCAL VOC uses one threshold, 0.5, and COCO averages over ten thresholds from 0.5 to 0.95.

Definition

The input for one class is a list of detections d1,…,dMd_1, \ldots, d_M, each with an image, a score and a box, and a set GG of ground-truth boxes of that class in the same images. Let N=∣G∣N = |G|. The VOC rule is:

  1. DETECTION-AP(D, G, τ) ▷ one class, VOC matching
  2. 1sort D by score, decreasing, ties by input order
  3. 2used[g] ← false for every g in G; tp ← 0; fp ← 0
  4. 3for k ← 1 to |D| do
  5. 4g ← the box of G in the image of d_k with the largest IoU with d_k
  6. 5if g exists and IoU(d_k, g) > τ and not used[g] then used[g] ← true; tp ← tp + 1
  7. 6else fp ← fp + 1
  8. 7P_k ← tp / (tp + fp); R_k ← tp / N
  9. 8p_interp(r) ← max{P_k : R_k ≥ r}, and 0 if no k has R_k ≥ r
  10. 9return Σ_k (R_k - R_{k-1}) · p_interp(R_k) ▷ R_0 = 0

Line L5 is where the boxes enter. A second detection of an object that is already matched is a false positive, so five detections of one object give one true positive and four false positives. The VOC development kit also has "difficult" objects; a detection that matches one is ignored, and these objects are not counted in NN.

Line L8 makes the curve monotone: the precision at recall rr is replaced by the best precision at any recall of at least rr. The interpolated precision-recall curve of retrieval uses the same rule. The sum of line L9 is the area under this staircase. Three versions of AP are in use, and they give different numbers for the same detections:

  • VOC 2007, 11 points. AP=111∑r∈{0,0.1,…,1}pinterp(r)\mathrm{AP} = \frac{1}{11} \sum_{r \in \{0, 0.1, \ldots, 1\}} p_{\mathrm{interp}}(r), Eq. (1) and (2) of Everingham et al. (2010).
  • VOC 2010 and later, all points. The area of line L9. Since recall grows by 1/N1/N at each true positive, this is the mean over the NN objects of the best precision at or after the rank where the object is found, with 0 for a missed object.
  • COCO, 101 points. The mean of pinterpp_{\mathrm{interp}} at r∈{0,0.01,…,1}r \in \{0, 0.01, \ldots, 1\}. The COCO code also changes the matching: a detection takes the unmatched ground-truth box with the largest IoU among those with IoU of at least τ\tau, so an already matched object does not block a detection that also overlaps another object.

mAP is the mean of AP over the classes. The COCO metric "AP" is the mean over the classes and over the ten thresholds τ=0.50,0.55,…,0.95\tau = 0.50, 0.55, \ldots, 0.95; COCO writes AP for what other papers call mAP, and also reports AP at τ=0.5\tau = 0.5 and 0.750.75, AP for small (area below 32232^2 pixels), medium and large (above 96296^2) objects, and keeps at most 100 detections per image.

The value is in [0,1][0, 1] and depends only on the order of the scores, not on their values (both are proved in the correctness file). AP is 1 exactly when every object is found and every false positive is ranked after the last true positive. The thresholds 0.5 and 0.5 to 0.95 are conventions of the benchmarks. The VOC paper calls the 50 percent threshold deliberately low and studies other values in Section 6.2.3.

Examples and non-examples

  • A small example. Image A has the objects (0,0,10,10)(0,0,10,10) and (20,0,30,10)(20,0,30,10), and image B has (0,0,10,10)(0,0,10,10), so N=3N = 3. The detections, by score, are a box (1,0,11,10)(1,0,11,10) in A (IoU 9/119/11 with the first object, a true positive), a box (0,1,10,11)(0,1,10,11) in A (IoU 9/119/11 with the same object, which is used, so a false positive), a box (0,0,9,10)(0,0,9,10) in B (IoU 9/109/10, a true positive), a box (24,0,34,10)(24,0,34,10) in A (IoU 3/7<0.53/7 < 0.5 with the second object, a false positive) and a box far from everything in B (a false positive). The precisions are 1,1/2,2/3,1/2,2/51, 1/2, 2/3, 1/2, 2/5 and the recalls 1/3,1/3,2/3,2/3,2/31/3, 1/3, 2/3, 2/3, 2/3. The all-point AP is 13⋅1+13⋅23=5/9≈0.556\frac{1}{3} \cdot 1 + \frac{1}{3} \cdot \frac{2}{3} = 5/9 \approx 0.556; the 11-point AP is (4⋅1+3⋅23)/11=6/11≈0.545(4 \cdot 1 + 3 \cdot \frac{2}{3}) / 11 = 6/11 \approx 0.545; the 101-point AP is (34+33⋅23)/101=56/101≈0.554(34 + 33 \cdot \frac{2}{3}) / 101 = 56/101 \approx 0.554.
  • The same example in COCO. For τ\tau from 0.50 to 0.80 the labels do not change and AP is 56/10156/101. At 0.85 and 0.90 only the detection with IoU 9/109/10 is a true positive, at rank 3, and AP is 34/303≈0.11234/303 \approx 0.112; at 0.90 it still counts because COCO tests "at least τ\tau" while VOC tests "above τ\tau". At 0.95 AP is 0. The COCO AP is the mean of the ten values, 622/1515≈0.411622/1515 \approx 0.411, much lower than the VOC value because the boxes are only roughly right.
  • The matching rules differ. Two objects (0,0,10,10)(0,0,10,10) and (2,0,12,10)(2,0,12,10) overlap with IoU 2/32/3. A detection (1,0,11,10)(1,0,11,10) with the higher score has IoU 9/119/11 with both and takes the first. A second detection (0,0,10,10)(0,0,10,10) has IoU 1 with the first object and 2/32/3 with the second. VOC sends it to the first object, which is used, so it is a false positive and AP is 1/21/2; COCO sends it to the second object and AP is 1.
  • Not accuracy. True negatives do not appear anywhere: there is no fixed set of "non-objects". A detector that adds many low-score false positives after its last true positive does not lose any AP.
  • Not the retrieval mAP of one query. In retrieval a document is relevant or not by itself. Here a box is right or wrong only after the matching, and its label depends on the boxes ranked before it.
  • Not mean IoU. The mean intersection over union of semantic segmentation averages a pixel ratio over classes and has no ranking at all.

Precision and recall and the interpolated precision-recall curve are the parts from which AP is built, and the mean average precision of retrieval is the same average over a ranking with relevance given in advance. The IoU threshold and the matching come from object detection benchmarks. Since mAP depends only on the ranking, the last step of a detector matters: box non-maximum suppression removes duplicates that would be false positives, and Soft-NMS instead moves them down the ranking, which can raise AP because a second object near the first is no longer lost. DET curves of miss rate against false positives per window, used by the Dalal-Triggs detector, and miss rate against false positives per image, used for pedestrians, are other summaries of the same detections.

The Python code of this page gives both matching rules, the three AP versions and the COCO average over thresholds, all with exact fractions. Its tests check the example above, compare the all-point AP with the mean over objects of the best later precision, check that only the order of the scores matters, and check that the COCO true positives never exceed a maximum matching found by search.

Proof: The all-point AP is the mean over objects of the best precision at or after each hit, and depends only on the rankingfull

We use the notation of the page. After matching, a class has a ranked list of detections, each a true positive (TP) or a false positive (FP), and N>0N > 0 objects that count (the difficult objects of VOC are left out, and so are detections matched to them). Let PkP_k and RkR_k be the precision and recall after rank kk, so Rk=tpk/NR_k = \mathrm{tp}_k / N and Pk=tpk/kP_k = \mathrm{tp}_k / k, where tpk\mathrm{tp}_k is the number of TPs among the first kk ranks. The interpolated precision is pinterp(r)=max⁡{Pk:Rk≥r}p_{\mathrm{interp}}(r) = \max\{P_k : R_k \ge r\}, and 0 when no rank reaches recall rr. The all-point AP of line L9 is ∑k(Rk−Rk−1) pinterp(Rk)\sum_k (R_k - R_{k-1}) \, p_{\mathrm{interp}}(R_k) with R0=0R_0 = 0.

Claim. Let r1<r2<⋯<rTr_1 < r_2 < \cdots < r_T be the ranks of the TT true positives. Then

  1. AP=1N∑j=1Npinterp(j/N)=1N∑j=1Tmax⁡k≥rjPk\mathrm{AP} = \dfrac{1}{N} \sum_{j=1}^{N} p_{\mathrm{interp}}(j / N) = \dfrac{1}{N} \sum_{j=1}^{T} \max_{k \ge r_j} P_k;
  2. 0≤AP≤10 \le \mathrm{AP} \le 1, and AP=1\mathrm{AP} = 1 exactly when T=NT = N and no FP is ranked before rNr_N;
  3. AP depends on the scores only through the ranking, so any strictly increasing change of all scores leaves it unchanged;
  4. the 11-point and 101-point values are the means of pinterpp_{\mathrm{interp}} at the recall levels 0,0.1,…,10, 0.1, \ldots, 1 and 0,0.01,…,10, 0.01, \ldots, 1.

Proof. Part 1. Recall changes only at a TP rank, and there it grows by exactly 1/N1/N: Rrj−Rrj−1=1/NR_{r_j} - R_{r_j - 1} = 1/N and Rrj=j/NR_{r_j} = j/N. All other terms of the sum have Rk−Rk−1=0R_k - R_{k-1} = 0. So AP=1N∑j=1Tpinterp(j/N)\mathrm{AP} = \frac{1}{N} \sum_{j=1}^{T} p_{\mathrm{interp}}(j/N). For j>Tj > T no rank has recall j/Nj/N, so pinterp(j/N)=0p_{\mathrm{interp}}(j/N) = 0, and the sum can run to NN. Finally, Rk≥j/NR_k \ge j/N holds exactly when tpk≥j\mathrm{tp}_k \ge j, that is, when k≥rjk \ge r_j, so pinterp(j/N)=max⁡k≥rjPkp_{\mathrm{interp}}(j/N) = \max_{k \ge r_j} P_k.

Part 2. Each PkP_k is in [0,1][0, 1], so each term of part 1 is in [0,1][0, 1], and AP is in [0,1][0, 1]. If T=NT = N and no FP comes before rNr_N, then PrN=N/rN=1P_{r_N} = N / r_N = 1, and every jj has rj≤rNr_j \le r_N, so every term is 1. Conversely, AP=1\mathrm{AP} = 1 needs all NN terms equal to 1, so T=NT = N, and the term for j=Nj = N needs some k≥rNk \ge r_N with Pk=1P_k = 1, that is, with no FP among the first kk ranks; then no FP comes before rNr_N.

Part 3. The matching of line L4 to L6 visits the detections in the order of line L1 and uses only their boxes, so the TP and FP labels depend only on the order. PkP_k and RkR_k depend only on the labels. A strictly increasing change of all scores keeps the order, and the tie rule (the input order) is the same.

Part 4 is the definition of the two sums in the code: each evaluates pinterpp_{\mathrm{interp}} at a fixed grid of recall levels and divides by the number of levels. □\square

Remark. Part 1 is the form that the tests use as an independent reference: it needs no sorting of recall values and no envelope, only the precision after each rank. It also shows that a missed object costs exactly 1/N1/N of the AP, and that an FP costs something only when it is ranked before a TP.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

detection_mean_average_precision.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/detection-mean-average-precision/. The authors are listed in prov/ZNZ16Q.jsonl.
"""Average precision (AP) and mean average precision (mAP) for detection.

A detection is (image_id, score, box) and a box is (x1, y1, x2, y2) in
continuous coordinates. Ground truth is a dict image_id -> list of boxes, for
one class. Two matching rules are given:

    match_voc   the rule of the PASCAL VOC development kit: a detection takes
                the ground-truth box with the largest IoU; it is a true
                positive if that IoU is above the threshold and the box is
                not used yet, and a false positive otherwise. A match with a
                box marked "difficult" is ignored.
    match_coco  the rule of the COCO API: a detection takes the unused
                ground-truth box with the largest IoU among those with IoU at
                least the threshold.

Three ways to turn the ranked list into one number are given: the 11-point
AP of VOC 2007, the all-point AP of VOC 2010 and later, and the 101-point AP
of COCO. All values are exact Fractions when the boxes are integers.
Standard library only.
"""

from fractions import Fraction


def iou(a, b):
    """IoU of two boxes; exact (a Fraction) on integer boxes."""
    iw = min(a[2], b[2]) - max(a[0], b[0])
    ih = min(a[3], b[3]) - max(a[1], b[1])
    inter = iw * ih if iw > 0 and ih > 0 else 0
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    if union == 0:
        return 0
    if isinstance(inter, int) and isinstance(union, int):
        return Fraction(inter, union)
    return inter / union


def rank(dets):
    """Indices of the detections by score, highest first, ties by index."""
    return sorted(range(len(dets)), key=lambda k: (-dets[k][1], k))


def match_voc(dets, gts, threshold=Fraction(1, 2), difficult=None):
    """Return (flags, npos). flags[r] is True (TP), False (FP) or None
    (ignored) for the detection of rank r; npos counts the boxes that are
    not difficult.
    """
    difficult = difficult or {}
    order = rank(dets)  # @line L1
    used = {img: [False] * len(boxes) for img, boxes in gts.items()}  # @line L2
    flags = []
    for k in order:  # @line L3
        img, _, box = dets[k]
        cands = gts.get(img, [])
        best, j = -1, -1
        for g, gbox in enumerate(cands):  # @line L4
            o = iou(box, gbox)
            if o > best:
                best, j = o, g
        diff = difficult.get(img, [False] * len(cands))
        if j >= 0 and best > threshold:  # @line L5
            if diff[j]:
                flags.append(None)
            elif not used[img][j]:
                used[img][j] = True
                flags.append(True)
            else:
                flags.append(False)  # @line L6
        else:
            flags.append(False)
    npos = sum(1 for img, boxes in gts.items() for g in range(len(boxes))
               if not difficult.get(img, [False] * len(boxes))[g])
    return flags, npos


def match_coco(dets, gts, threshold=Fraction(1, 2)):
    """Return (flags, npos) with the matching rule of the COCO API (no crowd
    regions and no area ranges)."""
    used = {img: [False] * len(boxes) for img, boxes in gts.items()}
    flags = []
    for k in rank(dets):
        img, _, box = dets[k]
        best, j = None, -1
        for g, gbox in enumerate(gts.get(img, [])):
            if used[img][g]:
                continue
            o = iou(box, gbox)
            if o >= threshold and (best is None or o > best):
                best, j = o, g
        if j >= 0:
            used[img][j] = True
            flags.append(True)
        else:
            flags.append(False)
    npos = sum(len(b) for b in gts.values())
    return flags, npos


def precision_recall(flags, npos):
    """Precision and recall after each rank; ignored detections are skipped."""
    prec, rec, tp, fp = [], [], 0, 0
    for f in flags:
        if f is None:
            continue
        if f:
            tp += 1
        else:
            fp += 1
        prec.append(Fraction(tp, tp + fp))  # @line L7
        rec.append(Fraction(tp, npos) if npos else Fraction(0))
    return prec, rec


def interpolated(prec, rec, r):
    """p_interp(r): the largest precision at a recall of at least r, else 0."""
    vals = [p for p, q in zip(prec, rec) if q >= r]  # @line L8
    return max(vals) if vals else Fraction(0)


def ap_all_points(prec, rec):
    """VOC 2010 and later: the area under the interpolated curve."""
    total, last = Fraction(0), Fraction(0)
    for k in range(len(rec)):
        if rec[k] > last:
            total += (rec[k] - last) * interpolated(prec, rec, rec[k])  # @line L9
            last = rec[k]
    return total


def ap_11_points(prec, rec):
    """VOC 2007: the mean of p_interp at the recalls 0, 0.1, ..., 1."""
    return sum(interpolated(prec, rec, Fraction(k, 10)) for k in range(11)) / 11


def ap_101_points(prec, rec):
    """COCO: the mean of p_interp at the recalls 0, 0.01, ..., 1."""
    return sum(interpolated(prec, rec, Fraction(k, 100)) for k in range(101)) / 101


def average_precision(dets, gts, threshold=Fraction(1, 2), rule="voc", points="all",
                      difficult=None):
    """AP of one class."""
    if rule == "voc":
        flags, npos = match_voc(dets, gts, threshold, difficult)
    else:
        flags, npos = match_coco(dets, gts, threshold)
    prec, rec = precision_recall(flags, npos)
    if points == "all":
        return ap_all_points(prec, rec)
    if points == 11:
        return ap_11_points(prec, rec)
    return ap_101_points(prec, rec)


def mean_average_precision(per_class, threshold=Fraction(1, 2), rule="voc", points="all"):
    """mAP: the mean of AP over classes. per_class maps a class name to a
    pair (dets, gts)."""
    aps = [average_precision(d, g, threshold, rule, points) for d, g in per_class.values()]
    return sum(aps) / len(aps)


COCO_THRESHOLDS = [Fraction(50 + 5 * k, 100) for k in range(10)]


def coco_map(per_class):
    """COCO AP: the mean over the IoU thresholds 0.50, 0.55, ..., 0.95 and
    over classes, with COCO matching and 101 recall points."""
    vals = [mean_average_precision(per_class, t, "coco", 101) for t in COCO_THRESHOLDS]
    return sum(vals) / len(vals)
test_detection_mean_average_precision.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/detection-mean-average-precision/. The authors are listed in prov/ZNZ16Q.jsonl.

import random
from fractions import Fraction

from detection_mean_average_precision import (COCO_THRESHOLDS, ap_11_points, ap_101_points,
                                              ap_all_points, average_precision, coco_map,
                                              interpolated, iou, match_coco, match_voc,
                                              mean_average_precision, precision_recall)

GTS = {"A": [(0, 0, 10, 10), (20, 0, 30, 10)], "B": [(0, 0, 10, 10)]}
DETS = [("A", 0.9, (1, 0, 11, 10)), ("A", 0.8, (0, 1, 10, 11)), ("B", 0.7, (0, 0, 9, 10)),
        ("A", 0.6, (24, 0, 34, 10)), ("B", 0.5, (40, 40, 50, 50))]


def random_class(rng, n_images=3, n_gt=3, n_det=8):
    gts, dets = {}, []
    for img in range(n_images):
        boxes = []
        for _ in range(rng.randint(0, n_gt)):
            x, y = rng.randint(0, 20), rng.randint(0, 20)
            boxes.append((x, y, x + rng.randint(3, 8), y + rng.randint(3, 8)))
        gts[img] = boxes
    for _ in range(rng.randint(0, n_det)):
        img = rng.randrange(n_images)
        if gts[img] and rng.random() < 0.7:
            g = rng.choice(gts[img])
            dx, dy = rng.randint(-2, 2), rng.randint(-2, 2)
            box = (g[0] + dx, g[1] + dy, g[2] + dx + rng.randint(-1, 1), g[3] + dy)
        else:
            x, y = rng.randint(0, 20), rng.randint(0, 20)
            box = (x, y, x + 5, y + 5)
        if box[2] <= box[0]:
            box = (box[0], box[1], box[0] + 1, box[3])
        dets.append((img, rng.randint(1, 5), box))  # integer scores with ties
    return dets, gts


def test_page_example():
    assert iou(DETS[0][2], GTS["A"][0]) == Fraction(9, 11)
    assert iou(DETS[3][2], GTS["A"][1]) == Fraction(3, 7)
    flags, npos = match_voc(DETS, GTS)
    assert flags == [True, False, True, False, False] and npos == 3
    prec, rec = precision_recall(flags, npos)
    assert prec == [1, Fraction(1, 2), Fraction(2, 3), Fraction(1, 2), Fraction(2, 5)]
    assert rec == [Fraction(1, 3), Fraction(1, 3), Fraction(2, 3), Fraction(2, 3), Fraction(2, 3)]
    assert ap_all_points(prec, rec) == Fraction(5, 9)
    assert ap_11_points(prec, rec) == Fraction(6, 11)
    assert ap_101_points(prec, rec) == Fraction(56, 101)


def test_page_example_coco():
    per_t = []
    for t in COCO_THRESHOLDS:
        flags, npos = match_coco(DETS, GTS, t)
        per_t.append(ap_101_points(*precision_recall(flags, npos)))
    assert per_t == [Fraction(56, 101)] * 7 + [Fraction(34, 303)] * 2 + [0]
    assert coco_map({"c": (DETS, GTS)}) == Fraction(622, 1515)
    # IoU exactly 9/10 counts at threshold 0.9 in COCO (at least) but not
    # in the VOC rule (above).
    assert match_coco(DETS, GTS, Fraction(9, 10))[0][2] is True
    assert match_voc(DETS, GTS, Fraction(9, 10))[0][2] is False


def test_voc_and_coco_matching_differ():
    gts = {"X": [(0, 0, 10, 10), (2, 0, 12, 10)]}
    dets = [("X", 0.9, (1, 0, 11, 10)), ("X", 0.8, (0, 0, 10, 10))]
    assert iou(*gts["X"]) == Fraction(2, 3)
    assert match_voc(dets, gts) == ([True, False], 2)
    assert match_coco(dets, gts) == ([True, True], 2)
    assert average_precision(dets, gts) == Fraction(1, 2)
    assert average_precision(dets, gts, rule="coco") == 1


def test_difficult_boxes_are_ignored():
    gts = {"X": [(0, 0, 10, 10), (20, 0, 30, 10)]}
    diff = {"X": [False, True]}
    dets = [("X", 0.9, (20, 0, 30, 10)), ("X", 0.8, (0, 0, 10, 10))]
    flags, npos = match_voc(dets, gts, difficult=diff)
    assert flags == [None, True] and npos == 1
    assert average_precision(dets, gts, difficult=diff) == 1


def test_all_points_equals_mean_over_recall_levels():
    # Recall moves in steps of 1/npos, so the area under the interpolated
    # curve is the mean of p_interp(k / npos) over k = 1..npos.
    rng = random.Random(21)
    for trial in range(200):
        dets, gts = random_class(rng)
        flags, npos = match_voc(dets, gts)
        if npos == 0:
            continue
        prec, rec = precision_recall(flags, npos)
        ref = sum(interpolated(prec, rec, Fraction(k, npos)) for k in range(1, npos + 1)) / npos
        assert ap_all_points(prec, rec) == ref


def test_ap_from_brute_force_over_ranks():
    # Brute force: for each true positive at rank r, take the best precision
    # at rank r or later; average over all npos objects (missed ones give 0).
    rng = random.Random(22)
    for trial in range(200):
        flags = [rng.random() < 0.5 for _ in range(rng.randint(0, 12))]
        npos = sum(flags) + rng.randint(0, 3)
        if npos == 0:
            continue
        prec, rec = precision_recall(flags, npos)
        total = Fraction(0)
        for r, f in enumerate(flags):
            if f:
                total += max(prec[r:])
        assert ap_all_points(prec, rec) == total / npos


def test_perfect_and_empty_detectors():
    gts = {0: [(0, 0, 4, 4), (10, 10, 14, 14)], 1: [(3, 3, 9, 9)]}
    dets = [(img, 1, b) for img, bs in gts.items() for b in bs]
    for points in ("all", 11, 101):
        assert average_precision(dets, gts, points=points) == 1
        assert average_precision([], gts, points=points) == 0
    assert coco_map({"c": (dets, gts)}) == 1


def test_only_the_order_of_scores_matters():
    rng = random.Random(23)
    for trial in range(100):
        dets, gts = random_class(rng)
        moved = [(img, 3 * s * s + 7, box) for img, s, box in dets]
        for rule in ("voc", "coco"):
            assert average_precision(dets, gts, rule=rule) == average_precision(moved, gts, rule=rule)


def test_coco_matching_is_one_to_one_and_respects_threshold():
    rng = random.Random(24)
    for trial in range(150):
        dets, gts = random_class(rng)
        t = rng.choice(COCO_THRESHOLDS)
        flags, npos = match_coco(dets, gts, t)
        # The true positives form a one-to-one matching on pairs with IoU at
        # least t, so they cannot exceed a maximum matching found by search.
        edges = [[(img, g) for g, gb in enumerate(gts[img]) if iou(box, gb) >= t]
                 for img, _, box in dets]

        def best(k, taken):
            if k == len(edges):
                return 0
            res = best(k + 1, taken)
            for e in edges[k]:
                if e not in taken:
                    res = max(res, 1 + best(k + 1, taken | {e}))
            return res

        assert sum(flags) <= best(0, frozenset())
        # A detection with no pair at IoU at least t is never a true positive.
        order = sorted(range(len(dets)), key=lambda k: (-dets[k][1], k))
        for r, k in enumerate(order):
            if not edges[k]:
                assert flags[r] is False


def test_mean_over_classes():
    per_class = {"a": (DETS, GTS), "b": ([("A", 1, (0, 0, 10, 10))], {"A": [(0, 0, 10, 10)]})}
    assert mean_average_precision(per_class) == (Fraction(5, 9) + 1) / 2

References

  1. Mark Everingham, Luc Van Gool, Christopher K. I. Williams, John Winn and Andrew Zisserman, The PASCAL Visual Object Classes (VOC) challenge, International Journal of Computer Vision 88(2), 2010, 303-338, Section 4.2, Eq. (1) and (2) (11-point interpolated AP), Eq. (3) (overlap above 50 percent), the rule that extra detections of one object are false positives, and Section 6.2.3 (the effect of the overlap threshold)
  2. Mark Everingham, S. M. Ali Eslami, Luc Van Gool, Christopher K. I. Williams, John Winn and Andrew Zisserman, The PASCAL Visual Object Classes challenge: a retrospective, International Journal of Computer Vision 111(1), 2015, 98-136, Section 2.4 (from 2010 on, AP uses all data points instead of 11 recall levels)
  3. Tsung-Yi Lin, Michael Maire, Serge Belongie, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick, Microsoft COCO: common objects in context, ECCV 2014, LNCS 8693, 740-755, The COCO data set and its detection task
  4. COCO consortium, Detection evaluation, The 12 metrics: AP averaged over IoU 0.50:0.05:0.95, AP at 0.50 and 0.75, the area ranges below 32^2 and above 96^2, at most 100 detections per image, and no distinction between AP and mAP
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection (precision, recall and average precision for detectors)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/ZNZ16Q/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ZNZ16Q/text.yaml