Deep Learning · Topic 1 · Learn Yolo from scratch A-Z · Interactive sheet · Advanced

The Learn Yolo from scratch A-Z Blueprint

Theory and Practical

YOLO turns object detection into a single regression problem: one forward pass maps the whole image to an S × S × (5B + C) tensor of boxes, confidences and class probabilities. Everything else on this page (the grid, the loss weights, the square roots, non-maximum suppression) follows from that one decision. Every number on this page is clickable. Every underlined term has a definition.

Before you start: what a convolution and a stride are (CNN), how a deep classifier is built and counted (AlexNet & VGG-16), and least-squares regression (Linear Regression). New to YOLO itself? Read the Intermediate page first.

7 × 7 × 30
output tensor
–
parameters
–
MACs per image
63.4 mAP
at 45 fps
S·S·(5B+C)
one pass, one tensor
01

Detection in real time: the challenge and the headline

On PASCAL VOC a detector must output a box and a class for every object, and is scored by mean average precision at an IoU of 0.5; in 2015 the accurate systems ran at under 10 frames per second.

Scoring one detection: is IoU ≥ threshold?

shift x20
shift y10
scale1.10
IoU threshold0.50

Drag the red box, or use the sliders. Green dashed = ground truth.

63.4
mAP · YOLO · 45 fps
155 fps
Fast YOLO · 52.7 mAP
0.5 fps
Fast R-CNN · 70.0 mAP
7 fps
Faster R-CNN · 73.2 mAP

Why it mattered

Two-stage detectors classify ~2,000 region proposals per image. YOLO reframes detection as one regression from pixels to box coordinates and class probabilities, trained end to end on a single loss, so the whole image (global context) informs every box. Price: about 7–10 mAP less than the best two-stage systems in 2016, mostly from localisation errors.

2010 DPM 2014 R-CNN 2015 Fast/Faster R-CNN 2016 YOLO 2017 YOLOv2 2018 YOLOv3 2020 YOLOv4
02

Walk an image through the network

Scrub through all layers: every shape, weight count and multiply-add below is computed from the embedded layer specification, so the totals are derived, not typed in.
conv + leaky ReLU max-pool 2 × 2 flatten / dense S × S × (5B + C) output
YOLO100%
layer scrubberinput
input
params so far
0
MACs so far
0

Forward equations of the whole network

backbone (24 conv layers, l = 1 … 24) a⁽ˡ⁾ = φ( W⁽ˡ⁾ ∗ a⁽ˡ⁻¹⁾ + b⁽ˡ⁾ ), φ(z) = max(z, 0.1·z) leaky ReLU, max-pools after layers 1, 2, 6, 16
head h = φ( W₁ · vec(a⁽²⁴⁾) + b₁ ), vec(a⁽²⁴⁾) ∈ ℝ^(7·7·1024 = 50,176), h ∈ ℝ⁴⁰⁹⁶, dropout 0.5 on h
z = W₂ · h + b₂ ∈ ℝ¹⁴⁷⁰ (linear) → reshape to Y ∈ ℝ^(7 × 7 × 30)
cell (i, j), predictor b ∈ {1, 2} Y[i, j, 5b−5 … 5b−1] = (x̂, ŷ, √ŵ, √ĥ, Ĉ), Y[i, j, 10 … 29] = p̂(c | object), c = 1 … 20
Conv1 uses 64 filters of 7 × 7, stride 2, padding 3 on a 448 × 448 input. What is its output size?
⌊(448 − 7 + 2·3) ÷ 2⌋ + 1 = ⌊447 ÷ 2⌋ + 1 = 223 + 1 = 224. The floor drops the half pixel; that is why padding 3 (not 3.5) still gives exactly half the input size.
03

The three ideas that made it work

Responsibility by grid cell, a box parameterisation that makes squared error fair across sizes, and non-maximum suppression to clean up duplicates.

Idea 1 · The cell that contains the centre is responsible

Click or tap anywhere to move the object's centre.

box width (px)160
box height (px)220
grid S7
x = (c_x ÷ (448 ÷ S)) − j, y = (c_y ÷ (448 ÷ S)) − i
w = box_w ÷ 448, h = box_h ÷ 448 → targets (x, y, √w, √h)

Idea 2 · Predict √w and √h so a small box's error costs more

squared error for the same absolute width error Δ · blue: on w · red: on √w · click the plot to move w
true width w (fraction of image)0.10
width error Δ0.03
(√(w+Δ) − √w)² ≈ ( Δ ÷ (2√w) )² = Δ² ÷ (4w)

Idea 3 · Class-specific confidence, then greedy NMS

score threshold0.20
NMS IoU threshold0.50
score(c) = Pr(c | obj) · Pr(obj) · IoU = Pr(c) · IoU

S = 7 on a 448 × 448 image. An object's centre is at (c_x, c_y) = (300, 120) px. Which target x does the responsible cell receive?
Cells are 448 ÷ 7 = 64 px wide. 300 ÷ 64 = 4.6875, so column j = 4 and x = 0.6875 ≈ 0.69; 120 ÷ 64 = 1.875 gives row i = 1 (y ≈ 0.88). 0.67 would be the image-relative coordinate, which v1 does not regress.
04

The defining rule: one pass, one S × S × (5B + C) tensor

Change S, B and C and compare the single regression with a proposal-based pipeline; then derive the loss and the gradient that flows back through the head.

grid S7
boxes per cell B2
classes C20
YOLO · one pass
7 × 7 × 30
vs
proposals
~2,000
regions classified per image
outputs = S² · (5B + C) · FC2 weights = 4,096 · outputs + outputs

The loss, written out

L = λ_coord Σᵢ₌₀^{S²−1} Σⱼ₌₀^{B−1} 𝟙ᵢⱼ^obj [ (xᵢ − x̂ᵢ)² + (yᵢ − ŷᵢ)² ]
  + λ_coord Σᵢ Σⱼ 𝟙ᵢⱼ^obj [ (√wᵢ − √ŵᵢ)² + (√hᵢ − √ĥᵢ)² ]
  + Σᵢ Σⱼ 𝟙ᵢⱼ^obj (Cᵢ − Ĉᵢ)² + λ_noobj Σᵢ Σⱼ 𝟙ᵢⱼ^noobj (Cᵢ − Ĉᵢ)²
  + Σᵢ 𝟙ᵢ^obj Σ_c (pᵢ(c) − p̂ᵢ(c))², λ_coord = 5, λ_noobj = 0.5, target Cᵢ = IoU(pred, truth) when responsible, else 0

Derivation: the gradient through the head

Responsibility mask. For an object with centre in cell i, compute IoU of each of the B current predictions with the truth; the best one gets 𝟙ᵢⱼ^obj = 1, all other predictors 𝟙^noobj = 1.
j* = argmaxⱼ IoU(b̂ᵢⱼ, b) → predictors specialise in sizes and aspect ratios
Coordinate gradient (responsible predictor only)
∂L/∂x̂ = −2 λ_coord (x − x̂) = −10 (x − x̂); same for ŷ
Size gradient: the network outputs s = √ŵ directly
∂L/∂s = −2 λ_coord (√w − s); an error Δ in w costs ≈ λ_coord · Δ² ÷ (4w) → ∝ 1/w
Confidence gradient: object vs empty predictors
obj: ∂L/∂Ĉ = −2 (IoU − Ĉ) · noobj: ∂L/∂Ĉ = 2 λ_noobj Ĉ = Ĉ
Class gradient: only cells that contain an object centre
∂L/∂p̂(c) = −2 𝟙ᵢ^obj (p(c) − p̂(c)); 20 squared errors, no softmax
Into the linear output layer: δ = ∂L/∂z ∈ ℝ¹⁴⁷⁰ (mostly zeros for coordinates and classes)
∂L/∂W₂ = δ hᵀ · ∂L/∂b₂ = δ · ∂L/∂h = W₂ᵀ δ
Through dropout and leaky ReLU into FC1, then reshape to 7 × 7 × 1024 and back through the convs
∂L/∂u₁ = (W₂ᵀ δ) ⊙ m ⊙ φ′(u₁), φ′ ∈ {1, 0.1} → every unit always passes ≥ 10 % of its gradient

Why the λ's: with 98 predictors and typically 1–3 responsible ones, the unweighted noobj terms would contribute about 30–90 × more gradient to Ĉ than the object terms and drive every confidence to zero early in training.

Reference implementation of the loss (PyTorch-style)

# pred, target: (N, S, S, 5B + C); target boxes stored in slot 0, class one-hot in 5B:
def yolo_v1_loss(pred, target, S=7, B=2, C=20, l_coord=5.0, l_noobj=0.5):
    obj = target[..., 4]                                   # 1 if an object centre is in the cell
    boxes = pred[..., :5*B].reshape(*pred.shape[:3], B, 5)  # (x, y, sqrt w, sqrt h, conf)
    tbox  = target[..., :4]                                 # (x, y, sqrt w, sqrt h)
    ious  = torch.stack([iou(cell_to_img(boxes[..., b, :4]),
                             cell_to_img(tbox)) for b in range(B)], -1)
    best  = ious.argmax(-1, keepdim=True)                  # responsible predictor
    resp  = torch.zeros_like(ious).scatter_(-1, best, 1.0) * obj[..., None]
    noobj = 1.0 - resp
    b     = boxes
    l_xy  = ((b[..., :2] - tbox[..., None, :2]) ** 2).sum(-1)
    l_wh  = ((b[..., 2:4] - tbox[..., None, 2:4]) ** 2).sum(-1)  # already sqrt
    l_obj = (b[..., 4] - ious.detach()) ** 2                  # target C = IoU
    l_no  = b[..., 4] ** 2
    l_cls = ((pred[..., 5*B:] - target[..., 5*B:]) ** 2).sum(-1) * obj
    loss  = (l_coord * resp * (l_xy + l_wh) + resp * l_obj
             + l_noobj * noobj * l_no).sum() + l_cls.sum()
    return loss / pred.shape[0]
What-if: keep S = 7 and C = 20 but raise B from 2 to 3. How many outputs does FC2 now produce, and how many objects can v1 detect at most?
5B + C = 15 + 20 = 35 per cell. The extra predictor adds shape variety, but each cell still has one class distribution and one assigned object during training, so capacity stays S² = 49.
05

Shapes by hand and by eye

Do one convolution with tiny numbers on paper, then use the same formula to trace 448 → 224 → 112 → 56 → 28 → 14 → 7 through YOLO.

Worked example by hand: a 4 × 4 input and one 3 × 3 filter

input I (4 × 4)
filter K (3 × 3)
output O

This filter (+1 left column, −1 right column) responds to dark-to-light vertical edges. Redo each step on paper: nine products, one sum, then the leaky ReLU.

O(r, c) = Σ_{u=0}^{2} Σ_{v=0}^{2} I(r·S + u − P, c·S + v − P) · K(u, v) + b

With b = 0, S = 1, P = 0. In YOLO the same operation runs with 64 to 1,024 filters and over all input channels at once: the sum gains a third index over Cin.

O = ⌊(N − K + 2P) ÷ S⌋ + 1 ⌊⌋
input N448
kernel K7
padding P3
stride S2
output size
224 × 224
kernel sliding over the padded input → output map · click to pause100%
Receptive field check: by conv24 a single 7 × 7 output position already sees far more than the 448-pixel image (the theoretical field computed in section 02 exceeds 448), so each cell's prediction can use whole-object and scene context even before the dense layers mix everything.
YOLO's stride-2 conv (K = 3, P = 1, S = 2) receives a 14 × 14 map. What comes out?
(14 − 3 + 2) ÷ 2 = 6.5 → floor 6 → + 1 = 7. This is the step that produces the 7 × 7 grid, together with the four max-pools (448 ÷ 2⁶ = 7).
06

Where the parameters live

One dense layer, 50,176 → 4,096, holds most of the parameters, while the 24 convs do almost all of the MACs; click a bar for its arithmetic.
100%
convdensepool layers have no parameters · bars are linear in value
click a bar

The arithmetic for that layer appears here.

Parameters

Compute (MACs)

per 448 × 448 image, forward pass

Worked example: counting the parameters

Complexity in general: conv weights (K²·Cin + 1)·Cout, conv MACs Hout·Wout·Cout·K²·Cin, activation memory Σ H·W·C values per image (times 4 bytes in float32, times about 2 for training because the backward pass keeps them).

What-if: feed 512 × 512 images, so the last conv map is 8 × 8 × 1024. How many parameters does FC1 (→ 4,096) now have?
Inputs = 8 · 8 · 1024 = 65,536; params = 65,536 · 4,096 + 4,096 = 268,439,552. The convs are unchanged (weights do not depend on H × W), but a flatten-then-dense head ties the parameter count to the input size; that is one reason later YOLOs use a conv head.
07

The family and its variants

Compare depth, parameters, accuracy and speed across the YOLO line; the two v1 models are computed from their layer specs and can be loaded into the walker.
variants · click a row
modelyearbackboneconv layersparamsbenchmarkscorefps
variant

Pick a row.

Trade-offs, in one line each. Fast YOLO: 3.4 × the speed for −10.7 mAP. YOLO-VGG16: +3.0 mAP but less than half the speed. v2: batch norm, anchor boxes and a fully convolutional head raise recall and allow any input size. v3: three output scales fix small objects. v4: a better backbone and “bag of freebies” training.

YOLO with the VGG-16 backbone reaches 66.4 mAP at 21 fps, the 24-layer YOLO 63.4 mAP at 45 fps. For a 30 fps video stream, which should you deploy (same GPU)?
At 21 fps YOLO-VGG16 would drop roughly every third frame. The 24-layer model meets the real-time budget; Fast YOLO would too, but costs 10.7 mAP more.
08

The cost of going deep

From MACs per image to milliseconds, epochs and the original training run; set the GPU's throughput, its realistic utilisation and the batch size.
model
peak throughput (TFLOPS)6.1
utilisation30 %
batch size64
t_img = 2 · MACs ÷ (TFLOPS · 10¹² · u)
t_epoch ≈ 3 · t_img · 16,551 (fwd + bwd)
t_run = 135 epochs · t_epoch
MACs per image
one image
one epoch (training)
original detection run
activation memory for the batch (float32)
A detector needs 20 G MACs per image. On a 10 TFLOPS GPU at 100 % utilisation, what is the best possible time per image?
2 · 20 × 10⁹ FLOPs ÷ 10 × 10¹² FLOP/s = 4 × 10⁻³ s = 4 ms, i.e. at most 250 fps. At a realistic 30 % utilisation it is about 13 ms.
09

Reuse it instead of retraining it

YOLO itself is a transfer recipe: 20 conv layers pretrained on ImageNet at 224 × 224, then 4 new convs and 2 new dense layers trained for detection at 448 × 448; click blocks to freeze or train them.

Which recipe?

Your labelled images
Similar to VOC photos?
your classes C3

Training details from the paper

pretraining
first 20 convs + avg-pool + FC on ImageNet 1000-class, 224 × 224, ≈ 1 week, 88 % top-5 (single crop)
detection
+ 4 conv + 2 FC (random init), input raised to 448 × 448
schedule
135 epochs on VOC 2007+2012, batch 64, momentum 0.9, weight decay 0.0005
learning rate
warm up 10⁻³ → 10⁻², 10⁻² for 75 epochs, 10⁻³ for 30, 10⁻⁴ for 30
regularise
dropout 0.5 after FC1; random scaling and translation up to 20 %; exposure and saturation × up to 1.5 in HSV
You retarget v1 to 3 classes (S = 7, B = 2). How many parameters does the new FC2 have?
Outputs = 49 · (10 + 3) = 637; params = 4,096 · 637 + 637 = 2,609,789. The original FC2 had 49 · 30 = 1,470 outputs and 6,022,590 parameters.
10

History: accuracy and speed on VOC 2007

Best reported VOC 2007 test results by year; switch to frames per second to see why 2016 was a break, and click a point for the story.
100%
click a point

Two-stage (Fast R-CNN) vs YOLO · tap a card to flip

In the paper's error analysis YOLO makes 4.75 % background errors vs 13.6 % for Fast R-CNN. What is the main reason?
A proposal classifier sees only the crop; YOLO's dense layers connect every output to the whole image. The same global view explains why combining the two (rescoring Fast R-CNN boxes with YOLO) raised Fast R-CNN from 71.8 to 75.0 mAP.
11

Where it is used today

Wherever a camera must be understood in real time on modest hardware, a YOLO-family detector is usually the first thing tried; click each row for the engineering detail.
Pedestrians, vehicles and signs at 30+ fps on embedded GPUs. Latency matters more than the last mAP point: an object 100 ms late at 50 km/h has moved 1.4 m. Typical choices: small variants, int8 inference, input sizes like 416 or 640.
Detection + tracking (e.g. SORT/DeepSORT-style association) for counting vehicles or people. The v1 weakness (one object per cell) shows up in dense crowds; multi-scale heads and anchors in later versions address it.
Counting fruit, detecting weeds for targeted spraying, spotting pests on leaves from drone or tractor cameras. Domain shift is large (outdoor light, occlusion), so fine-tuning with heavy augmentation is standard.
Polyp detection in endoscopy video, defect detection on production lines. Here recall at a fixed false-positive rate matters more than mAP@0.5, and IoU thresholds are often tuned per application.
Shelf monitoring, parcel and pallet detection, checkout-free stores. Many small, similar objects: the v1 grid would miss most of them; anchor-based multi-scale versions or higher input resolution are used.

SSD (2016)

One stage like YOLO, but predicts from several feature maps with default boxes: 74.3 mAP on VOC 2007 for SSD300 at real-time speed. Showed that multi-scale heads fix small objects.

YOLOv2 / v3 (2017–18)

Anchors, batch norm, fully convolutional heads, three scales and logistic class outputs. The v1 FC head and its ≈ 78 % of the parameters disappear.

RetinaNet (2017)

Focal loss down-weights easy background examples, a principled version of v1's λ_noobj = 0.5; it lets a one-stage detector match two-stage accuracy.

DETR (2020)

A transformer predicts a set of boxes with bipartite matching, so NMS is no longer needed. The “one object per cell” rule becomes “one object per query”.

A shelf camera must find 60 small, tightly packed products per image. Why is YOLO v1 (S = 7) a poor choice?
S² = 49 is a hard ceiling, and with one object per cell even fewer survive when centres cluster. Use a multi-scale, anchor-based successor or a finer grid.
12

Key takeaways

Eight sentences to remember; click each for the evidence on this page.
7 × 7 × 30 for VOC: 49 cells × (2 boxes × 5 + 20 classes). One network evaluation, no proposals. Section 04.
x, y are offsets inside that cell; w, h are relative to the image. Among its B predictors, the one with the highest IoU is trained on the box. Section 03.
The square roots make the cost of a width error scale like 1/w; the λ's stop the ~95 empty predictors from dominating. Section 04 derivation.
Thresholding this score and running greedy NMS gives the final detections; NMS adds 2–3 mAP for v1. Section 03.
Less accurate than Faster R-CNN (73.2 mAP at 7 fps) but the first real-time detector above 60 mAP. Section 01.
FC1 alone is 50,176 × 4,096 + 4,096 = 205,524,992 parameters. Later versions drop it for a 1 × 1 conv head. Section 06.
Global context: 4.75 % background vs 13.6 % for Fast R-CNN; coarse 7 × 7 features: 19.0 % localisation vs 8.6 %. Section 10.
Flocks of birds and crowded shelves break v1. Anchors, finer grids and multi-scale heads (v2, v3, SSD) remove the limit. Sections 04 and 11.
13

Check your understanding

Five derivation and what-if questions with instant feedback; click a dot to jump to a question.
0 / 5
answer all five
■ STAMPED · YOLO BLUEPRINT · ADVANCED
14

Glossary

Every term used on this page; type to filter and click a term to open its definition.