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 anchors and true boxes the rule takes 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 and the true boxes of one training image. A box is 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
ASSIGN(A, G, τ_pos, τ_neg) ▷ anchors A_1..A_n, true boxes G_1..G_m- 1
M[i][j] ← IoU(A_i, G_j) for every anchor i and true box j - 2
for each anchor i: m_i ← max_j M[i][j], g_i ← the first j with M[i][j] = m_i - 3
label_i ← 0 if m_i < τ_neg, else -1 (ignore) - 4
for each true box j with b_j ← max_i M[i][j] > 0 - 5
for each anchor i with M[i][j] = b_j: label_i ← 1 - 6
for each anchor i with m_i ≥ τ_pos: label_i ← 1 - 7
return the labels and the matched boxes g SAMPLE(label, B, f) ▷ batch size B, positive share f- 8
keep at most ⌊fB⌋ random positives, fill up to B with random negatives, set the rest to -1
A positive anchor learns the class of and the offsets of from . Faster R-CNN uses , , and . The paper says "higher than 0.7"; the py-faster-rcnn code uses , and so does this page. The code keeps 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 or when it ties for the best IoU of some true box with a positive best IoU. Otherwise it is negative when and ignored when .
- 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 , every anchor with IoU 0 for that box would tie and become positive.
Cost. Line L1 takes time and space. Lines L2 to L6 read each entry of a constant number of times, so they take too, and SAMPLE takes . For anchors and boxes that is IoU computations per image, small next to the network.
Example. Four anchors lie in a row: , , and . The true boxes are and a small . The IoUs with are , , and . The only anchor that meets is , with IoU . With the Faster R-CNN thresholds:
- has , between 0.3 and 0.7, so it is ignored.
- has , so it is positive and matched to .
- has , so it is negative.
- has , so line L3 makes it negative, but it is the best anchor for , so line L5 makes it positive and matched to .
Without lines L4 and L5 the small box would have no positive anchor. With the RetinaNet thresholds 0.5 and 0.4 and no best-anchor rule, is still ignored, since , and 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 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 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 is the only parameter. The paper reports a COCO AP of 38.0 at and 39.3 at (benchmark results).
Variations
- Thresholds. Each detector tunes and . 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- 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 still regresses to its own argmax , 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 anchors and 100 boxes the matrix has 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.
# 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
- Show that after ASSIGN every true box with has a positive anchor with .
- 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.
- Show that without the test 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?
- An anchor of side 32 and a true box of side 32 have centers apart along one axis. For which is the anchor positive, ignored and negative under the thresholds 0.7 and 0.3?
- 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 for anchors and true boxes, let , and let . Fix thresholds . Call anchor best when for some .
Claim 1 (the rule). After ASSIGN, exactly when or is best. For any other anchor, when and when . The matched box satisfies .
Proof. Line L3 sets every label to 0 or by the test . After that, lines L5 and L6 only write the value 1. Line L5 writes it for anchor exactly when some with has , that is, when is best. Line L6 writes it exactly when . 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 among the with .
Claim 2 (coverage). Every true box with has an anchor with and . A true box with makes no anchor positive through line L5.
Proof. Since is a maximum over a finite set, some anchor has , 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 with .
Claim 2 does not say that for that anchor. If for another box , then , and box can end with no anchor whose matched box is . 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 , no anchor is ignored.
Proof. By Claim 1 an ignored anchor has , which is empty when the two are equal.
Claim 4 (sampling). Let and be the numbers of positive and negative labels before SAMPLE. After SAMPLE there are positives and negatives, every kept label equals its old value, and every other label is .
Proof. Line L8 draws distinct positives without replacement, then distinct negatives, where is the number of positives drawn. Every label that is not drawn becomes , and a drawn label is copied. So the batch has at most labels, and at most of them are positive.
SSD matching. The SSD rule first sets every anchor to positive when is above its threshold, else negative, and then, for each true box in order, sets its best anchor (the first index of largest IoU) to positive and matched to . 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 .
ATSS. For each true box, the candidates are at most 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 positives for levels. ATSS does not promise a positive for every box: for the candidate IoUs the mean plus the sample standard deviation is , and no IoU reaches it.
References
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag RFHSZS Edit this page History Report an error Markdown