Techniqueadvanced
Anchor boxes
Also called default boxes, prior boxes.
A fixed set of reference boxes of several scales and aspect ratios at each feature map position, from which a detector predicts offsets and scores.
Anchor boxes are a fixed set of reference boxes that a detector places at every position of a feature map, with a few sizes and aspect ratios at each position. The detector does not search for boxes. For each anchor it predicts a class score and the four offsets of bounding box regression that move the anchor onto the object. So the anchors decide which boxes the detector can reach with small offsets, and anchor assignment decides which anchors learn which objects. Faster R-CNN introduced them for its region proposal network, and the single shot multibox detector calls them default boxes. The anchor grid costs time and space for a map with shapes; the network that scores them is not part of this page.
In plain words
A detector looks at a grid of positions over the image. At each position it has a small menu of boxes: a square, a tall box, a wide box, each in a small, a middle and a large size. These are the anchors. For each box on the menu the detector answers two questions: is there an object that fits this box, and how must the box move and stretch to fit it well? The anchors never move. Only the answers change from image to image. The menu is chosen so that every object in the image has some anchor close to it in place, size and shape. If an object has no close anchor, the detector has a hard time finding it. So the choice of sizes, shapes and grid spacing is a real design decision.
When it applies
The technique needs a feature map of positions, where position looks at an area of the image around the point . Here is the stride, the number of image pixels between two positions, and is an offset that each code base fixes: in SSD and in torchvision. A box is in continuous image coordinates.
An anchor shape is a size and an aspect ratio . The shape has and , so its area is for every ratio. With a set of sizes and a set of ratios there are shapes, and the map has anchors.
The technique fits a detector whose head is a convolution: the same small network runs at every position and outputs scores and offsets there. Then the anchors at one position all use the same features, and the shapes let the outputs specialize by size and shape. It also fits a detector with several feature maps, one set of anchor sizes per map. It does not fit a detector that predicts a set of boxes with no reference, such as DETR, or a detector that predicts boxes from points with no prior shape.
The template
ANCHORS(W_f, H_f, s, S, R, o) ▷ map size, stride, sizes, ratios, offset- 1
B ← empty list of shapes - 2
for each σ in S, for each r in R: append (σ / √r, σ √r) to B - 3
A ← empty list of boxes - 4
for v ← 0 to H_f - 1, for u ← 0 to W_f - 1 - 5
(c_x, c_y) ← ((u + o) s, (v + o) s) - 6
for each (w, h) in B: append (c_x - w/2, c_y - h/2, c_x + w/2, c_y + h/2) to A - 7
return A
Anchor of position is the box with center and the shape . The output order is fixed, position by position and shape by shape, so the detector output with index belongs to that anchor. Lines L1 and L2 depend only on and , so code computes them once. Lines L4 to L6 take time in the real RAM model, and the list uses space.
How close is the nearest anchor? A design question is the intersection over union between an object box and its best anchor. Four facts give the answer for simple cases, with proofs in the proof page.
- Two boxes with the same center and ratio and sizes have IoU . So sizes spaced by a factor 2, as in Faster R-CNN, give every centered square between two sizes a best IoU of at least , with at the size .
- Two boxes with the same center and area whose ratios differ by a factor have IoU . For this is , and for , the factor between the ratios and , it is .
- A square of side whose center is and away from the center of a square anchor of the same side has IoU with . On a grid of stride the nearest center is at most away in each axis, and the worst case is .
- For the worst case of fact 3 gives at stride 16 and at stride 4. So a small object on a coarse grid can have no anchor above 0.7, which is the reason why the matching rules have a "best anchor for each object" clause and why feature pyramids put small anchors on fine maps.
Example. The Faster R-CNN code places 9 anchors per position on a map of stride 16. With the legacy rule of that code (inclusive pixel boxes, base box , widths rounded), the 9 anchors of position are , and for ratio ; , and for ratio ; and , and for ratio . The wide ones are , and , so the rounding makes their areas a little larger than , and . A map, from an image of about , has anchors.
Implementation. The Python code has the generator of lines L1 to L7, the legacy generator of the Faster R-CNN code, IoU with exact fractions on integer boxes, the best IoU over a list of anchors by brute force, and the k-means of YOLOv2 on box sizes with the distance . The tests check the count, the area and the ratio of every shape, the centers for both offsets, the nine legacy boxes above, the four facts with exact values, that k-means finds three planted size clusters, and that more clusters give a higher mean best IoU.
Classic examples
- Faster R-CNN. Three areas , and and three ratios , and , so , on the last map of stride 16. The paper calls the scheme translation invariant: if an object moves, the same anchor at the new position and the same weights predict it.
- Single shot multibox detector. Default boxes on six feature maps. Map of has the scale of the image size, with and , ratios and one extra square of scale . SSD300 has 8732 default boxes in all.
- Feature pyramid network. One anchor size per level, to on the levels to , with three ratios each, so 15 shapes in all and 3 per position. The size grows with the stride, which keeps fact 4 the same on every level.
- RetinaNet. Three sizes , and times the base size of each pyramid level and three ratios, so 9 anchors per position, from to about pixels.
- YOLOv2. Five anchor shapes per cell of a map, found by k-means on the sizes of the training boxes with the distance of two centered boxes. On VOC 2007 the 5 cluster shapes give an average IoU of 61.0 with the closest shape, against 60.9 for the 9 hand-picked shapes of Faster R-CNN, and 9 clusters give 67.2 (benchmark results of the 2017 paper).
Variations
- Data-driven shapes. Choose the shapes by clustering the training boxes, as in YOLOv2, instead of by hand. With the distance the mean of a cluster is not the point that minimizes the sum of distances, so the k-means loop is a heuristic and the code stops after a fixed number of rounds.
- Anchors per level. With a pyramid, each level has its own sizes in proportion to its stride, as in FPN and RetinaNet.
- Densities. Some detectors put more anchors on small sizes, with centers at sub-stride offsets, to raise the IoU of fact 3 for small objects.
- Learned anchors. Guided anchoring and similar methods predict the anchor shape at each position from the features.
- Anchor-free detectors. FCOS and CenterNet use one point per position and predict distances to the sides or a size directly, which removes the anchor design but keeps the grid.
Pitfalls
- The offset . One code base centers anchors at , another at . Trained weights from one do not fit anchors from the other; the boxes are off by half a stride.
- The ratio convention. Some code takes and other code takes . With the symmetric set the set of shapes is the same, but the order changes, and the order must match the order of the network outputs.
- Inclusive pixels and rounding. The legacy anchors above are not exactly the continuous ones. Use one rule from training to test.
- Anchors outside the image. Large anchors near the border extend past the image. Faster R-CNN ignores them in training and clips the proposals at test time. Using them without care adds targets that point outside the image.
- Coverage gaps. A size or a shape with no close anchor gives few positive anchors in training and a low recall at test time. Check the best IoU of the training boxes with the anchors before training.
- Too many anchors. Doubling the shapes doubles the head outputs and the number of easy negatives; the extra negatives need sampling or a loss such as focal loss.
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-boxes/. The authors are listed in prov/JNRSBB.jsonl.
"""Anchor boxes: a fixed set of reference boxes at each position of a feature map.
A box is (x1, y1, x2, y2) in continuous image coordinates. The aspect ratio
r of a box is h / w, as in the Faster R-CNN code. A size sigma and a ratio r
give the box with w = sigma / sqrt(r) and h = sigma * sqrt(r), so its area is
sigma^2. Position (u, v) of a feature map with stride s has its anchors
centered at ((u + o) s, (v + o) s); the offset o is 0.5 in SSD and 0 in
torchvision, so state it. Standard library only.
"""
import math
from fractions import Fraction
def base_shapes(sizes, ratios):
"""The (w, h) of the anchors of one position, sizes outer, ratios inner."""
shapes = [] # @line L1
for sigma in sizes:
for r in ratios:
shapes.append((sigma / math.sqrt(r), sigma * math.sqrt(r))) # @line L2
return shapes
def anchors(wf, hf, stride, sizes, ratios, offset=0.5):
"""All anchors of a wf x hf feature map, position by position (rows, then columns)."""
shapes = base_shapes(sizes, ratios)
out = [] # @line L3
for v in range(hf): # @line L4
for u in range(wf):
cx, cy = (u + offset) * stride, (v + offset) * stride # @line L5
for w, h in shapes:
out.append((cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)) # @line L6
return out # @line L7
def legacy_base_anchors(base_size=16, ratios=(0.5, 1, 2), scales=(8, 16, 32)):
"""generate_anchors of the py-faster-rcnn code: inclusive pixel boxes, rounded sizes.
Python round() rounds halves to even, as numpy.round does in the original.
"""
w = h = base_size
xc = yc = 0.5 * (base_size - 1)
out = []
for r in ratios:
ws = round(math.sqrt(w * h / r))
hs = round(ws * r)
for s in scales:
ww, hh = ws * s, hs * s
out.append((xc - 0.5 * (ww - 1), yc - 0.5 * (hh - 1), xc + 0.5 * (ww - 1), yc + 0.5 * (hh - 1)))
return out
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 best_iou(box, anchor_list):
"""The largest IoU of the box with any anchor, by brute force."""
return max(iou(box, a) for a in anchor_list)
def centered_iou(wh1, wh2):
"""IoU of two boxes with the same center, given only (w, h)."""
iw, ih = min(wh1[0], wh2[0]), min(wh1[1], wh2[1])
inter = iw * ih
return inter / (wh1[0] * wh1[1] + wh2[0] * wh2[1] - inter)
def kmeans_shapes(shapes, k, rng, iters=50):
"""YOLOv2 dimension clusters: k-means on (w, h) with the distance 1 - centered IoU.
The center of a cluster is the mean (w, h) of its members, the usual k-means
update. The mean does not minimize the sum of 1 - IoU, so the loop is not
sure to settle; it stops at a fixed point or after iters rounds.
"""
centers = rng.sample(shapes, k)
assign = None
for _ in range(iters):
new = [max(range(k), key=lambda j: (centered_iou(s, centers[j]), -j)) for s in shapes]
if new == assign:
break
assign = new
for j in range(k):
members = [s for s, a in zip(shapes, assign) if a == j]
if members:
centers[j] = (sum(m[0] for m in members) / len(members),
sum(m[1] for m in members) / len(members))
return sorted(centers), assign
def mean_best_iou(shapes, centers):
"""Average over the shapes of the best centered IoU with a center, the YOLOv2 score."""
return sum(max(centered_iou(s, c) for c in centers) for s in shapes) / len(shapes)
test_anchor_boxes.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anchor-boxes/. The authors are listed in prov/JNRSBB.jsonl.
import math
import random
from fractions import Fraction
from anchor_boxes import (
anchors,
base_shapes,
best_iou,
centered_iou,
iou,
kmeans_shapes,
legacy_base_anchors,
mean_best_iou,
)
def test_count_area_and_ratio():
sizes, ratios = (128, 256, 512), (0.5, 1, 2)
a = anchors(60, 40, 16, sizes, ratios)
assert len(a) == 60 * 40 * 9
for k, (w, h) in enumerate(base_shapes(sizes, ratios)):
assert abs(w * h - sizes[k // 3] ** 2) < 1e-6
assert abs(h / w - ratios[k % 3]) < 1e-12
def test_centers_follow_stride_and_offset():
a = anchors(3, 2, 8, (16,), (1,), offset=0.5)
centers = [((b[0] + b[2]) / 2, (b[1] + b[3]) / 2) for b in a]
assert centers == [(4.0, 4.0), (12.0, 4.0), (20.0, 4.0), (4.0, 12.0), (12.0, 12.0), (20.0, 12.0)]
a0 = anchors(2, 1, 8, (16,), (1,), offset=0)
assert a0[0] == (-8.0, -8.0, 8.0, 8.0)
def test_legacy_table():
expected = [
(-84, -40, 99, 55), (-176, -88, 191, 103), (-360, -184, 375, 199),
(-56, -56, 71, 71), (-120, -120, 135, 135), (-248, -248, 263, 263),
(-36, -80, 51, 95), (-80, -168, 95, 183), (-168, -344, 183, 359),
]
assert legacy_base_anchors() == expected
def test_centered_same_ratio():
# Two centered boxes of one ratio and sizes s1 <= s2 have IoU (s1 / s2)^2.
for s1, s2 in [(32, 64), (100, 128), (7, 7)]:
assert abs(centered_iou((s1, s1 * 2), (s2, s2 * 2)) - (s1 / s2) ** 2) < 1e-12
def test_centered_same_area_ratio_factor():
# Same area, ratios that differ by a factor q: IoU 1 / (2 sqrt(q) - 1).
for q in (2.0, 4.0, 9.0):
b1 = base_shapes((100,), (1.0,))[0]
b2 = base_shapes((100,), (q,))[0]
assert abs(centered_iou(b1, b2) - 1 / (2 * math.sqrt(q) - 1)) < 1e-12
assert abs(centered_iou((2, 2), (1, 4)) - Fraction(1, 3)) < 1e-12
def test_octave_sizes_cover_half():
# Square sizes spaced by a factor 2 give every centered square between them IoU >= 1/2.
sizes = [32, 64, 128, 256]
for k in range(1000):
x = 32 * 2 ** (3 * k / 999)
best = max(centered_iou((x, x), (s, s)) for s in sizes)
assert best >= 0.5 - 1e-12
assert abs(max(centered_iou((32 * math.sqrt(2),) * 2, (s, s)) for s in sizes) - 0.5) < 1e-12
def test_half_stride_offset():
# The worst center for a square box of size 32 lies half a stride from an anchor center in x and y.
for stride, expected in [(16, Fraction(576, 1472)), (4, Fraction(900, 1148))]:
grid = [(u * stride - 16, v * stride - 16, u * stride + 16, v * stride + 16)
for u in range(-3, 4) for v in range(-3, 4)]
h = stride // 2
gt = (h - 16, h - 16, h + 16, h + 16)
assert best_iou(gt, grid) == expected
def test_grid_contains_every_anchor_box():
rng = random.Random(11)
a = anchors(5, 4, 16, (32, 64), (0.5, 1, 2))
for _ in range(20):
g = a[rng.randrange(len(a))]
assert abs(best_iou(g, a) - 1.0) < 1e-12
def test_kmeans_recovers_clusters():
rng = random.Random(5)
true = [(20.0, 40.0), (60.0, 60.0), (150.0, 75.0)]
shapes = []
for w, h in true:
for _ in range(40):
shapes.append((w * rng.uniform(0.95, 1.05), h * rng.uniform(0.95, 1.05)))
best = None
for seed in range(5):
centers, _ = kmeans_shapes(shapes, 3, random.Random(seed))
score = mean_best_iou(shapes, centers)
if best is None or score > best[0]:
best = (score, centers)
score, centers = best
assert score > 0.9
for (w, h), (cw, ch) in zip(sorted(true), centers):
assert abs(cw / w - 1) < 0.03 and abs(ch / h - 1) < 0.03
def test_more_clusters_do_not_hurt():
rng = random.Random(8)
shapes = [(rng.uniform(10, 200), rng.uniform(10, 200)) for _ in range(150)]
s1 = mean_best_iou(shapes, kmeans_shapes(shapes, 1, random.Random(0))[0])
s5 = mean_best_iou(shapes, kmeans_shapes(shapes, 5, random.Random(0))[0])
assert s5 > s1
def test_iou_check_values():
assert iou((0, 0, 2, 2), (1, 1, 3, 3)) == Fraction(1, 7)
assert iou((0, 0, 10, 10), (5, 0, 15, 10)) == Fraction(1, 3)
Exercises
- Show that the shape has area and ratio , and count the anchors of SSD300 from the map sizes with 4, 6, 6, 6, 4 and 4 boxes per position.
- Show that two centered boxes of the same area whose ratios differ by a factor have IoU . Which gives an IoU of exactly ?
- A square object of side 32 lies at the worst place on a grid of stride 16 with square anchors of side 32. Show that no anchor has an IoU above 0.4 with it. What is the largest stride for which some anchor of side 32 always has IoU at least 0.5?
- Sizes are spaced by a factor . Find the smallest best IoU of a centered square with sizes between and the largest size, as a function of .
- Run k-means with the distance on a small set of box sizes and find an input where the mean update makes the total distance larger.
Proof: The anchor grid has the stated shapes and centers, and the IoU of an object with its nearest anchor has closed forms for size, shape and position errorsfull
A box is with and , and its area is . For two boxes and write with .
Claim 1 (the grid). ANCHORS returns boxes. The box for position and the shape of size and ratio has center , width , height , area and ratio .
Proof. Line L2 appends one shape for each pair , so has shapes. The loop of line L4 runs once for each of the positions, and line L6 appends one box for each shape, so the count is . The box of line L6 has , and the midpoint of line L5. Its area is and its ratio is .
In Claims 2 to 4 two boxes have the same center, so each box is fixed by its width and height. Two such boxes with sizes and overlap in a box of size , since along each axis the shorter interval lies inside the longer one.
Claim 2 (size error). Two centered boxes with the same ratio and sizes have IoU .
Proof. With the same ratio, box 1 has width and height times those of box 2, so it lies inside box 2. The intersection is box 1 and the union is box 2, and the IoU is .
Corollary (octave sizes). Let the square sizes be and let a centered square have side with . Then its best IoU with the anchors is at least .
Proof. Pick with . By Claim 2 the two anchors give and . The first falls and the second rises as grows, and they are equal at , where both are . So the larger of the two is at least for every in the interval.
Claim 3 (shape error). Two centered boxes of area with ratios and have IoU .
Proof. Box has width and height . Since , box 2 is the narrower and box 1 is the shorter, so the intersection has width and height , and area . The union is . Dividing, the IoU is .
For the IoU is , and for it is .
Claim 4 (position error). Let and be squares of side whose centers differ by and with . Then with , and this value does not increase when or grows.
Proof. Along the two intervals have length and start apart, so they overlap in a length ; the same holds along . So and . The function has derivative on , so it grows with , and does not grow when or grows.
Corollary (stride). Let the anchors be squares of side centered at the points for all integers and , with . Then every square of side has an anchor with IoU at least , , and a square centered at has no anchor with a higher IoU.
Proof. Rounding the center of to the nearest grid point in each axis gives an anchor with , and Claim 4 gives the bound. For the square at the middle of four grid points, every anchor has and , so by Claim 4 none does better than .
For this gives at and at .
On the k-means of YOLOv2. The assignment step puts each box in the cluster with the smallest distance , so it does not raise the total distance for fixed centers. The update step replaces each center by the mean width and height of its members. For the squared Euclidean distance the mean is the minimizer, which is why plain k-means never raises its objective. For the mean is not always the minimizer, so the total distance can rise in an update step, and the loop has no proof of termination. The code stops at a fixed point of the assignment or after a set number of rounds, so it always stops; the tests check its result on planted clusters, not a general guarantee.
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.1, Anchors (3 scales and 3 aspect ratios, k = 9 anchors at each position, translation invariance, multi-scale anchors as regression references)
- 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, Choosing scales and aspect ratios for default boxes (the linear scale rule with s_min = 0.2 and s_max = 0.9, the ratios 1, 2, 3, 1/2, 1/3 and the extra box of scale sqrt(s_k s_k+1))
- Tsung-Yi Lin, Piotr Dollar, Ross Girshick, Kaiming He, Bharath Hariharan and Serge Belongie, Feature pyramid networks for object detection, CVPR 2017, Section 4.1, Feature pyramid networks for RPN (one anchor size from 32 to 512 per pyramid level, 3 aspect ratios, 15 anchor shapes in all)
- Joseph Redmon and Ali Farhadi, YOLO9000: better, faster, stronger, CVPR 2017 (arXiv 1612.08242), Section 2, paragraphs Convolutional with anchor boxes and Dimension clusters (k-means with the distance 1 - IOU, k = 5, Table 1)
- 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 JNRSBB Edit this page History Report an error Markdown