Deep Learning · Topic 1 · Learn Yolo from scratch A-Z · The whole process · Advanced

From photo to boxes,
A to Z

Theory and Practical. Twenty-six steps follow one 768 × 576 street photo through YOLOv1. A to T take that one photo through the network to three labelled boxes. U to Y show how its 271.7 million weights were learned: the loss, its gradient, the optimiser, pre-training and augmentation. Z is what it costs to run and how to reuse it.

Click any letter, press ▶, or use the arrow keys.

Advanced level, Year 1, for Master students taking the Data Mining and Deep-Learning course. Every step carries the full mathematics, the paper's design choices and the cost formulas. The basics are on the Intermediate page; the architecture is on the Blueprint.

01

The whole process on one sheet

The photo enters on the left; three boxes leave on the right. Tensors are drawn to scale: width is the spatial size, depth is the number of channels. The dashed red loop underneath is training. Click any lettered dot to jump to that step.
YOLOv1 · input → forward pass → output · training below · cost on the right100%
02

Step by step

Letters fill in as you pass them. Each step shows what goes in and what comes out, a figure, a one-sentence plain version, the mathematics, and a check. The running totals of weights and multiply-adds are computed from the same layer specification as the Blueprint.
A
step 1 of 26
input100%
← → keys · any letter key jumps · F = full screen
input24 conv layers (backbone + detection convs)flatten · FC1 · FC2

in
out

In plain words

tensor at this point
weights so far
0
MACs so far
0
Advanced · the key block in full

The detection head and its loss, derived

The backbone is an ordinary classifier. What makes YOLO a detector is the 7 × 7 × 30 head and the loss that trains it. Below: the loss term by term, its gradient through the head, the cost formulas behind the running totals, the design choices and ablations of Redmon et al. (2016), the successors, and a reference implementation.

D1

The loss, term by term

𝓛 = λcoord Σi=0S²−1 Σj=0B−1 𝟙ijobj [ (xi − x̂i)² + (yi − ŷi)² ]  ① centre
  + λcoord Σi Σj 𝟙ijobj [ (√wi − √ŵi)² + (√hi − √ĥi)² ]  ② size
  + Σi Σj 𝟙ijobj (Ci − Ĉi)²  ③ confidence, responsible
  + λnoobj Σi Σj 𝟙ijnoobj (Ci − Ĉi)²  ④ confidence, empty
  + Σi 𝟙iobj Σc ∈ classes (pi(c) − p̂i(c))²  ⑤ class
S = 7 · B = 2 · C = 20 · λcoord = 5 · λnoobj = 0.5 · target Ci = IoU(b̂ij, bi) for the responsible j, 0 otherwise

Why sum-squared error? It is the simplest loss to optimise and treats the whole output as one regression. Its flaw: it weighs a box-centre error the same as a confidence or class error, and the 98 predictors are mostly empty. The paper fixes this with two weights rather than a new loss.

Why λnoobj = 0.5? In our photo 3 of 98 predictors are responsible and 95 are not. Unweighted, term ④ pushes almost every confidence to 0 and overwhelms the gradient from the cells that do hold objects, which the paper says makes training diverge early.

Why √w, √h? A 5-pixel error matters more on a small box than on a large one. Regressing √w gives d√w/dw = 1/(2√w), so the same absolute error costs more when w is small.

D2

The gradient through the head

output layer: the network emits x̂, ŷ, √ŵ, √ĥ, Ĉ and p̂ directly (linear activation)
∂𝓛/∂x̂ij = 2 λcoord 𝟙ijobj (x̂ij − xi)   ∂𝓛/∂√ŵij = 2 λcoord 𝟙ijobj (√ŵij − √wi)
∂𝓛/∂Ĉij = 2 (𝟙ijobj + λnoobj 𝟙ijnoobj) (Ĉij − Cij)   IoU target treated as a constant
∂𝓛/∂p̂i(c) = 2 𝟙iobj (p̂i(c) − pi(c))
collect them in δ2 = ∂𝓛/∂ŷ ∈ ℝ1470; FC2 is ŷ = W2h + b2
∂𝓛/∂W2 = δ2 hᵀ (1470 × 4096)  ∂𝓛/∂b2 = δ2  ∂𝓛/∂h = W2ᵀ δ2
dropout h = m ⊙ a / (1 − p), leaky a = φ(z1), FC1 z1 = W1v + b1
δ1 = ∂𝓛/∂z1 = φ′(z1) ⊙ m ⊙ (W2ᵀ δ2) / (1 − p)   φ′ ∈ {1, 0.1}
∂𝓛/∂W1 = δ1 vᵀ (4096 × 50176)  ∂𝓛/∂v = W1ᵀ δ1 → reshape 7 × 7 × 1024
each conv: ∂𝓛/∂X = transposed convolution of δ with W; ∂𝓛/∂W = correlation of X with δ

The output gradient is sparse. Coordinate and class gradients are non-zero only in the 3 cells that hold an object centre; the other 46 cells send back only the small confidence gradient Ĉ (since 2 · 0.5 · Ĉ = Ĉ). Every one of those 1,470 numbers still reaches all 4,096 units of FC1 through W2ᵀ, so every cell's features are shaped by every object. That is the global reasoning the paper credits for its low background error.

Why it works. The responsible-predictor rule j = argmax IoU makes the two predictors of a cell specialise: whichever already fits better gets pulled closer, the other is told "no object". Over training, one predictor drifts towards tall boxes and the other towards wide ones, which is an early, learned version of the anchor boxes YOLOv2 later fixed by k-means.

Cost. The backward pass needs two products per weight layer (∂𝓛/∂X and ∂𝓛/∂W), so it costs about 2 × the forward MACs; one training image ≈ 3 × MACs.

D3

Complexity with formulas

conv weights P = (k² · Cin + 1) · Cout   conv MACs M = Hout · Wout · Cout · k² · Cin   Hout = ⌊(Hin − k + 2p) / s⌋ + 1
dense weights P = (nin + 1) · nout   dense MACs M = nin · nout   activation memory A = Σlayers H · W · C × 4 bytes (fp32, batch 1)
every layer, computed from the layer specification100%
layerk / s / poutputweightsMACsactivations
D4

Design choices, training details and ablations from the paper

choicevaluewhy
grid S · boxes B · classes C7 · 2 · 20output 7 × 7 × 30; at most 49 objects, one class vector per cell
input448 × 448detection needs finer detail than the 224 × 224 pre-training
activationleaky ReLU, 0.1all layers except the last, which is linear
λcoord · λnoobj5 · 0.5re-balance sum-squared error toward localisation
box size target√w, √hsmall boxes penalised more for the same error
pre-training20 conv, ImageNet, ≈ 1 week, 88 % top-5then 4 conv + 2 FC added with random weights
optimiserSGD, batch 64, momentum 0.9, decay 0.0005135 epochs on VOC 2007 + 2012 train/val
learning rate10⁻³ → 10⁻², then 75 · 30 · 30 epochs at 10⁻² · 10⁻³ · 10⁻⁴starting high diverges
regularisationdropout 0.5 after FC1plus augmentation below
augmentationscale and shift ±20 %, exposure and saturation ×1.5 (HSV)16.5 k images are few for 271.7 M weights
post-processingNMSadds 2–3 % mAP
result (VOC 2007 test unless noted)mAPfps
Fast YOLO (9 conv layers, fewer filters)52.7155
YOLO (24 conv layers)63.445
YOLO with a VGG-16 backbone66.421
Fast R-CNN70.00.5
Faster R-CNN, VGG-1673.27
Fast R-CNN rescored by YOLO75.0—
YOLO, VOC 2012 test57.9—

Error analysis (paper, Fig. 4). Of YOLO's top detections, 19.0 % are localisation errors against 8.6 % for Fast R-CNN; background false positives are 4.75 % against 13.6 %. YOLO sees the whole image, so it rarely invents objects, but its coarse 64-pixel grid and squared-error loss make its boxes less tight. That is why rescoring Fast R-CNN with YOLO adds 3.2 mAP (71.8 → 75.0).

D5

Variants and successors, with their trade-offs

modelyearwhat changedtrade-off
Fast YOLO20169 conv layers instead of 24, fewer filters3.4 × faster, 10.7 mAP lower
YOLOv2 / YOLO90002017batch norm, no FC head (fully convolutional), 5 anchor boxes from k-means, σ-bounded offsets, 13 × 13 grid at 416, multi-scale training, Darknet-1976.8 mAP at 67 fps (416), 78.6 at 40 fps (544); class per anchor instead of per cell
YOLOv32018Darknet-53 with residual blocks, predictions at 3 scales, 9 anchors, independent logistic class scoresmuch better on small objects; heavier backbone
YOLOv42020CSPDarknet-53, SPP + PANet neck, Mosaic augmentation, CIoU loss“bag of freebies”: accuracy from training tricks at the same inference cost
YOLOv5 → YOLOv82020–23PyTorch code base, auto-anchors, later anchor-free decoupled headseasy to train and deploy; design choices documented in code more than papers
YOLOX2021anchor-free, decoupled classification/regression head, SimOTA label assignmentreplaces the hard “one cell, best IoU” rule with an optimal-transport assignment
YOLOv102024consistent dual assignment so one box per object is trained directlyno NMS at inference: lower latency and no NMS threshold to tune
D6

Reference implementation of the key block (PyTorch-style)

yolo_v1_head_and_loss.py
import torch
import torch.nn as nn

S, B, C = 7, 2, 20                  # grid, boxes per cell, classes
L_COORD, L_NOOBJ = 5.0, 0.5

def iou(a, b):                       # boxes (cx, cy, w, h) in image units, shape [..., 4]
    a1, a2 = a[..., :2] - a[..., 2:] / 2, a[..., :2] + a[..., 2:] / 2
    b1, b2 = b[..., :2] - b[..., 2:] / 2, b[..., :2] + b[..., 2:] / 2
    wh = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(min=0)
    inter = wh[..., 0] * wh[..., 1]
    union = a[..., 2] * a[..., 3] + b[..., 2] * b[..., 3] - inter
    return inter / union.clamp(min=1e-9)

class YoloHead(nn.Module):           # 7 x 7 x 1024 features -> 7 x 7 x 30
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Flatten(), nn.Linear(7 * 7 * 1024, 4096),
            nn.LeakyReLU(0.1), nn.Dropout(0.5),
            nn.Linear(4096, S * S * (B * 5 + C)))      # linear output

    def forward(self, f):                # f: [N, 1024, 7, 7]
        return self.fc(f).view(-1, S, S, B * 5 + C)

class YoloV1Loss(nn.Module):
    # p, t: [N, S, S, 30]. Target t holds (x, y, sqrt w, sqrt h, 1) in slots 0..4
    # for cells with an object centre, zeros elsewhere, one-hot classes in 10..29.
    def forward(self, p, t):
        obj = (t[..., 4] > 0).float()                          # 1_i^obj  [N, S, S]
        gx, gy = torch.meshgrid(torch.arange(S), torch.arange(S), indexing='xy')
        cell = torch.stack([gx, gy], -1).to(p)                  # (col, row) per cell

        def to_img(bx):                                        # offsets, sqrt size -> image units
            return torch.cat([(bx[..., :2] + cell) / S, bx[..., 2:4] ** 2], -1)

        box = p[..., :B * 5].view(*p.shape[:3], B, 5)          # [N, S, S, B, 5]
        ious = torch.stack([iou(to_img(box[..., j, :4]), to_img(t[..., :4]))
                            for j in range(B)], -1)           # [N, S, S, B]
        best = ious.argmax(-1, keepdim=True)                    # responsible predictor j
        resp = torch.zeros_like(ious).scatter_(-1, best, 1.0) * obj.unsqueeze(-1)

        coord = ((box[..., :4] - t[..., None, :4]) ** 2).sum(-1)  # terms 1 + 2
        conf_obj = (box[..., 4] - ious.detach()) ** 2            # term 3, IoU as constant
        conf_noobj = box[..., 4] ** 2                            # term 4
        cls = ((p[..., B * 5:] - t[..., B * 5:]) ** 2).sum(-1)     # term 5

        loss = (L_COORD * (resp * coord).sum()
                + (resp * conf_obj).sum()
                + L_NOOBJ * ((1 - resp) * conf_noobj).sum()
                + (obj * cls).sum())
        return loss / p.shape[0]                              # mean over the batch

The backbone is any CNN that maps 448 × 448 × 3 to 7 × 7 × 1024 (24 convolutions with leaky ReLU in the paper). Training: torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9, weight_decay=5e-4), warm up to 1e-2, then step down at epochs 75 and 105 of 135.

03

All 26 steps in one table

A printable summary: the letter, the step, what goes in, what comes out, and the one figure to remember. Shapes and weight counts come from the layer specification; training rows carry the hyper-parameters of the paper. Click a row to open that step.
letterstepinputoutputkey figure

04

Check yourself

Derivations, calculations and what-if questions. Pick an answer; the explanation appears whichever you choose. Use the step letters to go back when one surprises you.

05

Glossary

Every term marked with a red ? on this page. Click a badge anywhere to see its definition in place, or filter the list here.