Algorithm Search⌘K

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 O(WfHfk)O(W_f H_f k) time and space for a Wf×HfW_f \times H_f map with kk 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 Wf×HfW_f \times H_f positions, where position (u,v)(u, v) looks at an area of the image around the point ((u+o)s,(v+o)s)((u + o)s, (v + o)s). Here ss is the stride, the number of image pixels between two positions, and oo is an offset that each code base fixes: o=0.5o = 0.5 in SSD and o=0o = 0 in torchvision. A box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in continuous image coordinates.

An anchor shape is a size σ\sigma and an aspect ratio r=h/wr = h / w. The shape has w=σ/rw = \sigma / \sqrt r and h=σrh = \sigma \sqrt r, so its area is σ2\sigma^2 for every ratio. With a set SS of sizes and a set RR of ratios there are k=∣S∣⋅∣R∣k = |S| \cdot |R| shapes, and the map has WfHfkW_f H_f k anchors.

The technique fits a detector whose head is a convolution: the same small network runs at every position and outputs kk scores and 4k4k 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

  1. ANCHORS(W_f, H_f, s, S, R, o) ▷ map size, stride, sizes, ratios, offset
  2. 1B ← empty list of shapes
  3. 2for each σ in S, for each r in R: append (σ / √r, σ √r) to B
  4. 3A ← empty list of boxes
  5. 4for v ← 0 to H_f - 1, for u ← 0 to W_f - 1
  6. 5(c_x, c_y) ← ((u + o) s, (v + o) s)
  7. 6for each (w, h) in B: append (c_x - w/2, c_y - h/2, c_x + w/2, c_y + h/2) to A
  8. 7return A

Anchor jj of position (u,v)(u, v) is the box with center ((u+o)s,(v+o)s)((u + o)s, (v + o)s) and the shape BjB_j. The output order is fixed, position by position and shape by shape, so the detector output with index (v,u,j)(v, u, j) belongs to that anchor. Lines L1 and L2 depend only on SS and RR, so code computes them once. Lines L4 to L6 take O(WfHfk)O(W_f H_f k) time in the real RAM model, and the list uses O(WfHfk)O(W_f H_f k) 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.

  1. Two boxes with the same center and ratio and sizes σ1≤σ2\sigma_1 \le \sigma_2 have IoU (σ1/σ2)2(\sigma_1 / \sigma_2)^2. 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 1/21/2, with 1/21/2 at the size σ2\sigma \sqrt 2.
  2. Two boxes with the same center and area whose ratios differ by a factor q≥1q \ge 1 have IoU 1/(2q−1)1/(2\sqrt q - 1). For q=2q = 2 this is 0.5470.547, and for q=4q = 4, the factor between the ratios 1/21/2 and 22, it is 1/31/3.
  3. A square of side σ\sigma whose center is dxd_x and dyd_y away from the center of a square anchor of the same side has IoU p/(2σ2−p)p/(2\sigma^2 - p) with p=(σ−dx)(σ−dy)p = (\sigma - d_x)(\sigma - d_y). On a grid of stride ss the nearest center is at most s/2s/2 away in each axis, and the worst case is dx=dy=s/2d_x = d_y = s/2.
  4. For σ=32\sigma = 32 the worst case of fact 3 gives 576/1472=0.391576/1472 = 0.391 at stride 16 and 900/1148=0.784900/1148 = 0.784 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 (0,0,15,15)(0, 0, 15, 15), widths rounded), the 9 anchors of position (0,0)(0, 0) are (−84,−40,99,55)(-84, -40, 99, 55), (−176,−88,191,103)(-176, -88, 191, 103) and (−360,−184,375,199)(-360, -184, 375, 199) for ratio 1/21/2; (−56,−56,71,71)(-56, -56, 71, 71), (−120,−120,135,135)(-120, -120, 135, 135) and (−248,−248,263,263)(-248, -248, 263, 263) for ratio 11; and (−36,−80,51,95)(-36, -80, 51, 95), (−80,−168,95,183)(-80, -168, 95, 183) and (−168,−344,183,359)(-168, -344, 183, 359) for ratio 22. The wide ones are 184×96184 \times 96, 368×192368 \times 192 and 736×384736 \times 384, so the rounding makes their areas a little larger than 1282128^2, 2562256^2 and 5122512^2. A 60×4060 \times 40 map, from an image of about 1000×6001000 \times 600, has 60⋅40⋅9=2160060 \cdot 40 \cdot 9 = 21600 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 1−IoU⁡1 - \operatorname{IoU}. 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 1282128^2, 2562256^2 and 5122512^2 and three ratios 1:11{:}1, 1:21{:}2 and 2:12{:}1, so k=9k = 9, 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 kk of mm has the scale sk=smin⁡+(smax⁡−smin⁡)(k−1)/(m−1)s_k = s_{\min} + (s_{\max} - s_{\min})(k - 1)/(m - 1) of the image size, with smin⁡=0.2s_{\min} = 0.2 and smax⁡=0.9s_{\max} = 0.9, ratios {1,2,3,1/2,1/3}\{1, 2, 3, 1/2, 1/3\} and one extra square of scale sksk+1\sqrt{s_k s_{k+1}}. SSD300 has 8732 default boxes in all.
  • Feature pyramid network. One anchor size per level, 32232^2 to 5122512^2 on the levels P2P_2 to P6P_6, 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 202^0, 21/32^{1/3} and 22/32^{2/3} times the base size of each pyramid level and three ratios, so 9 anchors per position, from 3232 to about 813813 pixels.
  • YOLOv2. Five anchor shapes per cell of a 13×1313 \times 13 map, found by k-means on the sizes of the training boxes with the distance 1−IoU⁡1 - \operatorname{IoU} 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 1−IoU⁡1 - \operatorname{IoU} 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 oo. One code base centers anchors at (u+0.5)s(u + 0.5)s, another at usus. 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 r=h/wr = h/w and other code takes w/hw/h. With the symmetric set {1/2,1,2}\{1/2, 1, 2\} 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.

anchor_boxes.pyI0RawGitHub
# 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

  1. Show that the shape (σ/r,σr)(\sigma/\sqrt r, \sigma\sqrt r) has area σ2\sigma^2 and ratio h/w=rh/w = r, and count the anchors of SSD300 from the map sizes 38,19,10,5,3,138, 19, 10, 5, 3, 1 with 4, 6, 6, 6, 4 and 4 boxes per position.
  2. Show that two centered boxes of the same area whose ratios differ by a factor qq have IoU 1/(2q−1)1/(2\sqrt q - 1). Which qq gives an IoU of exactly 1/21/2?
  3. 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?
  4. Sizes σ1<σ2<…\sigma_1 < \sigma_2 < \dots are spaced by a factor c>1c > 1. Find the smallest best IoU of a centered square with sizes between σ1\sigma_1 and the largest size, as a function of cc.
  5. Run k-means with the distance 1−IoU⁡1 - \operatorname{IoU} 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 (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) with x1<x2x_1 < x_2 and y1<y2y_1 < y_2, and its area is (x2−x1)(y2−y1)(x_2 - x_1)(y_2 - y_1). For two boxes AA and BB write IoU⁡(A,B)=∣A∩B∣/∣A∪B∣\operatorname{IoU}(A, B) = |A \cap B| / |A \cup B| with ∣A∪B∣=∣A∣+∣B∣−∣A∩B∣|A \cup B| = |A| + |B| - |A \cap B|.

Claim 1 (the grid). ANCHORS returns WfHf∣S∣∣R∣W_f H_f |S| |R| boxes. The box for position (u,v)(u, v) and the shape of size σ\sigma and ratio rr has center ((u+o)s,(v+o)s)((u + o)s, (v + o)s), width σ/r\sigma / \sqrt r, height σr\sigma \sqrt r, area σ2\sigma^2 and ratio h/w=rh / w = r.

Proof. Line L2 appends one shape for each pair (σ,r)(\sigma, r), so BB has ∣S∣∣R∣|S||R| shapes. The loop of line L4 runs once for each of the WfHfW_f H_f positions, and line L6 appends one box for each shape, so the count is WfHf∣S∣∣R∣W_f H_f |S||R|. The box of line L6 has x2−x1=wx_2 - x_1 = w, y2−y1=hy_2 - y_1 = h and the midpoint (cx,cy)(c_x, c_y) of line L5. Its area is (σ/r)(σr)=σ2(\sigma / \sqrt r)(\sigma \sqrt r) = \sigma^2 and its ratio is σr/(σ/r)=r\sigma\sqrt r / (\sigma / \sqrt r) = r. □\square

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 (w1,h1)(w_1, h_1) and (w2,h2)(w_2, h_2) overlap in a box of size min⁡(w1,w2)×min⁡(h1,h2)\min(w_1, w_2) \times \min(h_1, h_2), 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 σ1≤σ2\sigma_1 \le \sigma_2 have IoU (σ1/σ2)2(\sigma_1 / \sigma_2)^2.

Proof. With the same ratio, box 1 has width and height σ1/σ2\sigma_1 / \sigma_2 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 σ12/σ22\sigma_1^2 / \sigma_2^2. □\square

Corollary (octave sizes). Let the square sizes be σ,2σ,4σ,…\sigma, 2\sigma, 4\sigma, \dots and let a centered square have side xx with σ≤x≤2mσ\sigma \le x \le 2^m \sigma. Then its best IoU with the anchors is at least 1/21/2.

Proof. Pick jj with 2jσ≤x≤2j+1σ2^j \sigma \le x \le 2^{j+1} \sigma. By Claim 2 the two anchors give (2jσ/x)2(2^j \sigma / x)^2 and (x/2j+1σ)2(x / 2^{j+1} \sigma)^2. The first falls and the second rises as xx grows, and they are equal at x=2jσ2x = 2^j \sigma \sqrt 2, where both are 1/21/2. So the larger of the two is at least 1/21/2 for every xx in the interval. □\square

Claim 3 (shape error). Two centered boxes of area σ2\sigma^2 with ratios r1≤r2r_1 \le r_2 and q=r2/r1q = r_2 / r_1 have IoU 1/(2q−1)1/(2\sqrt q - 1).

Proof. Box ii has width σ/ri\sigma / \sqrt{r_i} and height σri\sigma \sqrt{r_i}. Since r1≤r2r_1 \le r_2, box 2 is the narrower and box 1 is the shorter, so the intersection has width σ/r2\sigma / \sqrt{r_2} and height σr1\sigma \sqrt{r_1}, and area σ2r1/r2=σ2/q\sigma^2 \sqrt{r_1 / r_2} = \sigma^2 / \sqrt q. The union is 2σ2−σ2/q2\sigma^2 - \sigma^2 / \sqrt q. Dividing, the IoU is (1/q)/(2−1/q)=1/(2q−1)(1/\sqrt q) / (2 - 1/\sqrt q) = 1/(2\sqrt q - 1). □\square

For q=2q = 2 the IoU is 1/(22−1)≈0.5471/(2\sqrt 2 - 1) \approx 0.547, and for q=4q = 4 it is 1/31/3.

Claim 4 (position error). Let GG and AA be squares of side σ\sigma whose centers differ by dxd_x and dyd_y with 0≤dx,dy≤σ0 \le d_x, d_y \le \sigma. Then IoU⁡(G,A)=p/(2σ2−p)\operatorname{IoU}(G, A) = p / (2\sigma^2 - p) with p=(σ−dx)(σ−dy)p = (\sigma - d_x)(\sigma - d_y), and this value does not increase when dxd_x or dyd_y grows.

Proof. Along xx the two intervals have length σ\sigma and start dxd_x apart, so they overlap in a length σ−dx≥0\sigma - d_x \ge 0; the same holds along yy. So ∣G∩A∣=p|G \cap A| = p and ∣G∪A∣=2σ2−p|G \cup A| = 2\sigma^2 - p. The function p↦p/(2σ2−p)p \mapsto p/(2\sigma^2 - p) has derivative 2σ2/(2σ2−p)2>02\sigma^2/(2\sigma^2 - p)^2 > 0 on 0≤p≤σ20 \le p \le \sigma^2, so it grows with pp, and pp does not grow when dxd_x or dyd_y grows. □\square

Corollary (stride). Let the anchors be squares of side σ\sigma centered at the points ((u+o)s,(v+o)s)((u + o)s, (v + o)s) for all integers uu and vv, with s≤2σs \le 2\sigma. Then every square GG of side σ\sigma has an anchor with IoU at least p∗/(2σ2−p∗)p^* / (2\sigma^2 - p^*), p∗=(σ−s/2)2p^* = (\sigma - s/2)^2, and a square centered at ((u+o+1/2)s,(v+o+1/2)s)((u + o + 1/2)s, (v + o + 1/2)s) has no anchor with a higher IoU.

Proof. Rounding the center of GG to the nearest grid point in each axis gives an anchor with dx,dy≤s/2d_x, d_y \le s/2, and Claim 4 gives the bound. For the square at the middle of four grid points, every anchor has dx≥s/2d_x \ge s/2 and dy≥s/2d_y \ge s/2, so by Claim 4 none does better than dx=dy=s/2d_x = d_y = s/2. □\square

For σ=32\sigma = 32 this gives 242/(2048−576)=576/1472≈0.39124^2 / (2048 - 576) = 576/1472 \approx 0.391 at s=16s = 16 and 302/(2048−900)=900/1148≈0.78430^2/(2048 - 900) = 900/1148 \approx 0.784 at s=4s = 4.

On the k-means of YOLOv2. The assignment step puts each box in the cluster with the smallest distance 1−IoU⁡1 - \operatorname{IoU}, 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 1−IoU⁡1 - \operatorname{IoU} 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

  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.1, Anchors (3 scales and 3 aspect ratios, k = 9 anchors at each position, translation invariance, multi-scale anchors as regression references)
  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, 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))
  3. 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)
  4. 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)
  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/JNRSBB/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