Algorithm Search⌘K

Algorithmadvanced

YOLO

Also called you only look once.

Detect objects in one pass by having each cell of a grid over the image predict box coordinates, objectness and class scores directly.

Time
O(C S^4 B^2) worst
Space
O(S^2 B C) extra
Where
B = the number of boxes per cell; C = the number of classes; S = the side of the grid in cells
Properties
deterministicnot exactofflineiterative
Origin
Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi, 2016

YOLO, short for "you only look once", treats detection as one regression problem. The image is resized and passed once through a convolutional network. The network divides it into an S×SS \times S grid. Each cell predicts BB boxes and CC class probabilities. For each box, the cell gives a center offset inside the cell, a width and height relative to the image, and a confidence. The paper uses S=7S = 7, B=2B = 2 and C=20C = 20 for PASCAL VOC, so the output is a 7×7×307 \times 7 \times 30 tensor and an image gives 98 boxes. At test time the score of a box for a class is the class probability of its cell times the box confidence. Low scores are dropped, and non-maximum suppression is applied to each class. YOLO ran at 45 frames per second with 63.4 percent mAP on VOC 2007, and the smaller Fast YOLO ran at 155 frames per second. Later versions, starting with YOLO9000, predict offsets from anchor boxes whose shapes are found by k-means.

In plain words

YOLO lays a grid over the image. The cell that holds the center of an object is in charge of that object. Each cell guesses a few boxes, says how sure it is that each box holds an object, and says which class the object of the cell is. All of this comes out of one pass of the network, so it is fast. To get the final list, each box's sureness is multiplied by the class guess of its cell. Weak boxes are removed, and near copies of the same class are removed too. Because each cell names only one class and holds few boxes, YOLO version 1 misses groups of small objects, such as a flock of birds.

The problem

The input is an image and a trained network that gives the S×S×(5B+C)S \times S \times (5B + C) tensor. 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 decoding, the class-specific scores and the NMS at test time, and the training loss of version 1 with its rule for the predictor in charge. It also gives the anchor decoding and the shape clusters of version 2, and proves facts about these steps. The network is outside.

The algorithm

  1. YOLO-DETECT(I, network, S, B, C, τ_score, τ)
  2. 1T ← network(I), a tensor of S × S × (5B + C) ▷ outside
  3. 2for each cell (i, j) and box k: b ← ((j + x)/S · W, (i + y)/S · H, w · W, h · H) as center and size
  4. 3score_c(b) ← Pr(class c | cell) · confidence(b) for c = 1, ..., C
  5. 4for each class c
  6. 5candidates ← the boxes with score_c > τ_score
  7. 6greedy NMS at IoU τ of the candidates by score_c
  8. 7add the kept boxes, with class c, to the output
  9. 8return the output sorted by score

Confidence. In training, the confidence target of a box is Pr⁡(object)⋅IoU\Pr(\text{object}) \cdot \text{IoU} with the truth. So the score of line L3 is Pr⁡(classc∣object)⋅Pr⁡(object)⋅IoU\Pr(\text{class}_c \mid \text{object}) \cdot \Pr(\text{object}) \cdot \text{IoU}. It holds both the class and how well the box fits.

Loss. The cell that holds the center of a truth box is responsible for it. Inside that cell, the one of the BB predictors whose box has the largest IoU with the truth is the responsible predictor. Let 1ijobj\mathbb{1}^{obj}_{ij} mark the responsible predictor jj of cell ii, let 1ijnoobj\mathbb{1}^{noobj}_{ij} mark all the others, and let 1iobj\mathbb{1}^{obj}_i mark the cells with an object. Then the loss is

L=λcoord∑i,j1ijobj[(x−x^)2+(y−y^)2+(w−w^)2+(h−h^)2]+∑i,j1ijobj(c−c^)2+λnoobj∑i,j1ijnoobj c2+∑i1iobj∑k(pk−p^k)2,\begin{aligned} L = {} & \lambda_{coord} \sum_{i,j} \mathbb{1}^{obj}_{ij}\bigl[(x - \hat x)^2 + (y - \hat y)^2 + (\sqrt{w} - \sqrt{\hat w})^2 + (\sqrt{h} - \sqrt{\hat h})^2\bigr] \\ & + \sum_{i,j} \mathbb{1}^{obj}_{ij}(c - \hat c)^2 + \lambda_{noobj} \sum_{i,j} \mathbb{1}^{noobj}_{ij}\, c^2 + \sum_i \mathbb{1}^{obj}_i \sum_{k} (p_k - \hat p_k)^2, \end{aligned}

with λcoord=5\lambda_{coord} = 5 and λnoobj=0.5\lambda_{noobj} = 0.5. The hatted values are the targets, c^\hat c is the IoU of the predicted box with the truth, and p^\hat p is the one-hot class. The square roots make an error of a few pixels cost more on a small box than on a large one. The class term counts once per cell, not once per box.

Version 2 decoding. YOLO9000 predicts tx,ty,tw,th,tot_x, t_y, t_w, t_h, t_o for each of kk anchors at a cell with corner (cx,cy)(c_x, c_y) in grid units:

bx=σ(tx)+cx,by=σ(ty)+cy,bw=pwetw,bh=pheth,Pr⁡(object)⋅IoU=σ(to).b_x = \sigma(t_x) + c_x, \quad b_y = \sigma(t_y) + c_y, \quad b_w = p_w e^{t_w}, \quad b_h = p_h e^{t_h}, \quad \Pr(\text{object}) \cdot \text{IoU} = \sigma(t_o).

The sigmoid keeps the center inside the cell, which made training more stable than the free offsets of bounding box regression. The prior shapes (pw,ph)(p_w, p_h) are k=5k = 5 centers of k-means on the training boxes, with the distance d=1−IoUd = 1 - \text{IoU} between two shapes placed at the same center. With a Euclidean distance, large boxes would give larger errors than small ones.

Example

Take S=2S = 2, B=1B = 1, C=2C = 2, an image of 100×100100 \times 100 pixels, τscore=0.2\tau_{score} = 0.2 and τ=0.5\tau = 0.5. The cells give (x,y,w,h,conf,p0,p1)(x, y, w, h, \text{conf}, p_0, p_1):

cell output box scores
(0, 0) 0.8, 0.8, 0.6, 0.6, 0.9, 0.8, 0.2 (10, 10, 70, 70) 0.72, 0.18
(0, 1) 0.3, 0.5, 0.4, 0.4, 0.6, 0.1, 0.9 (45, 5, 85, 45) 0.06, 0.54
(1, 0) 0.8, 0.0, 0.6, 0.6, 0.6, 0.6, 0.4 (10, 20, 70, 80) 0.36, 0.24
(1, 1) 0.5, 0.5, 0.2, 0.2, 0.1, 0.5, 0.5 (70, 70, 90, 90) 0.05, 0.05

For cell (1, 0), the center is ((0+0.8)/2⋅100,(1+0)/2⋅100)=(40,50)((0 + 0.8)/2 \cdot 100, (1 + 0)/2 \cdot 100) = (40, 50) and the size is 60, which gives the box (10,20,70,80)(10, 20, 70, 80).

  1. Class 0 keeps the scores above 0.2: 0.72 and 0.36. Their boxes overlap with IoU 3000/4200=5/7>0.53000/4200 = 5/7 > 0.5, so NMS removes the second one. The same object is seen from two cells.
  2. Class 1 keeps 0.54 and 0.24. Their boxes have IoU 625/4575≈0.14625/4575 \approx 0.14, so both stay.
  3. The output is (0.72,0)(0.72, 0), (0.54,1)(0.54, 1) and (0.24,1)(0.24, 1), with the boxes above. The last one is the object of class 0 again, now under class 1, since NMS for each class does not compare across classes.

For the loss, take S=1S = 1, B=2B = 2, C=2C = 2, the truth (20,20,80,80)(20, 20, 80, 80) of class 1, and the outputs (0.6,0.5,0.6,0.6,0.7)(0.6, 0.5, 0.6, 0.6, 0.7) and (0.5,0.5,0.2,0.2,0.4)(0.5, 0.5, 0.2, 0.2, 0.4) with class probabilities (0.3,0.7)(0.3, 0.7). The boxes are (30,20,90,80)(30, 20, 90, 80) with IoU 5/75/7 and (40,40,60,60)(40, 40, 60, 60) with IoU 1/91/9, so the first predictor is responsible. Then L=5⋅0.12+(0.7−5/7)2+0.5⋅0.42+0.32+0.32≈0.3102L = 5 \cdot 0.1^2 + (0.7 - 5/7)^2 + 0.5 \cdot 0.4^2 + 0.3^2 + 0.3^2 \approx 0.3102.

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. Decoding. For 0≤x,y≤10 \le x, y \le 1 the center of a box lies in its cell. The version 2 center always lies in its cell, for any tt.
  2. Output. It is sorted by score, every score is above τscore\tau_{score}, and two boxes of one class have IoU at most τ\tau.
  3. Loss. The loss is zero exactly when the responsible predictors give the targets, all other confidences are zero, and the class vectors of the object cells are one-hot on the truth. For a fixed error in ww, the term falls as the box grows.
  4. Clusters. When the clustering converges, each shape is given to a center of largest IoU, and each center is the mean of its shapes.
Proof: The decoded centers lie in their cells, the output is sorted and suppressed per class, the version 1 loss vanishes exactly on the targets and weights small boxes more, and the converged clustering assigns each shape to a center of largest IoUfull

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 box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in pixels on an image of W×HW \times H, and the grid has S×SS \times S cells.

Claim 1 (decoding). In version 1, a box of cell (i,j)(i, j) with 0≤x,y≤10 \le x, y \le 1 has its center in [jW/S,(j+1)W/S]×[iH/S,(i+1)H/S][jW/S, (j+1)W/S] \times [iH/S, (i+1)H/S], the cell. In version 2, the center (σ(tx)+cx,σ(ty)+cy)(\sigma(t_x) + c_x, \sigma(t_y) + c_y) lies in the open cell (cx,cx+1)×(cy,cy+1)(c_x, c_x + 1) \times (c_y, c_y + 1) for every real tt, and the objectness σ(to)\sigma(t_o) lies in (0,1)(0, 1).

Proof. The version 1 center is ((j+x)W/S,(i+y)H/S)((j + x)W/S, (i + y)H/S), and j≤j+x≤j+1j \le j + x \le j + 1. The sigmoid takes values in (0,1)(0, 1). □\square

In floating point the sigmoid can round to 0 or 1 for large ∣t∣|t|, so the test allows the closed cell.

Claim 2 (output). The detection returns a list in order of non-increasing score. Every score is above τscore\tau_{score}, and two boxes of the same class have IoU at most τ\tau.

Proof. For a class cc, line L5 keeps only the boxes with score above τscore\tau_{score}. Greedy NMS visits them by non-increasing score and keeps a box only if its IoU with every box kept so far for cc is at most τ\tau. Any two kept boxes of cc were compared when the later one was kept. The merged list is then sorted by score. Boxes of different classes are never compared. □\square

Claim 3 (loss). Let each cell hold at most one truth center, and let all widths and heights be non-negative. In a truth cell, let rr be the responsible predictor of the code: the first predictor of largest IoU with the truth. The version 1 loss of the code is non-negative. It is zero if and only if all of the following hold:

  1. in each truth cell, rr gives the target x,y,w,hx, y, w, h and confidence 1;
  2. every other predictor in the grid has confidence 0;
  3. the class vector of each truth cell is one-hot on its class.

Proof. Every term is a square times a positive weight, so the loss is non-negative, and it is zero exactly when every term is zero. The no-object terms are zero exactly when item 2 holds, and the class terms are zero exactly when item 3 holds. It is left to show that the terms of rr are zero exactly when item 1 holds. If item 1 holds, the box of rr is the truth, its IoU is 1, and the confidence term is (1−1)2=0(1 - 1)^2 = 0, as are the coordinate terms. Conversely, if the coordinate terms of rr are zero, then xx and yy equal the targets and w,h\sqrt{w}, \sqrt{h} equal the square roots of the targets, so ww and hh equal the targets. Then the box of rr is the truth, its IoU is 1, and a zero confidence term gives confidence 1. □\square

The test builds outputs of this kind. It puts the truth values at a random predictor index and sets all other values to zero. A predictor with all values zero has an empty box of IoU 0, so the predictor with the truth values is rr.

Claim 4 (small boxes). For a fixed error δ>0\delta > 0 in the width, the term (w+δ−w)2(\sqrt{w + \delta} - \sqrt{w})^2 falls as ww grows.

Proof. w+δ−w=δ/(w+δ+w)\sqrt{w + \delta} - \sqrt{w} = \delta / (\sqrt{w + \delta} + \sqrt{w}), which is positive and falls as ww grows, so its square falls too. □\square

So an error of 0.050.05 in ww costs more on a box of width 0.10.1 than on a box of width 0.80.8. With a plain square, the costs would be the same.

Claim 5 (clusters). If the clustering ends because the assignment did not change, then each shape is assigned to a center of largest IoU with it, with ties to the lower index. Also, each center that has shapes is the mean of its shapes.

Proof. In each round, the code first assigns every shape to the index of largest IoU with the current centers. If this assignment equals the one of the round before, the loop stops before it moves the centers. The current centers were computed as the means of that same assignment. So the assignment is the best one for the final centers, and the centers are its means. □\square

If the loop ends at the iteration limit, the last step moved the centers, and the assignment may not match them. The test uses data that converges well before the limit. The mean does not minimize ∑(1−IoU)\sum (1 - \text{IoU}) in a cluster, unlike the squared Euclidean case. So there is no proof that the cost falls at each round, and the method is a heuristic, as in YOLO9000.

Complexity

The network is outside. Decoding and scoring the S2BS^2 B boxes for CC classes costs O(S2BC)O(S^2 B C). Greedy NMS of one class costs O((S2B)2)O((S^2 B)^2) in the worst case, so the test-time steps cost O(CS4B2)O(C S^4 B^2). For S=7S = 7 and B=2B = 2 this is at most 98 boxes per class, so the cost after the network is small. The loss costs O(S2(B+C)+G)O(S^2 (B + C) + G) for GG truths. One round of the shape clustering costs O(nk)O(nk) for nn shapes and kk centers.

Properties

  • One pass and global context. The network sees the whole image when it predicts each box. The paper reports fewer background false positives than Fast R-CNN, but more localization errors.
  • Spatial limits. In version 1, one class per cell and BB boxes per cell limit how many nearby objects can be found. Two objects whose centers fall in one cell compete for it.
  • Coarse grid. The 7×77 \times 7 grid and the fully connected output make the boxes coarse. Version 2 moved to a fully convolutional 13×1313 \times 13 map with anchors.
  • Deterministic at test time; not exact, since it is a learned method.

Variants and improvements

  • YOLO9000 (YOLOv2). Batch normalization, a classifier trained at higher resolution, anchors from dimension clusters, the sigmoid offsets above, and training at several input sizes. At input 416 it reached 76.8 percent mAP at 67 frames per second on VOC 2007. Anchors raised recall from 81 to 88 percent.
  • YOLOv3. Predictions at 3 scales with 9 clusters, in the spirit of the feature pyramid network, and a separate logistic classifier for each class.
  • Later versions. Many later detectors carry the name, with other authors. They add stronger backbones, mosaic data augmentation, anchor-free heads and, in some, training without NMS.
  • Other one-stage detectors. SSD predicts from default boxes on several maps. RetinaNet uses the focal loss. DETR predicts a set with no grid and no NMS.

When to use it

Use a YOLO-style detector when speed is the first need, as in video or on small devices, and the objects are not mostly tiny and crowded. Version 1 is mainly of teaching value. For accuracy on small objects, use a detector with a feature pyramid.

Pitfalls

  • Objects that share a cell. Two centers in one cell give one object to that cell in version 1. Groups of small objects are the known weak point.
  • Wrong axes. The tensor is indexed by row and column, but xx goes with the column. Swapping them moves every box.
  • Negative widths. A raw output for ww can be negative, and its square root is undefined. Clamp it, or predict w\sqrt{w} directly.
  • NMS for each class only. As in the example, the same object can come out under two classes.
  • Score threshold. The paper does not fix the threshold for the class-specific scores. Too high loses recall, too low gives many false positives.
  • Euclidean k-means on shapes. Plain k-means on (w,h)(w, h) favours large boxes. Use 1−IoU1 - \text{IoU} as the distance.

Implementations

The network is outside this page. The Python code takes the output tensor as input, and the tests build it by hand or with a fixed seed. The code implements the decoding and detection of lines L1 to L8, the version 1 loss with the responsible predictor, the version 2 decoding with anchors, and k-means on shapes with the distance 1−IoU1 - \text{IoU}. The tests check the example above, the properties of the output on random tensors, the loss example, a zero loss on perfect outputs, the larger weight of an error on a small box, the version 2 center that stays in its cell, and the clusters on three groups of shapes.

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.

yolo_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yolo-detector/. The authors are listed in prov/D6VPA6.jsonl.
"""YOLO (version 1, with the box decoding and anchor clusters of version 2)
around given network outputs.

The convolutional network is not part of this file. The caller passes the
output tensor as out[i][j], the list of B * 5 + C numbers of grid cell (row i,
column j): for each of the B boxes x, y, w, h and a confidence, then C class
probabilities. The tests build it by hand or with a fixed seed. This file has
the parts that are not learned: the decoding of the tensor, the class-specific
scores and the NMS for each class at test time, the version 1 training loss,
the version 2 decoding of offsets against anchors, and the k-means clustering
of box shapes with the distance 1 - IoU.

Boxes are (x1, y1, x2, y2) in pixels. Standard library only.
"""

import math
import random
from fractions import Fraction


def iou(a, b):
    """Intersection over union; 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 cell_box(i, j, x, y, w, h, s, img_w, img_h):
    """Version 1 decoding: x and y are offsets inside cell (i, j), and w and h
    are fractions of the image size."""
    cx, cy = (j + x) / s * img_w, (i + y) / s * img_h
    bw, bh = w * img_w, h * img_h
    return (cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2)


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(out, s, b, c, img_w, img_h, score_thr=0.2, nms_thr=0.5):
    """Test-time YOLO v1. Returns a list of (score, class, box), best first."""
    # out is the S x S x (5B + C) output of the network.
    assert len(out) == s and all(len(row) == s and all(len(v) == 5 * b + c for v in row)
                                 for row in out)  # @line L1
    boxes, scores = [], []
    for i in range(s):
        for j in range(s):
            v = out[i][j]
            probs = v[5 * b:]
            for k in range(b):
                x, y, w, h, conf = v[5 * k:5 * k + 5]
                boxes.append(cell_box(i, j, x, y, max(w, 0.0), max(h, 0.0), s, img_w, img_h))  # @line L2
                scores.append([p * conf for p in probs])  # @line L3
    dets = []
    for cl in range(c):  # @line L4
        cand = [n for n in range(len(boxes)) if scores[n][cl] > score_thr]  # @line L5
        keep = greedy_nms([boxes[n] for n in cand], [scores[n][cl] for n in cand], nms_thr)  # @line L6
        dets.extend((scores[cand[k]][cl], cl, boxes[cand[k]]) for k in keep)  # @line L7
    dets.sort(key=lambda d: (-d[0], d[1]))
    return dets  # @line L8


def yolo_v1_loss(out, gts, labels, s, b, c, img_w, img_h, l_coord=5.0, l_noobj=0.5):
    """The sum-squared loss of YOLO v1 on given outputs.

    The cell that holds the center of a truth box is responsible for it; if two
    centers fall in one cell, the first truth is kept. In that cell, the
    predictor whose box has the largest IoU with the truth (ties to the lower
    index) is responsible, and its confidence target is that IoU. Every other
    predictor gets the no-object term."""
    owner = {}
    for g, cl in zip(gts, labels):
        cx, cy = (g[0] + g[2]) / 2, (g[1] + g[3]) / 2
        i = min(int(cy / img_h * s), s - 1)
        j = min(int(cx / img_w * s), s - 1)
        if (i, j) not in owner:
            owner[(i, j)] = (g, cl, cx * s / img_w - j, cy * s / img_h - i,
                             (g[2] - g[0]) / img_w, (g[3] - g[1]) / img_h)
    loss = 0.0
    for i in range(s):
        for j in range(s):
            v = out[i][j]
            preds = [v[5 * k:5 * k + 5] for k in range(b)]
            if (i, j) not in owner:
                loss += l_noobj * sum(p[4] ** 2 for p in preds)
                continue
            g, cl, tx, ty, tw, th = owner[(i, j)]
            ious = [iou(cell_box(i, j, p[0], p[1], max(p[2], 0.0), max(p[3], 0.0), s, img_w, img_h), g)
                    for p in preds]
            r = max(range(b), key=lambda k: (ious[k], -k))
            for k, p in enumerate(preds):
                if k != r:
                    loss += l_noobj * p[4] ** 2
                    continue
                x, y, w, h, conf = p
                loss += l_coord * ((x - tx) ** 2 + (y - ty) ** 2)
                loss += l_coord * ((math.sqrt(max(w, 0.0)) - math.sqrt(tw)) ** 2
                                   + (math.sqrt(max(h, 0.0)) - math.sqrt(th)) ** 2)
                loss += (conf - float(ious[r])) ** 2
            loss += sum((v[5 * b + k] - (1.0 if k == cl else 0.0)) ** 2 for k in range(c))
    return loss


def sigmoid(t):
    return 1 / (1 + math.exp(-t))


def decode_v2(t, i, j, prior, stride):
    """Version 2 decoding of t = (t_x, t_y, t_w, t_h, t_o) at cell (row i, column j)
    with an anchor prior = (p_w, p_h) in grid units. Returns (box in pixels, objectness)."""
    bx, by = sigmoid(t[0]) + j, sigmoid(t[1]) + i
    bw, bh = prior[0] * math.exp(t[2]), prior[1] * math.exp(t[3])
    box = ((bx - bw / 2) * stride, (by - bh / 2) * stride, (bx + bw / 2) * stride, (by + bh / 2) * stride)
    return box, sigmoid(t[4])


def shape_iou(a, b):
    """IoU of two shapes (w, h) placed at the same center."""
    inter = min(a[0], b[0]) * min(a[1], b[1])
    return inter / (a[0] * a[1] + b[0] * b[1] - inter)


def dimension_clusters(shapes, k, seed=0, iters=100):
    """k-means on box shapes with the distance 1 - IoU and the mean as the center.
    Returns (centroids, assignment)."""
    rng = random.Random(seed)
    cents = rng.sample(list(shapes), k)
    assign = None
    for _ in range(iters):
        new = [max(range(k), key=lambda c: (shape_iou(sh, cents[c]), -c)) for sh in shapes]
        if new == assign:
            break
        assign = new
        for c in range(k):
            members = [sh for sh, a in zip(shapes, assign) if a == c]
            if members:
                cents[c] = (sum(m[0] for m in members) / len(members),
                            sum(m[1] for m in members) / len(members))
    return cents, assign
test_yolo_detector.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yolo-detector/. The authors are listed in prov/D6VPA6.jsonl.

import math
import random

from yolo_detector import (
    cell_box,
    decode_v2,
    detect,
    dimension_clusters,
    iou,
    shape_iou,
    yolo_v1_loss,
)


def close(a, b, tol=1e-9):
    return all(abs(x - y) < tol for x, y in zip(a, b))


def page_tensor():
    return [
        [[0.8, 0.8, 0.6, 0.6, 0.9, 0.8, 0.2], [0.3, 0.5, 0.4, 0.4, 0.6, 0.1, 0.9]],
        [[0.8, 0.0, 0.6, 0.6, 0.6, 0.6, 0.4], [0.5, 0.5, 0.2, 0.2, 0.1, 0.5, 0.5]],
    ]


def test_page_example_decoding():
    out = page_tensor()
    assert close(cell_box(0, 0, 0.8, 0.8, 0.6, 0.6, 2, 100, 100), (10, 10, 70, 70))
    assert close(cell_box(0, 1, 0.3, 0.5, 0.4, 0.4, 2, 100, 100), (45, 5, 85, 45))
    assert close(cell_box(1, 0, 0.8, 0.0, 0.6, 0.6, 2, 100, 100), (10, 20, 70, 80))
    assert abs(iou((10, 10, 70, 70), (10, 20, 70, 80)) - 5 / 7) < 1e-12
    dets = detect(out, 2, 1, 2, 100, 100)
    assert [(round(sc, 9), cl) for sc, cl, _ in dets] == [(0.72, 0), (0.54, 1), (0.24, 1)]
    assert close(dets[0][2], (10, 10, 70, 70)) and close(dets[2][2], (10, 20, 70, 80))
    # With a looser NMS threshold the second box of class 0 stays.
    dets = detect(out, 2, 1, 2, 100, 100, nms_thr=0.75)
    assert [(round(sc, 9), cl) for sc, cl, _ in dets] == [(0.72, 0), (0.54, 1), (0.36, 0), (0.24, 1)]


def test_detect_properties_on_random_outputs():
    rng = random.Random(6)
    for _ in range(5):
        s, b, c = 4, 2, 3
        out = [[[rng.random() for _ in range(5 * b + c)] for _ in range(s)] for _ in range(s)]
        dets = detect(out, s, b, c, 64, 64, score_thr=0.15, nms_thr=0.4)
        assert len(dets) <= s * s * b * c
        assert [d[0] for d in dets] == sorted((d[0] for d in dets), reverse=True)
        assert all(d[0] > 0.15 for d in dets)
        for x in range(len(dets)):
            for y in range(x):
                if dets[x][1] == dets[y][1]:
                    assert iou(dets[x][2], dets[y][2]) <= 0.4


def test_page_example_loss():
    out = [[[0.6, 0.5, 0.6, 0.6, 0.7, 0.5, 0.5, 0.2, 0.2, 0.4, 0.3, 0.7]]]
    want = 5 * 0.1 ** 2 + (0.7 - 5 / 7) ** 2 + 0.5 * 0.4 ** 2 + 0.3 ** 2 + 0.3 ** 2
    assert abs(yolo_v1_loss(out, [(20, 20, 80, 80)], [1], 1, 2, 2, 100, 100) - want) < 1e-12
    # With no object, only the no-object term of both confidences is left.
    assert abs(yolo_v1_loss(out, [], [], 1, 2, 2, 100, 100) - 0.5 * (0.49 + 0.16)) < 1e-12


def test_loss_is_zero_on_perfect_outputs():
    rng = random.Random(7)
    s, b, c = 3, 2, 4
    for _ in range(20):
        cells = rng.sample([(i, j) for i in range(s) for j in range(s)], 3)
        gts, labels = [], []
        out = [[[0.0] * (5 * b + c) for _ in range(s)] for _ in range(s)]
        for i, j in cells:
            x, y = rng.uniform(0.05, 0.95), rng.uniform(0.05, 0.95)
            w, h = rng.uniform(0.1, 0.5), rng.uniform(0.1, 0.5)
            g = cell_box(i, j, x, y, w, h, s, 90, 90)
            cl = rng.randrange(c)
            gts.append(g)
            labels.append(cl)
            k = rng.randrange(b)
            out[i][j][5 * k:5 * k + 5] = [x, y, w, h, 1.0]
            out[i][j][5 * b + cl] = 1.0
        assert yolo_v1_loss(out, gts, labels, s, b, c, 90, 90) < 1e-12


def test_square_root_weights_small_boxes():
    def loss_for(w_true, w_pred):
        g = cell_box(0, 0, 0.5, 0.5, w_true, 0.5, 1, 100, 100)
        out = [[[0.5, 0.5, w_pred, 0.5, 0.0, 1.0]]]
        return yolo_v1_loss(out, [g], [0], 1, 1, 1, 100, 100, l_noobj=0.0)

    small = loss_for(0.1, 0.15) - (0 - float(iou(cell_box(0, 0, 0.5, 0.5, 0.15, 0.5, 1, 100, 100),
                                               cell_box(0, 0, 0.5, 0.5, 0.1, 0.5, 1, 100, 100)))) ** 2
    large = loss_for(0.8, 0.85) - (0 - float(iou(cell_box(0, 0, 0.5, 0.5, 0.85, 0.5, 1, 100, 100),
                                               cell_box(0, 0, 0.5, 0.5, 0.8, 0.5, 1, 100, 100)))) ** 2
    assert small > 5 * large


def test_v2_decoding():
    box, obj = decode_v2((0.0, 0.0, 0.0, 0.0, 0.0), 1, 2, (2.0, 3.0), 32)
    assert close(box, (48, 0, 112, 96)) and obj == 0.5
    rng = random.Random(8)
    for _ in range(100):
        t = [rng.gauss(0, 5) for _ in range(5)]
        i, j = rng.randrange(13), rng.randrange(13)
        box, obj = decode_v2(t, i, j, (1.5, 2.5), 32)
        cx, cy = (box[0] + box[2]) / 64, (box[1] + box[3]) / 64
        assert j <= cx <= j + 1 and i <= cy <= i + 1 and 0 <= obj <= 1


def test_dimension_clusters():
    rng = random.Random(9)
    groups = [(1.0, 1.0), (3.0, 1.0), (1.0, 4.0)]
    shapes = [(gw * rng.uniform(0.9, 1.1), gh * rng.uniform(0.9, 1.1)) for gw, gh in groups for _ in range(30)]
    cents, assign = dimension_clusters(shapes, 3, seed=1)
    for gw, gh in groups:
        assert any(abs(cw - gw) < 0.1 * gw and abs(ch - gh) < 0.1 * gh for cw, ch in cents)
    for sh, a in zip(shapes, assign):
        assert shape_iou(sh, cents[a]) >= max(shape_iou(sh, cc) for cc in cents) - 1e-12
    assert math.isclose(shape_iou((2, 2), (1, 4)), 2 / 6)

History

Before YOLO, detectors applied a classifier many times: on sliding windows, as in the deformable part model, or on proposals, as in R-CNN and its successors. Redmon, Divvala, Girshick and Farhadi put YOLO on arXiv in June 2015 and presented it at CVPR 2016. It was the first detector to run in real time at a useful accuracy on PASCAL VOC, with one network from pixels to boxes. Redmon and Farhadi added anchors and other changes in YOLO9000 at CVPR 2017. YOLOv3 followed in 2018. The name was later taken up by a long line of detectors from other groups.

References

  1. Joseph Redmon, Santosh Divvala, Ross Girshick and Ali Farhadi, You only look once: unified, real-time object detection, CVPR 2016, 779-788, Section 2, Unified detection (S x S grid, B boxes with x, y, w, h and confidence, C class probabilities, class-specific confidence; S = 7, B = 2, C = 20, a 7 x 7 x 30 tensor); Section 2.2, Training (the loss with lambda_coord = 5, lambda_noobj = 0.5 and square roots of w and h; the responsible predictor has the highest current IOU); Section 2.3, Inference (98 boxes per image, NMS adds 2 to 3 percent mAP); Section 2.4, Limitations; Section 4, Experiments (Table 1: 63.4 mAP at 45 FPS, Fast YOLO 52.7 mAP at 155 FPS on VOC 2007)
  2. Joseph Redmon and Ali Farhadi, YOLO9000: better, faster, stronger, CVPR 2017 (arXiv 1612.08242), Section 2, Better (convolutional with anchor boxes: recall from 81 to 88 percent; dimension clusters: k-means with d = 1 - IOU and k = 5; direct location prediction: b_x = sigma(t_x) + c_x, b_w = p_w e^t_w; a 13 x 13 map for a 416 input); Table 3 (YOLOv2 at 416: 76.8 mAP at 67 FPS on VOC 2007)
  3. Joseph Redmon and Ali Farhadi, YOLOv3: an incremental improvement, arXiv 1804.02767, 2018, Section 2, The deal (predictions at 3 scales, 9 clusters, independent logistic classifiers)
  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