Algorithm Search⌘K

Techniqueadvanced

IoU-based anchor assignment

Also called anchor matching, label assignment for detection.

Label each anchor positive when its IoU with some true box exceeds a high threshold or is the best for that box, negative below a low threshold, else ignored.

Anchor assignment decides, for each anchor box in a training image, whether it must learn an object, learn background, or stay out of the loss. A positive anchor learns the class of its matched true box and the box regression offsets to that box. A negative anchor learns the class "background". An ignored anchor adds nothing. The rule of Faster R-CNN uses the intersection over union of the anchor with the true boxes: positive above a high threshold or when it is the best anchor for some true box, negative below a low threshold, and ignored between. With nn anchors and mm true boxes the rule takes O(nm)O(nm) time. It is a heuristic: the thresholds and the sampling come from experiments, not from a theorem.

In plain words

During training a detector has thousands of anchors and a few true objects in each image. Before it can compute a loss, it must say what each anchor should have predicted. An anchor that covers an object well should say "this object, and move me this much". An anchor on empty ground should say "nothing here". An anchor that half covers an object is unclear, so the simplest choice is to leave it out. Also, every object must get at least one anchor, even a small object that no anchor covers well, or the detector never learns to find it. Most anchors are empty, so the detector also picks a balanced subset of them for each step.

When it applies

The technique needs a fixed list of anchors A1,…,AnA_1, \dots, A_n and the true boxes G1,…,GmG_1, \dots, G_m of one training image. A box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in continuous coordinates. It applies to every detector that predicts at fixed reference boxes: the region proposal network of Faster R-CNN, the single shot multibox detector, RetinaNet and the anchor heads of a feature pyramid network. The same kind of rule labels the proposals of Fast R-CNN, with the proposals in the role of the anchors.

It does not apply to a set predictor such as DETR, which assigns its predictions to the true boxes by a one-to-one matching of minimum cost, computed with the Hungarian algorithm for each image.

The template

  1. ASSIGN(A, G, τ_pos, τ_neg) ▷ anchors A_1..A_n, true boxes G_1..G_m
  2. 1M[i][j] ← IoU(A_i, G_j) for every anchor i and true box j
  3. 2for each anchor i: m_i ← max_j M[i][j], g_i ← the first j with M[i][j] = m_i
  4. 3label_i ← 0 if m_i < τ_neg, else -1 (ignore)
  5. 4for each true box j with b_j ← max_i M[i][j] > 0
  6. 5for each anchor i with M[i][j] = b_j: label_i ← 1
  7. 6for each anchor i with m_i ≥ τ_pos: label_i ← 1
  8. 7return the labels and the matched boxes g
  9. SAMPLE(label, B, f) ▷ batch size B, positive share f
  10. 8keep at most ⌊fB⌋ random positives, fill up to B with random negatives, set the rest to -1

A positive anchor ii learns the class of GgiG_{g_i} and the offsets of GgiG_{g_i} from AiA_i. Faster R-CNN uses τpos=0.7\tau_{pos} = 0.7, τneg=0.3\tau_{neg} = 0.3, B=256B = 256 and f=0.5f = 0.5. The paper says "higher than 0.7"; the py-faster-rcnn code uses ≥0.7\ge 0.7, and so does this page. The code keeps gig_i as the argmax of the row even for an anchor made positive by line L5, as py-faster-rcnn, Detectron2 and torchvision do.

The rule has these properties, which follow line by line from the template and which the tests check on random boxes:

  • An anchor is positive exactly when mi≥τposm_i \ge \tau_{pos} or when it ties for the best IoU of some true box with a positive best IoU. Otherwise it is negative when mi<τnegm_i < \tau_{neg} and ignored when τneg≤mi<τpos\tau_{neg} \le m_i < \tau_{pos}.
  • Every true box with a positive best IoU has at least one positive anchor at that best IoU (line L5). Line L6 cannot undo line L5, since it only sets labels to 1.
  • A true box with IoU 0 with every anchor has no positive anchor. Line L4 skips it on purpose: without the test bj>0b_j > 0, every anchor with IoU 0 for that box would tie and become positive.

Cost. Line L1 takes O(nm)O(nm) time and space. Lines L2 to L6 read each entry of MM a constant number of times, so they take O(nm)O(nm) too, and SAMPLE takes O(n)O(n). For n=20000n = 20000 anchors and m=10m = 10 boxes that is 2⋅1052 \cdot 10^5 IoU computations per image, small next to the network.

Example. Four anchors lie in a row: A1=(0,0,10,10)A_1 = (0, 0, 10, 10), A2=(5,0,15,10)A_2 = (5, 0, 15, 10), A3=(10,0,20,10)A_3 = (10, 0, 20, 10) and A4=(20,0,30,10)A_4 = (20, 0, 30, 10). The true boxes are G1=(4,0,14,10)G_1 = (4, 0, 14, 10) and a small G2=(21,0,25,4)G_2 = (21, 0, 25, 4). The IoUs with G1G_1 are 60/140=3/760/140 = 3/7, 90/110=9/1190/110 = 9/11, 40/160=1/440/160 = 1/4 and 00. The only anchor that meets G2G_2 is A4A_4, with IoU 16/100=0.1616/100 = 0.16. With the Faster R-CNN thresholds:

  • A1A_1 has m1=0.429m_1 = 0.429, between 0.3 and 0.7, so it is ignored.
  • A2A_2 has m2=0.818≥0.7m_2 = 0.818 \ge 0.7, so it is positive and matched to G1G_1.
  • A3A_3 has m3=0.25<0.3m_3 = 0.25 < 0.3, so it is negative.
  • A4A_4 has m4=0.16<0.3m_4 = 0.16 < 0.3, so line L3 makes it negative, but it is the best anchor for G2G_2, so line L5 makes it positive and matched to G2G_2.

Without lines L4 and L5 the small box G2G_2 would have no positive anchor. With the RetinaNet thresholds 0.5 and 0.4 and no best-anchor rule, A1A_1 is still ignored, since 3/7≥0.43/7 \ge 0.4, and A4A_4 is negative.

Implementation. The Python code has the rule of lines L1 to L7 with the best-anchor rule as an option, the sampling of line L8, the SSD matching and ATSS. IoU is exact with fractions on integer boxes, so ties are exact. The tests check the example, all three properties above on random boxes against the definition, the sampling counts, that SSD gives each true box its best anchor, and an ATSS threshold computed by hand.

Classic examples

  • Faster R-CNN, region proposal network. The template with 0.7 and 0.3 and the best-anchor rule, and 256 anchors per image with up to half positive. Anchors that cross the image border are ignored in training.
  • Fast R-CNN, second stage. Proposals with IoU at least 0.5 with a true box are foreground, those with a maximum IoU in [0.1,0.5)[0.1, 0.5) are background, and 25 percent of the 64 regions sampled from each image are foreground. The lower bound 0.1 acts as a heuristic for hard negatives.
  • Single shot multibox detector. Each true box first takes the default box with the best IoU, then every default box with IoU above 0.5 with some true box is positive. There is no ignore zone. The many negatives are cut by hard negative mining to at most 3 negatives per positive, taking the ones with the highest confidence loss.
  • RetinaNet. Positive at IoU 0.5 or more, background below 0.4, ignored between, with no sampling: the focal loss down-weights the easy negatives instead.
  • ATSS. For each true box, take the k=9k = 9 anchors of each pyramid level whose centers are closest to the box center. Set the threshold to the mean plus the standard deviation of their IoUs, and keep those at or above it whose center lies inside the box. An anchor positive for several boxes takes the one with the highest IoU. The threshold adapts to each box, and kk is the only parameter. The paper reports a COCO AP of 38.0 at k=3k = 3 and 39.3 at k=9k = 9 (benchmark results).

Variations

  • Thresholds. Each detector tunes τpos\tau_{pos} and τneg\tau_{neg}. Cascade R-CNN trains a chain of second-stage heads at IoU thresholds 0.5, 0.6 and 0.7.
  • Center rules. Anchor-free detectors label a point positive when it lies in the box, or in a central part of it, and in the right pyramid level for the box size.
  • Set matching. DETR and its followers use a one-to-one matching of predictions and true boxes by a cost that mixes class scores and box distances, so each true box has exactly one positive prediction.
  • Dynamic assignment. OTA and SimOTA assign by a transport or a top-kk rule on a cost that includes the current predictions, so the labels change during training.

Pitfalls

  • Strict and non-strict thresholds. "Above 0.7" and "at least 0.7" differ for exact values, which occur with integer boxes and with anchors equal to a true box. State the choice.
  • The matched box of a forced anchor. In the Faster R-CNN code an anchor made positive by line L5 for box jj still regresses to its own argmax gig_i, which can be another box. When two boxes share their best anchor, one of them has no anchor that learns it. The SSD code instead gives the forced anchor to the box that forced it.
  • Boxes with no overlap. A true box that lies between all anchors, or outside the area they cover, has no positive anchor. Check the training set for such boxes, or add anchors.
  • Crowd and difficult boxes. COCO marks crowd regions, and PASCAL VOC marks difficult objects. Anchors that match them are usually ignored, not negative. Treating them as background teaches the detector to miss them.
  • Sampling with few positives. If an image has 10 positive anchors, the batch of 256 gets 246 negatives, not 128. The share of positives then varies from image to image, which changes the effective loss weight.
  • The cost of the IoU matrix. For 10510^5 anchors and 100 boxes the matrix has 10710^7 entries. Compute it in blocks or on the device that holds the anchors.

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.

anchor_assignment.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anchor-assignment/. The authors are listed in prov/RFHSZS.jsonl.
"""Anchor assignment: which anchors learn which true boxes.

A box is (x1, y1, x2, y2) in continuous coordinates. A label is 1 (positive,
the anchor learns the class and the offsets of its matched true box), 0
(negative, background) or -1 (ignored in the loss). Standard library only.

assign_max_iou is the rule of the Faster R-CNN region proposal network:
positive at IoU >= pos_thr (the code of py-faster-rcnn uses >=), negative
below neg_thr, and every anchor that ties for the best IoU of some true box is
positive too. The matched box of an anchor is always its own argmax, as in
py-faster-rcnn, Detectron2 and torchvision.
"""

import math
from fractions import Fraction


def iou(a, b):
    """IoU of two boxes; a Fraction on integer or Fraction 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 all(isinstance(v, (int, Fraction)) for v in (inter, union)):
        return Fraction(inter) / union
    return inter / union


def iou_matrix(anchors, gts):
    return [[iou(a, g) for g in gts] for a in anchors]  # @line L1


def assign_max_iou(anchors, gts, pos_thr=0.7, neg_thr=0.3, best_for_gt=True):
    """Return (labels, matched): labels in {1, 0, -1} and the index of the matched true box.

    matched[i] is -1 when there is no true box. With best_for_gt=False this is
    the RetinaNet rule (0.5 and 0.4 there).
    """
    n = len(anchors)
    if not gts:
        return [0] * n, [-1] * n
    m = iou_matrix(anchors, gts)
    labels, matched, best = [], [], []
    for i in range(n):
        row = m[i]
        mi = max(row)  # @line L2
        matched.append(row.index(mi))
        best.append(mi)
        labels.append(0 if mi < neg_thr else -1)  # @line L3
    if best_for_gt:
        for j in range(len(gts)):
            bj = max(m[i][j] for i in range(n))  # @line L4
            if bj > 0:
                for i in range(n):
                    if m[i][j] == bj:
                        labels[i] = 1  # @line L5
    for i in range(n):
        if best[i] >= pos_thr:
            labels[i] = 1  # @line L6
    return labels, matched  # @line L7


def sample(labels, batch, fraction, rng):
    """Keep at most floor(fraction * batch) random positives, fill to batch with negatives."""
    pos = [i for i, v in enumerate(labels) if v == 1]
    neg = [i for i, v in enumerate(labels) if v == 0]
    n_pos = min(len(pos), int(math.floor(fraction * batch)))
    keep_pos = set(rng.sample(pos, n_pos))  # @line L8
    keep_neg = set(rng.sample(neg, min(len(neg), batch - n_pos)))
    out = []
    for i, v in enumerate(labels):
        if (v == 1 and i in keep_pos) or (v == 0 and i in keep_neg):
            out.append(v)
        else:
            out.append(-1)
    return out


def assign_ssd(anchors, gts, thr=0.5):
    """SSD matching: each true box takes its best anchor, then every anchor above thr takes its argmax.

    There is no ignore zone: all other anchors are negative. A forced anchor
    keeps the true box that forced it, as in common SSD code; a later true box
    wins when two pick the same anchor.
    """
    n = len(anchors)
    if not gts:
        return [0] * n, [-1] * n
    m = iou_matrix(anchors, gts)
    matched = [max(range(len(gts)), key=lambda j: (m[i][j], -j)) for i in range(n)]
    labels = [1 if m[i][matched[i]] > thr else 0 for i in range(n)]
    for j in range(len(gts)):
        i_best = max(range(n), key=lambda i: (m[i][j], -i))
        labels[i_best] = 1
        matched[i_best] = j
    return labels, matched


def center(b):
    return ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)


def mean_std(values):
    """Mean and sample standard deviation (n - 1), as torch.std in the ATSS code."""
    n = len(values)
    mu = sum(values) / n
    if n < 2:
        return mu, 0.0
    return mu, math.sqrt(sum((v - mu) ** 2 for v in values) / (n - 1))


def assign_atss(levels, gts, k=9):
    """Adaptive training sample selection of Zhang et al. (CVPR 2020).

    levels is a list of anchor lists, one per pyramid level. For each true box,
    take the k anchors of each level whose centers are closest to its center,
    set the threshold to the mean plus the standard deviation of their IoUs,
    and keep those at or above it whose center lies inside the box. An anchor
    that is positive for several boxes takes the one with the highest IoU.
    Returns labels in {1, 0} and matched indices over the flat anchor list.
    """
    flat = [a for level in levels for a in level]
    offsets, start = [], 0
    for level in levels:
        offsets.append(start)
        start += len(level)
    labels, matched, best = [0] * len(flat), [-1] * len(flat), [-1.0] * len(flat)
    for j, g in enumerate(gts):
        gx, gy = center(g)
        cand = []
        for li, level in enumerate(levels):
            dist = sorted(range(len(level)),
                          key=lambda i: ((center(level[i])[0] - gx) ** 2 + (center(level[i])[1] - gy) ** 2, i))
            cand.extend(offsets[li] + i for i in dist[:k])
        ious = [float(iou(flat[i], g)) for i in cand]
        mu, sd = mean_std(ious)
        thr = mu + sd
        for i, v in zip(cand, ious):
            cx, cy = center(flat[i])
            inside = g[0] < cx < g[2] and g[1] < cy < g[3]
            if v >= thr and inside and v > best[i]:
                labels[i], matched[i], best[i] = 1, j, v
    return labels, matched
test_anchor_assignment.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anchor-assignment/. The authors are listed in prov/RFHSZS.jsonl.

import random
from fractions import Fraction

from anchor_assignment import (
    assign_atss,
    assign_max_iou,
    assign_ssd,
    iou,
    iou_matrix,
    mean_std,
    sample,
)

ANCHORS = [(0, 0, 10, 10), (5, 0, 15, 10), (10, 0, 20, 10), (20, 0, 30, 10)]
GTS = [(4, 0, 14, 10), (21, 0, 25, 4)]


def rand_box(rng, size=100):
    x1, y1 = rng.randint(0, size - 2), rng.randint(0, size - 2)
    return (x1, y1, rng.randint(x1 + 1, size), rng.randint(y1 + 1, size))


def test_page_example():
    m = iou_matrix(ANCHORS, GTS)
    assert [row[0] for row in m] == [Fraction(3, 7), Fraction(9, 11), Fraction(1, 4), 0]
    assert [row[1] for row in m] == [0, 0, 0, Fraction(4, 25)]
    labels, matched = assign_max_iou(ANCHORS, GTS)
    assert labels == [-1, 1, 0, 1]
    assert matched == [0, 0, 0, 1]
    labels, _ = assign_max_iou(ANCHORS, GTS, best_for_gt=False)
    assert labels == [-1, 1, 0, 0]
    # RetinaNet thresholds: 3/7 lies in [0.4, 0.5), so the first anchor is still ignored.
    labels, _ = assign_max_iou(ANCHORS, GTS, 0.5, 0.4, best_for_gt=False)
    assert labels == [-1, 1, 0, 0]


def test_rule_against_definition():
    rng = random.Random(1)
    for _ in range(60):
        anchors = [rand_box(rng) for _ in range(25)]
        gts = [rand_box(rng) for _ in range(rng.randint(1, 4))]
        labels, matched = assign_max_iou(anchors, gts)
        m = [[iou(a, g) for g in gts] for a in anchors]
        best_gt = [max(m[i][j] for i in range(len(anchors))) for j in range(len(gts))]
        for i in range(len(anchors)):
            mi = max(m[i])
            assert m[i][matched[i]] == mi
            is_best = any(m[i][j] == best_gt[j] > 0 for j in range(len(gts)))
            if mi >= Fraction(7, 10) or is_best:
                assert labels[i] == 1
            elif mi < Fraction(3, 10):
                assert labels[i] == 0
            else:
                assert labels[i] == -1
        for j in range(len(gts)):
            if best_gt[j] > 0:
                assert any(labels[i] == 1 and m[i][j] == best_gt[j] for i in range(len(anchors)))


def test_ties_and_no_overlap():
    anchors = [(0, 0, 10, 10), (10, 0, 20, 10), (40, 40, 50, 50)]
    labels, _ = assign_max_iou(anchors, [(5, 0, 15, 10)])
    assert labels == [1, 1, 0]
    # A true box that touches no anchor makes no anchor positive.
    labels, matched = assign_max_iou(anchors, [(100, 100, 110, 110)])
    assert labels == [0, 0, 0] and matched == [0, 0, 0]
    assert assign_max_iou(anchors, []) == ([0, 0, 0], [-1, -1, -1])


def test_sampling():
    rng = random.Random(2)
    labels = [1] * 300 + [0] * 5000 + [-1] * 200
    out = sample(labels, 256, 0.5, rng)
    assert out.count(1) == 128 and out.count(0) == 128
    assert all(o == -1 or o == v for o, v in zip(out, labels))
    out = sample([1] * 10 + [0] * 5000, 256, 0.5, rng)
    assert out.count(1) == 10 and out.count(0) == 246


def test_ssd_every_box_gets_an_anchor():
    rng = random.Random(3)
    for _ in range(60):
        anchors = [rand_box(rng) for _ in range(30)]
        gts = [rand_box(rng) for _ in range(rng.randint(1, 3))]
        labels, matched = assign_ssd(anchors, gts)
        assert -1 not in labels
        m = [[iou(a, g) for g in gts] for a in anchors]
        for i in range(len(anchors)):
            if max(m[i]) > Fraction(1, 2):
                assert labels[i] == 1
        bests = [max(range(len(anchors)), key=lambda i: (m[i][j], -i)) for j in range(len(gts))]
        if len(set(bests)) == len(gts):
            for j, i in enumerate(bests):
                assert labels[i] == 1 and matched[i] == j


def test_ssd_example():
    labels, matched = assign_ssd(ANCHORS, GTS)
    assert labels == [0, 1, 0, 1] and matched[1] == 0 and matched[3] == 1


def test_mean_std():
    mu, sd = mean_std([1.0, 2.0, 3.0, 4.0])
    assert mu == 2.5 and abs(sd - (5 / 3) ** 0.5) < 1e-12


def grid(stride, size, n):
    return [(u * stride + stride / 2 - size / 2, v * stride + stride / 2 - size / 2,
             u * stride + stride / 2 + size / 2, v * stride + stride / 2 + size / 2)
            for v in range(n) for u in range(n)]


def test_atss_properties():
    rng = random.Random(4)
    levels = [grid(8, 32, 16), grid(16, 64, 8), grid(32, 128, 4)]
    flat = [a for lv in levels for a in lv]
    for _ in range(20):
        gts = []
        for _ in range(rng.randint(1, 3)):
            w, h = rng.uniform(16, 100), rng.uniform(16, 100)
            x, y = rng.uniform(0, 128 - w), rng.uniform(0, 128 - h)
            gts.append((x, y, x + w, y + h))
        labels, matched = assign_atss(levels, gts, k=9)
        for i, v in enumerate(labels):
            if v == 1:
                g = gts[matched[i]]
                cx, cy = (flat[i][0] + flat[i][2]) / 2, (flat[i][1] + flat[i][3]) / 2
                assert g[0] < cx < g[2] and g[1] < cy < g[3]
            else:
                assert matched[i] == -1
        # Only the k nearest anchors of each level are candidates: at most 27 per box.
        for j in range(len(gts)):
            assert sum(1 for i in range(len(flat)) if matched[i] == j) <= 27


def test_atss_threshold_by_hand():
    # One level, k = 3. The candidates have IoUs 1, 1/3 and 1/3 with the box:
    # mean 5/9, sample std 0.3849, threshold 0.940, so only the exact anchor passes.
    level = [(0, 0, 4, 4), (2, 0, 6, 4), (-2, 0, 2, 4), (20, 20, 24, 24)]
    assert iou(level[1], (0, 0, 4, 4)) == Fraction(1, 3)
    labels, matched = assign_atss([level], [(0, 0, 4, 4)], k=3)
    assert labels == [1, 0, 0, 0] and matched == [0, -1, -1, -1]

Exercises

  1. Show that after ASSIGN every true box jj with max⁡iM[i][j]>0\max_i M[i][j] > 0 has a positive anchor ii with M[i][j]=max⁡iM[i][j]M[i][j] = \max_i M[i][j].
  2. Find a set of anchors and two true boxes for which the Faster R-CNN rule leaves one true box with no anchor whose matched box is that true box.
  3. Show that without the test bj>0b_j > 0 on line L4, a true box that meets no anchor makes every anchor with IoU 0 for it positive. What would such an anchor learn?
  4. An anchor of side 32 and a true box of side 32 have centers dd apart along one axis. For which dd is the anchor positive, ignored and negative under the thresholds 0.7 and 0.3?
  5. In ATSS, find three IoU values for the candidates of a true box for which no candidate reaches the threshold mean plus sample standard deviation.
Proof: ASSIGN labels each anchor by the stated rule, gives every overlapped true box a positive anchor at its best IoU, and SAMPLE keeps the stated countsfull

Let M[i][j]=IoU⁡(Ai,Gj)M[i][j] = \operatorname{IoU}(A_i, G_j) for nn anchors and m≥1m \ge 1 true boxes, let mi=max⁡jM[i][j]m_i = \max_j M[i][j], and let bj=max⁡iM[i][j]b_j = \max_i M[i][j]. Fix thresholds 0≤τneg≤τpos0 \le \tau_{neg} \le \tau_{pos}. Call anchor ii best when M[i][j]=bj>0M[i][j] = b_j > 0 for some jj.

Claim 1 (the rule). After ASSIGN, labeli=1\text{label}_i = 1 exactly when mi≥τposm_i \ge \tau_{pos} or ii is best. For any other anchor, labeli=0\text{label}_i = 0 when mi<τnegm_i < \tau_{neg} and labeli=−1\text{label}_i = -1 when τneg≤mi<τpos\tau_{neg} \le m_i < \tau_{pos}. The matched box gig_i satisfies M[i][gi]=miM[i][g_i] = m_i.

Proof. Line L3 sets every label to 0 or −1-1 by the test mi<τnegm_i < \tau_{neg}. After that, lines L5 and L6 only write the value 1. Line L5 writes it for anchor ii exactly when some jj with bj>0b_j > 0 has M[i][j]=bjM[i][j] = b_j, that is, when ii is best. Line L6 writes it exactly when mi≥τposm_i \ge \tau_{pos}. So a label is 1 exactly when one of the two conditions holds, and any other label keeps its value from line L3. Line L2 picks gig_i among the jj with M[i][j]=miM[i][j] = m_i. □\square

Claim 2 (coverage). Every true box jj with bj>0b_j > 0 has an anchor ii with labeli=1\text{label}_i = 1 and M[i][j]=bjM[i][j] = b_j. A true box with bj=0b_j = 0 makes no anchor positive through line L5.

Proof. Since bjb_j is a maximum over a finite set, some anchor ii has M[i][j]=bjM[i][j] = b_j, and line L5 sets its label to 1. By Claim 1 no later line sets a label to anything but 1. Line L4 skips every jj with bj=0b_j = 0. □\square

Claim 2 does not say that gi=jg_i = j for that anchor. If M[i][k]>M[i][j]M[i][k] > M[i][j] for another box kk, then gi=kg_i = k, and box jj can end with no anchor whose matched box is jj. This is the behaviour of the reference code, and the page lists it as a pitfall.

Claim 3 (no ignored anchors without a gap). If τneg=τpos\tau_{neg} = \tau_{pos}, no anchor is ignored.

Proof. By Claim 1 an ignored anchor has τneg≤mi<τpos\tau_{neg} \le m_i < \tau_{pos}, which is empty when the two are equal. □\square

Claim 4 (sampling). Let PP and NN be the numbers of positive and negative labels before SAMPLE. After SAMPLE there are min⁡(P,⌊fB⌋)\min(P, \lfloor fB \rfloor) positives and min⁡(N,B−min⁡(P,⌊fB⌋))\min(N, B - \min(P, \lfloor fB \rfloor)) negatives, every kept label equals its old value, and every other label is −1-1.

Proof. Line L8 draws min⁡(P,⌊fB⌋)\min(P, \lfloor fB \rfloor) distinct positives without replacement, then min⁡(N,B−p)\min(N, B - p) distinct negatives, where pp is the number of positives drawn. Every label that is not drawn becomes −1-1, and a drawn label is copied. So the batch has at most BB labels, and at most ⌊fB⌋\lfloor fB \rfloor of them are positive. □\square

SSD matching. The SSD rule first sets every anchor to positive when mim_i is above its threshold, else negative, and then, for each true box jj in order, sets its best anchor (the first index of largest IoU) to positive and matched to jj. So every true box whose best anchor is not taken by a later box has an anchor matched to it, and when the best anchors of all boxes are distinct, every true box has one. There is no label −1-1.

ATSS. For each true box, the candidates are at most kk anchors per level, and an anchor becomes positive for the box only if its IoU is at least the mean plus the standard deviation of the candidate IoUs and its center lies strictly inside the box. When an anchor passes for several boxes, the code keeps the box with the strictly highest IoU, and the first one on a tie. So every positive anchor has its center inside its matched box, and each box has at most kLkL positives for LL levels. ATSS does not promise a positive for every box: for the candidate IoUs 1,1,01, 1, 0 the mean plus the sample standard deviation is 2/3+1/3≈1.2442/3 + 1/\sqrt 3 \approx 1.244, and no IoU reaches it.

References

  1. Shaoqing Ren, Kaiming He, Ross Girshick and Jian Sun, Faster R-CNN: towards real-time object detection with region proposal networks, IEEE Transactions on Pattern Analysis and Machine Intelligence 39(6), 2017, 1137-1149, Section 3.1.2, Loss function (positive at the highest IoU for a true box or above 0.7, negative below 0.3 for all true boxes, the rest left out), and Section 3.1.3 (256 sampled anchors, up to 1:1)
  2. Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, Scott Reed, Cheng-Yang Fu and Alexander C. Berg, SSD: single shot multibox detector, ECCV 2016, Section 2.2, Matching strategy (each true box to its best default box, then every default box above 0.5) and Hard negative mining (at most 3:1)
  3. Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He and Piotr Dollar, Focal loss for dense object detection, ICCV 2017 (arXiv 1708.02002), Section 4, RetinaNet detector, paragraph Anchors (positive at IoU 0.5, background below 0.4, the rest ignored)
  4. Shifeng Zhang, Cheng Chi, Yongqiang Yao, Zhen Lei and Stan Z. Li, Bridging the gap between anchor-based and anchor-free detection via adaptive training sample selection, CVPR 2020 (arXiv 1912.02424), Section 4.1, Algorithm 1 (k nearest anchors per level, threshold mean plus standard deviation of their IoUs, center inside the box)
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection

Where this leads

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/RFHSZS/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)
WritingW3 standard
  • five exercises