Algorithm Search⌘K

Algorithmadvanced

Single shot multibox detector

Also called SSD detector.

Predict class scores and offsets for default boxes on several feature maps of different resolutions in one pass, followed by non-maximum suppression.

Time
O(C D^2) worst
Space
O(C D) extra
Where
C = the number of object classes; D = the number of default boxes
Properties
deterministicnot exactofflineiterative
Origin
Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, Scott Reed, Cheng Yang Fu, Alexander C. Berg, 2016

The single shot multibox detector (SSD) finds objects with one pass of a convolutional network and no proposal stage. It attaches small convolutional predictors to several feature maps of falling resolution, for example 6 maps of 38×3838 \times 38 down to 1×11 \times 1 cells for an input of 300×300300 \times 300. Each cell of each map has a fixed set of default boxes, which are anchor boxes of a few aspect ratios at a scale that grows from map to map. For every default box the network outputs C+1C + 1 class scores, the background included, and four offsets in the encoding of bounding box regression. At test time the offsets are decoded, and non-maximum suppression is applied to each class. SSD300 has 8732 default boxes and reached 74.3 percent mAP on PASCAL VOC 2007 at 59 frames per second. That was as accurate as Faster R-CNN with the same backbone and several times faster.

In plain words

SSD covers the image with many fixed boxes of several sizes and shapes, at every cell of several grids, from fine to coarse. For each box the network says at once what is in it, background included, and how to move and stretch the box to fit the object. No second look at the image is needed. Small objects are found on the fine grids and large objects on the coarse grids. In training, each true object is given the boxes that overlap it well. All other boxes learn to say "background", but only the hardest of them are used, three for each object box, so that the many easy background boxes do not swamp the loss. At test time, near copies of each class are removed.

The problem

The input is an image and a trained network that gives, for every default box dd, a vector of C+1C + 1 class scores and four offsets δd\delta_d. The output is a list of boxes with a class and a score, judged by detection mean average precision. This page gives the steps that are not learned: the default boxes, the decoding and the NMS at test time, and the matching, the hard negative mining and the loss in training. It proves facts about these steps. The network is outside the page.

The algorithm

  1. SSD-DETECT(I, network, τ_conf = 0.01, τ = 0.45, K = 200)
  2. 1for every default box d: class scores z_d and offsets δ_d ← network(I) ▷ outside
  3. 2D ← the default boxes of every cell of every feature map
  4. 3p_d ← SOFTMAX(z_d) for every d ∈ D
  5. 4b_d ← DECODE(d, δ_d) for every d ∈ D
  6. 5for each class c = 1, ..., C
  7. 6greedy NMS at IoU τ of the boxes b_d with p_{d,c} > τ_conf, by score p_{d,c}
  8. 7merge the boxes kept for all classes
  9. 8return the K boxes of highest score

Default boxes. With mm feature maps, map kk has the scale

sk=smin+smax−sminm−1(k−1),smin=0.2, smax=0.9,s_k = s_{min} + \frac{s_{max} - s_{min}}{m - 1}(k - 1), \qquad s_{min} = 0.2,\ s_{max} = 0.9,

as a fraction of the image side. For an aspect ratio aa in {1,2,3,12,13}\{1, 2, 3, \tfrac12, \tfrac13\} the box has width skas_k\sqrt{a} and height sk/as_k/\sqrt{a}. For ratio 1 there is one more box of scale sk′=sksk+1s'_k = \sqrt{s_k s_{k+1}}. The boxes of a map with fk×fkf_k \times f_k cells are centered at ((j+0.5)/fk,(i+0.5)/fk)((j + 0.5)/f_k, (i + 0.5)/f_k). In SSD300, the maps of 382,192,102,52,32,1238^2, 19^2, 10^2, 5^2, 3^2, 1^2 cells have 4, 6, 6, 6, 4 and 4 boxes per cell, which gives 5776+2166+600+150+36+4=87325776 + 2166 + 600 + 150 + 36 + 4 = 8732 boxes. The paper sets the scale of the first map, conv4_3, to 0.1, and does not give sm+1s_{m+1}. The code takes 1 for sm+1s_{m+1} by default.

Matching. Each ground truth box is first matched to the default box of best IoU. Then every other default box whose IoU with some truth is above 0.5 is matched to the truth of best IoU. Matched boxes are positives and the rest are negatives. The code does the first step as a greedy bipartite matching: it takes the pair of largest IoU among the unmatched boxes and truths, again and again. So two truths never share their step-1 box. The anchor assignment page compares this rule with others.

Loss. With NN positives,

L=1N(Lconf+αLloc),α=1,L = \frac{1}{N}\bigl(L_{conf} + \alpha L_{loc}\bigr), \qquad \alpha = 1,

where LconfL_{conf} is the softmax cross-entropy of the positives for their class and of the chosen negatives for background, and LlocL_{loc} is the smooth L1 loss of the positives between the offsets and the encoded truth. L=0L = 0 when N=0N = 0.

Hard negative mining. The negatives are sorted by their background loss, and only the largest ones are kept, so that negatives and positives are at most 3:1.

Example

Take boxes in pixel units, for easy numbers. The ground truth boxes are G1=(0,0,10,10)G_1 = (0, 0, 10, 10) and G2=(20,0,30,10)G_2 = (20, 0, 30, 10). The default boxes are D0=(0,0,10,10)D_0 = (0, 0, 10, 10), D1=(0,0,10,8)D_1 = (0, 0, 10, 8), D2=(0,0,10,4)D_2 = (0, 0, 10, 4), D3=(25,0,35,10)D_3 = (25, 0, 35, 10) and D4=(40,0,50,10)D_4 = (40, 0, 50, 10).

  1. The IoUs with G1G_1 are 1, 0.8, 0.4, 0, 0. With G2G_2, only D3D_3 overlaps, with IoU 50/150=1/350/150 = 1/3.
  2. Step 1 matches D0D_0 to G1G_1 (IoU 1), then D3D_3 to G2G_2 (IoU 1/3). D3D_3 is positive only through this step.
  3. Step 2 matches D1D_1 to G1G_1 (0.8 is above 0.5). D2D_2 (0.4) and D4D_4 (0) are negatives.
  4. So the labels are G1,G1,−,G2,−G_1, G_1, -, G_2, -, with N=3N = 3, and up to 9 negatives are kept, here both.

For the mining alone: with 1 positive and 5 negatives of background loss 0.1, 2.0, 0.5, 1.2 and 0.05, the 3 kept negatives are those with loss 2.0, 1.2 and 0.5.

For the loss, take four default boxes of side 0.5 that tile the unit square, a truth equal to the top left one of class 1, and α=1\alpha = 1. The class probabilities are (1/4,3/4)(1/4, 3/4) for the positive and (1/2,1/2)(1/2, 1/2), (3/4,1/4)(3/4, 1/4) and (1/4,3/4)(1/4, 3/4) for the three negatives, with background first. The positive has offsets (0.5,0,0,0)(0.5, 0, 0, 0) against a target of zero. Then LconfL_{conf} of the positive is −ln⁡(3/4)-\ln(3/4), and Lloc=smooth⁡L1(0.5)=0.125L_{loc} = \operatorname{smooth}_{L_1}(0.5) = 0.125. With a ratio of 1 the only kept negative is the one of loss ln⁡4\ln 4, and L=ln⁡(16/3)+0.125≈1.799L = \ln(16/3) + 0.125 \approx 1.799. With the ratio of 3 all three negatives count, and LL grows by ln⁡2+ln⁡(4/3)\ln 2 + \ln(4/3).

Correctness

The network has no correctness theorem; its accuracy is measured. The proof page shows these facts for the steps that are not learned:

  1. Default boxes. Every box of map kk with ratio aa has area sk2s_k^2 and width over height aa, and the count is ∑kfk2nk\sum_k f_k^2 n_k.
  2. Matching. The boxes of step 1 are distinct. A truth gets no box only when every box that overlaps it went to another truth in step 1. Every box of IoU above 0.5 with some truth is positive, and every negative has IoU at most 0.5 with every truth.
  3. Hard negatives. The kept negatives are the min⁡(3N,n−)\min(3N, n_-) negatives of largest background loss.
  4. Output. At most KK detections, sorted by score, each above τconf\tau_{conf}, with pairwise IoU at most τ\tau inside each class.
Proof: The default boxes have the stated shapes and count, the matching gives each truth its own box when it can and makes every box of IoU above the threshold positive, the mining keeps the hardest negatives, and the output is sorted and suppressed per classfull

The network is learned and outside the claims. The claims are about the steps of the page that are not learned, as the Python code does them. A corner box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) and a default box is (cx,cy,w,h)(c_x, c_y, w, h).

Claim 1 (default boxes). Let map kk have fk×fkf_k \times f_k cells, scale sks_k and ratio list RkR_k. Every box of map kk made from a ratio a∈Rka \in R_k has area sk2s_k^2 and w/h=aw/h = a. The extra box has side sksk+1\sqrt{s_k s_{k+1}}. The number of boxes is ∑kfk2nk\sum_k f_k^2 n_k, with nk=∣Rk∣+[1∈Rk]n_k = |R_k| + [1 \in R_k].

Proof. wh=ska⋅sk/a=sk2w h = s_k\sqrt{a} \cdot s_k/\sqrt{a} = s_k^2 and w/h=aw/h = a. The code makes nkn_k shapes for map kk and places all of them at each of the fk2f_k^2 cell centers. □\square

For SSD300, nk=4,6,6,6,4,4n_k = 4, 6, 6, 6, 4, 4 and the count is 87328732.

Claim 2 (matching). Let m(i)m(i) be the truth of box ii, or −1-1. Then:

  1. the boxes matched in step 1 are distinct, and so are their truths;
  2. a truth gg has no box only if every box with positive IoU with gg was matched in step 1 to another truth;
  3. a box whose best IoU is above the threshold tt is positive;
  4. a negative box has IoU at most tt with every truth;
  5. a matched box has positive IoU with its truth, and a box matched in step 2 has a truth of largest IoU.

Proof. Step 1 removes the chosen box and the chosen truth from the free sets after each pair, so no box or truth is chosen twice. This gives item 1. Step 1 stops when no free truth or no free box is left, or when the largest IoU over the free pairs is 0. Suppose truth gg is still free at the end. Then either no box is free, or every free box has IoU 0 with gg. In both cases, every box with positive IoU with gg is not free, so it was matched in step 1, and to a truth other than gg, since gg is free. This gives item 2. In step 2 every free box ii takes a truth jj of largest IoU, and is matched when that IoU is above tt. A box of best IoU above tt is thus matched in step 1 or in step 2, which gives item 3. A box that stays negative was free in step 2 with best IoU at most tt, which gives item 4. Step 1 only takes pairs of positive IoU, and step 2 only matches IoU above t≥0t \geq 0, which gives item 5. □\square

Item 2 shows when the first rule of the paper, the best box for each truth, can fail. If two truths have the same best box, only one can have it. The greedy step gives the other truth its best free box, as the bipartite matching of MultiBox does.

Claim 3 (hard negatives). With NN positives and n−n_- negatives, the kept negatives are min⁡(3N,n−)\min(3N, n_-) negatives, and no negative that is left out has a larger background loss than a kept one. So negatives and positives are at most 3:1.

Proof. The code sorts the negatives by non-increasing loss, with ties by index, and takes a prefix of that length. An element after the prefix has a loss at most that of every element in it. □\square

Claim 4 (loss). The code returns 1N(Lconf+αLloc)\frac{1}{N}(L_{conf} + \alpha L_{loc}), with LconfL_{conf} the sum of −log⁡pi,c(i)-\log p_{i, c(i)} over the positives and of −log⁡pi,0-\log p_{i,0} over the kept negatives, and LlocL_{loc} the sum of smooth⁡L1\operatorname{smooth}_{L_1} over the four offsets of the positives against the encoded truth. It returns 0 when N=0N = 0.

Proof. This is the code line by line, with the softmax of the scores as pp. □\square

Claim 5 (output). The detection returns at most KK triples (score, class, box), in order of non-increasing score. Each score is above τconf\tau_{conf}, and two boxes of the same class have IoU at most τ\tau.

Proof. For each class, the candidates are the boxes with a probability above τconf\tau_{conf}. Greedy NMS keeps a candidate only if its IoU with every box kept so far for the class is at most τ\tau. The candidates of other classes are never compared, so the statement holds only inside a class. The merged list is sorted by non-increasing score, and its first KK items are returned. A prefix of a list keeps both the order and the pairwise property. □\square

Complexity

The network is outside. With DD default boxes and CC classes, the softmax costs O(DC)O(DC) and the decoding O(D)O(D). Greedy NMS of one class costs O(Dlog⁡D)O(D \log D) to sort and O(D2)O(D^2) to compare in the worst case, so the test-time steps cost O(CD2)O(C D^2), and the final sort O(CDlog⁡(CD))O(CD \log(CD)). Implementations keep only a few hundred boxes of each class before NMS, which caps the quadratic term. In training, the matching costs O(DG)O(DG) for the IoUs of GG truths. The greedy step 1 of the code costs O(DG2)O(D G^2), and the mining costs O(Dlog⁡D)O(D \log D). The extra space is O(CD)O(CD) for the probabilities.

Properties

  • One stage. No proposals and no per-region pooling, so the cost does not grow with the number of objects, apart from NMS.
  • Several maps. Each map handles a range of sizes. The fine maps come early in the network and have weak features, so small objects are the weak point.
  • Translation-equivariant on each map. The same default boxes and predictors are used at every cell.
  • Deterministic at test time; not exact, since it is a learned method.

Variants and improvements

  • DSSD and FPN. A top-down path gives the fine maps stronger features. The feature pyramid network is the most used form.
  • RetinaNet. It replaces hard negative mining with the focal loss, which weights all negatives by how hard they are.
  • SSD512. A larger input and one more map give 76.9 percent mAP on VOC 2007 test.
  • Lighter backbones. MobileNet with SSD heads is a common detector on phones.
  • Anchor-free one-stage detectors. FCOS and CenterNet predict from points rather than default boxes. DETR predicts a set and needs neither defaults nor NMS.

When to use it

Use SSD when one fast pass matters more than the last points of accuracy, and the objects are not mostly tiny. For small objects use a detector with a feature pyramid. For crowded scenes where NMS removes true boxes, consider soft-NMS or a set-based detector.

Pitfalls

  • Box encoding scale. Many implementations divide the center offsets by 0.1 and the log sizes by 0.2. Train and test must use the same scale.
  • Boxes in image fractions. The default boxes are relative to the image, so a non-square image has non-square boxes for ratio 1, unless the image is resized to a square as in the paper.
  • Data augmentation. The paper reports that its sampling of random crops raised mAP by 8.8 points. Without it, SSD is much weaker on small and large objects.
  • The forced matches. Step 1 can make a box of low IoU positive. Without step 1, small truths may have no positive at all.
  • NMS threshold per class. NMS at 0.45 inside each class does not remove a box of a second class at the same place.
  • Negatives swamping the loss. Without mining or a focal loss, the many easy background boxes dominate LconfL_{conf}.

Implementations

The network is outside this page. The Python code takes the class scores and offsets of every default box as inputs, and the tests build them by hand or with a fixed seed. The code implements the scales and the default boxes, the encoding with optional scales of the offsets, the two-step matching, hard negative mining, the loss, and the detection of lines L1 to L8. The tests check the 8732 boxes of SSD300 and the shapes of the boxes, the matching example above and a case where step 1 gives a second truth its own box, the matching rule on random boxes, the mining and loss examples, the round trip of encoding and decoding, the properties of the output on random scores, and a run that recovers a known box.

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.

single_shot_multibox_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-shot-multibox-detector/. The authors are listed in prov/TNJGM1.jsonl.
"""SSD around given network outputs.

The convolutional network is not part of this file. The caller passes, for
each default box, a list of C + 1 class scores (logits, background first) and
four offsets. The tests build them by hand or with a fixed seed. This file has
the parts that are not learned: the default boxes, the matching of default
boxes to ground truth boxes, hard negative mining, the training loss, and the
test-time decoding with non-maximum suppression (NMS) for each class.

Default boxes are (cx, cy, w, h) in coordinates relative to the image, so the
image is the unit square. Corner boxes are (x1, y1, x2, y2). Standard library only.
"""

import math
from fractions import Fraction


def ssd_scales(m, s_min=0.2, s_max=0.9):
    """The scales s_1, ..., s_m spaced evenly from s_min to s_max (m >= 2)."""
    return [s_min + (s_max - s_min) * k / (m - 1) for k in range(m)]


def default_boxes(fmap_sizes, ratios, s_min=0.2, s_max=0.9, scales=None, s_last=1.0):
    """Default boxes for square feature maps of the given sizes.

    ratios[k] is the list of aspect ratios (width / height) of map k. When 1 is
    in the list, one more box of scale sqrt(s_k s_{k+1}) and ratio 1 is added,
    with s_{m+1} = s_last. The order is map, row, column, then the shapes."""
    m = len(fmap_sizes)
    s = list(scales) if scales is not None else ssd_scales(m, s_min, s_max)
    s.append(s_last)
    out = []
    for k, f in enumerate(fmap_sizes):
        shapes = [(s[k] * math.sqrt(a), s[k] / math.sqrt(a)) for a in ratios[k]]
        if 1 in ratios[k]:
            e = math.sqrt(s[k] * s[k + 1])
            shapes.append((e, e))
        for i in range(f):
            for j in range(f):
                cx, cy = (j + 0.5) / f, (i + 0.5) / f
                for w, h in shapes:
                    out.append((cx, cy, w, h))
    return out


def corners(d):
    return (d[0] - d[2] / 2, d[1] - d[3] / 2, d[0] + d[2] / 2, d[1] + d[3] / 2)


def iou(a, b):
    """Intersection over union of corner boxes; exact Fractions on integer boxes."""
    iw = min(a[2], b[2]) - max(a[0], b[0])
    ih = min(a[3], b[3]) - max(a[1], b[1])
    if iw <= 0 or ih <= 0:
        return 0
    inter = iw * ih
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    if isinstance(inter, int) and isinstance(union, int):
        return Fraction(inter, union)
    return inter / union


def encode(d, g, var=(1.0, 1.0)):
    """Offsets of corner box g from default box d = (cx, cy, w, h)."""
    gw, gh = g[2] - g[0], g[3] - g[1]
    gx, gy = (g[0] + g[2]) / 2, (g[1] + g[3]) / 2
    return ((gx - d[0]) / d[2] / var[0], (gy - d[1]) / d[3] / var[0],
            math.log(gw / d[2]) / var[1], math.log(gh / d[3]) / var[1])


def decode(d, t, var=(1.0, 1.0)):
    """The corner box given by offsets t from default box d = (cx, cy, w, h)."""
    cx, cy = d[0] + t[0] * var[0] * d[2], d[1] + t[1] * var[0] * d[3]
    w, h = d[2] * math.exp(t[2] * var[1]), d[3] * math.exp(t[3] * var[1])
    return (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)


def match(boxes, gts, thr=0.5):
    """The SSD matching. boxes are corner boxes. Returns, for each box, the index
    of its ground truth box or -1 for a negative.

    Step 1 (bipartite): repeatedly take the pair (box, truth) of largest positive
    IoU among the boxes and truths not matched yet, and match it, so each truth
    gets its own box. Step 2: every other box whose best IoU is above thr is
    matched to a truth of largest IoU. Ties go to the lower index."""
    res = [-1] * len(boxes)
    if not gts:
        return res
    ious = [[iou(b, g) for g in gts] for b in boxes]
    free_b, free_g = set(range(len(boxes))), set(range(len(gts)))
    while free_g and free_b:
        best, bi, gj = 0, -1, -1
        for j in sorted(free_g):
            for i in sorted(free_b):
                if ious[i][j] > best:
                    best, bi, gj = ious[i][j], i, j
        if best <= 0:
            break
        res[bi] = gj
        free_b.discard(bi)
        free_g.discard(gj)
    for i in free_b:
        j = max(range(len(gts)), key=lambda k: (ious[i][k], -k))
        if ious[i][j] > thr:
            res[i] = j
    return res


def hard_negatives(neg_losses, num_pos, ratio=3):
    """Indices into neg_losses of the min(ratio * num_pos, len) largest losses,
    ties by index, in that order."""
    order = sorted(range(len(neg_losses)), key=lambda i: (-neg_losses[i], i))
    return order[:min(ratio * num_pos, len(neg_losses))]


def softmax(z):
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    return [v / s for v in e]


def smooth_l1(x):
    return 0.5 * x * x if abs(x) < 1 else abs(x) - 0.5


def ssd_loss(defaults, logits, locs, gts, labels, alpha=1.0, thr=0.5, ratio=3, var=(1.0, 1.0)):
    """The SSD training loss (L_conf + alpha L_loc) / N on given network outputs.

    labels[j] in 1..C is the class of truth j; class 0 is the background. N is the
    number of matched default boxes, and the loss is 0 when N = 0."""
    m = match([corners(d) for d in defaults], gts, thr)
    pos = [i for i, j in enumerate(m) if j >= 0]
    if not pos:
        return 0.0
    neg = [i for i, j in enumerate(m) if j < 0]
    bg_loss = [-math.log(softmax(logits[i])[0]) for i in neg]
    chosen = [neg[k] for k in hard_negatives(bg_loss, len(pos), ratio)]
    conf = -sum(math.log(softmax(logits[i])[labels[m[i]]]) for i in pos)
    conf += -sum(math.log(softmax(logits[i])[0]) for i in chosen)
    loc = sum(smooth_l1(a - b) for i in pos
              for a, b in zip(locs[i], encode(defaults[i], gts[m[i]], var)))
    return (conf + alpha * loc) / len(pos)


def greedy_nms(boxes, scores, thr):
    order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
    keep = []
    for i in order:
        if all(iou(boxes[i], boxes[k]) <= thr for k in keep):
            keep.append(i)
    return keep


def detect(defaults, logits, locs, conf_thr=0.01, nms_thr=0.45, top_k=200, var=(1.0, 1.0)):
    """Test-time SSD on given network outputs. Returns a list of
    (score, class, corner box), best first, at most top_k long."""
    # logits and locs are the outputs of the network for every default box.
    assert len(defaults) == len(logits) == len(locs)  # @line L1
    num = len(defaults)  # @line L2
    probs = [softmax(z) for z in logits]  # @line L3
    boxes = [decode(defaults[i], locs[i], var) for i in range(num)]  # @line L4
    dets = []
    for c in range(1, len(logits[0]) if logits else 1):  # @line L5
        cand = [i for i in range(num) if probs[i][c] > conf_thr]
        keep = greedy_nms([boxes[i] for i in cand], [probs[i][c] for i in cand], nms_thr)  # @line L6
        dets.extend((probs[cand[k]][c], c, boxes[cand[k]]) for k in keep)  # @line L7
    dets.sort(key=lambda d: (-d[0], d[1]))
    return dets[:top_k]  # @line L8
test_single_shot_multibox_detector.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-shot-multibox-detector/. The authors are listed in prov/TNJGM1.jsonl.

import math
import random

from single_shot_multibox_detector import (
    corners,
    decode,
    default_boxes,
    detect,
    encode,
    hard_negatives,
    iou,
    match,
    ssd_loss,
    ssd_scales,
)

SSD300_MAPS = [38, 19, 10, 5, 3, 1]
SSD300_RATIOS = [[1, 2, 0.5]] + [[1, 2, 3, 0.5, 1 / 3]] * 3 + [[1, 2, 0.5]] * 2


def test_scales_and_box_count():
    s = ssd_scales(6)
    assert all(abs(a - b) < 1e-12 for a, b in zip(s, [0.2, 0.34, 0.48, 0.62, 0.76, 0.9]))
    d = default_boxes(SSD300_MAPS, SSD300_RATIOS)
    assert len(d) == 38 * 38 * 4 + 19 * 19 * 6 + 10 * 10 * 6 + 5 * 5 * 6 + 3 * 3 * 4 + 4 == 8732


def test_default_box_shapes():
    s = ssd_scales(3)
    d = default_boxes([4, 2, 1], [[1, 2, 0.5], [1, 3], [2]])
    assert len(d) == 16 * 4 + 4 * 3 + 1
    first = d[:4]
    assert all(abs(b[0] - 0.125) < 1e-12 and abs(b[1] - 0.125) < 1e-12 for b in first)
    for (_, _, w, h), a in zip(first[:3], [1, 2, 0.5]):
        assert abs(w * h - s[0] ** 2) < 1e-12 and abs(w / h - a) < 1e-12
    assert abs(first[3][2] - math.sqrt(s[0] * s[1])) < 1e-12
    # The single box of the last map has ratio 2 and no extra box.
    cx, cy, w, h = d[-1]
    assert (cx, cy) == (0.5, 0.5) and abs(w * h - s[2] ** 2) < 1e-12 and abs(w / h - 2) < 1e-12
    for b in d:
        assert 0 < b[0] < 1 and 0 < b[1] < 1


def test_page_example_matching():
    gts = [(0, 0, 10, 10), (20, 0, 30, 10)]
    boxes = [(0, 0, 10, 10), (0, 0, 10, 8), (0, 0, 10, 4), (25, 0, 35, 10), (40, 0, 50, 10)]
    assert match(boxes, gts) == [0, 0, -1, 1, -1]
    # Two truths that prefer the same box: the second gets its own box in step 1.
    gts = [(0, 0, 10, 10), (0, 0, 10, 9)]
    boxes = [(0, 0, 10, 10), (0, 0, 10, 4)]
    assert match(boxes, gts) == [0, 1]
    assert match(boxes, []) == [-1, -1]


def test_matching_properties():
    rng = random.Random(3)

    def rbox():
        x, y = rng.randint(0, 20), rng.randint(0, 20)
        return (x, y, x + rng.randint(2, 12), y + rng.randint(2, 12))

    for _ in range(150):
        boxes = [rbox() for _ in range(rng.randint(1, 12))]
        gts = [rbox() for _ in range(rng.randint(1, 4))]
        m = match(boxes, gts)
        for i, b in enumerate(boxes):
            best = max(iou(b, g) for g in gts)
            if best > 0.5:
                assert m[i] >= 0
            if m[i] >= 0:
                assert iou(b, gts[m[i]]) > 0
            else:
                assert best <= 0.5
        for j, g in enumerate(gts):
            if j not in m:
                # Every box that overlaps g was given to another truth in step 1.
                assert all(m[i] >= 0 for i, b in enumerate(boxes) if iou(b, g) > 0)


def test_hard_negatives():
    losses = [0.1, 2.0, 0.5, 1.2, 0.05]
    assert hard_negatives(losses, 1) == [1, 3, 2]
    assert hard_negatives(losses, 2) == [1, 3, 2, 0, 4]
    assert hard_negatives(losses, 0) == []
    assert hard_negatives([1.0, 1.0, 1.0], 1, ratio=2) == [0, 1]


def test_page_example_loss():
    defaults = [(0.25, 0.25, 0.5, 0.5), (0.75, 0.25, 0.5, 0.5), (0.25, 0.75, 0.5, 0.5),
                (0.75, 0.75, 0.5, 0.5)]
    gts = [(0.0, 0.0, 0.5, 0.5)]
    l3 = math.log(3)
    logits = [[0.0, l3], [0.0, 0.0], [l3, 0.0], [0.0, l3]]
    locs = [(0.5, 0.0, 0.0, 0.0), (0.0,) * 4, (0.0,) * 4, (0.0,) * 4]
    want = -math.log(3 / 4) + math.log(4) + 0.125
    assert abs(ssd_loss(defaults, logits, locs, gts, [1], ratio=1) - want) < 1e-12
    want += math.log(2) + math.log(4 / 3)
    assert abs(ssd_loss(defaults, logits, locs, gts, [1]) - want) < 1e-12
    assert ssd_loss(defaults, logits, locs, [], []) == 0.0


def test_encode_decode_round_trip():
    rng = random.Random(4)
    for _ in range(50):
        d = (rng.random(), rng.random(), rng.uniform(0.05, 0.5), rng.uniform(0.05, 0.5))
        x, y = rng.random(), rng.random()
        g = (x, y, x + rng.uniform(0.01, 0.6), y + rng.uniform(0.01, 0.6))
        for var in [(1.0, 1.0), (0.1, 0.2)]:
            assert all(abs(a - b) < 1e-9 for a, b in zip(decode(d, encode(d, g, var), var), g))


def test_detect_properties_on_random_outputs():
    rng = random.Random(5)
    defaults = default_boxes([4, 2, 1], [[1, 2, 0.5], [1, 3], [1]])
    for _ in range(4):
        logits = [[rng.gauss(0, 2) for _ in range(4)] for _ in defaults]
        locs = [tuple(rng.gauss(0, 0.2) for _ in range(4)) for _ in defaults]
        out = detect(defaults, logits, locs, conf_thr=0.2, top_k=15)
        assert len(out) <= 15
        assert [s for s, _, _ in out] == sorted((s for s, _, _ in out), reverse=True)
        assert all(s > 0.2 for s, _, _ in out)
        for a in range(len(out)):
            for b in range(a):
                if out[a][1] == out[b][1]:
                    assert iou(out[a][2], out[b][2]) <= 0.45


def test_detect_recovers_a_box():
    truth = (0.3, 0.2, 0.7, 0.9)
    defaults = default_boxes([4, 2], [[1, 2, 0.5], [1, 0.5]])
    logits, locs = [], []
    for d in defaults:
        o = float(iou(corners(d), truth))
        logits.append([0.0, -2.0, 8.0 * o])
        locs.append(encode(d, truth) if o > 0.3 else (0.0,) * 4)
    out = detect(defaults, logits, locs)
    s, c, b = out[0]
    assert c == 2 and all(abs(x - y) < 1e-9 for x, y in zip(b, truth))
    assert all(iou(bb, truth) <= 0.45 for _, cc, bb in out[1:] if cc == 2)

History

MultiBox (Erhan, Szegedy, Toshev and Anguelov 2014) predicted class-agnostic boxes from priors with a network, and Faster R-CNN (2015) put anchors on one feature map. YOLO (2016) made detection one pass but predicted from a coarse grid with a few boxes per cell. Liu, Anguelov, Erhan, Szegedy, Reed, Fu and Berg put SSD on arXiv in December 2015 and presented it at ECCV 2016. They combined default boxes of several shapes on several feature maps with the matching of MultiBox and hard negative mining. SSD300 reached 74.3 percent mAP at 59 frames per second on VOC 2007 test, which made real-time detection at the accuracy of two-stage methods practical. Its multi-scale prediction led to the feature pyramid network and RetinaNet.

References

  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, LNCS 9905, 21-37, Section 2.1, Model (multi-scale feature maps, convolutional predictors, default boxes); Section 2.2, Training (matching strategy with jaccard overlap above 0.5 and the best box for each truth, training objective with alpha = 1, scales s_min = 0.2 and s_max = 0.9 with ratios 1, 2, 3, 1/2, 1/3 and an extra box of scale sqrt(s_k s_k+1), hard negative mining at 3:1, data augmentation); Section 3, Experimental results (8732 boxes for SSD300; inference with confidence 0.01, NMS at 0.45 per class and the top 200 detections; SSD300 74.3 mAP at 59 FPS and SSD512 76.9 mAP on VOC 2007 test)
  2. Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, Scott Reed, Cheng-Yang Fu and Alexander C. Berg, SSD: single shot multibox detector, arXiv 1512.02325, the extended version, with the same Sections 2 and 3
  3. 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 (the anchors on one feature map that SSD extends to several maps)
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example