The whole process on one sheet
Step by step
In plain words
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.
The loss, term by term
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.
The gradient through the head
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.
Complexity with formulas
| layer | k / s / p | output | weights | MACs | activations |
|---|
Design choices, training details and ablations from the paper
| choice | value | why |
|---|---|---|
| grid S · boxes B · classes C | 7 · 2 · 20 | output 7 × 7 × 30; at most 49 objects, one class vector per cell |
| input | 448 × 448 | detection needs finer detail than the 224 × 224 pre-training |
| activation | leaky ReLU, 0.1 | all layers except the last, which is linear |
| λcoord · λnoobj | 5 · 0.5 | re-balance sum-squared error toward localisation |
| box size target | √w, √h | small boxes penalised more for the same error |
| pre-training | 20 conv, ImageNet, ≈ 1 week, 88 % top-5 | then 4 conv + 2 FC added with random weights |
| optimiser | SGD, batch 64, momentum 0.9, decay 0.0005 | 135 epochs on VOC 2007 + 2012 train/val |
| learning rate | 10⁻³ → 10⁻², then 75 · 30 · 30 epochs at 10⁻² · 10⁻³ · 10⁻⁴ | starting high diverges |
| regularisation | dropout 0.5 after FC1 | plus augmentation below |
| augmentation | scale and shift ±20 %, exposure and saturation ×1.5 (HSV) | 16.5 k images are few for 271.7 M weights |
| post-processing | NMS | adds 2–3 % mAP |
| result (VOC 2007 test unless noted) | mAP | fps |
|---|---|---|
| Fast YOLO (9 conv layers, fewer filters) | 52.7 | 155 |
| YOLO (24 conv layers) | 63.4 | 45 |
| YOLO with a VGG-16 backbone | 66.4 | 21 |
| Fast R-CNN | 70.0 | 0.5 |
| Faster R-CNN, VGG-16 | 73.2 | 7 |
| Fast R-CNN rescored by YOLO | 75.0 | — |
| YOLO, VOC 2012 test | 57.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).
Variants and successors, with their trade-offs
| model | year | what changed | trade-off |
|---|---|---|---|
| Fast YOLO | 2016 | 9 conv layers instead of 24, fewer filters | 3.4 × faster, 10.7 mAP lower |
| YOLOv2 / YOLO9000 | 2017 | batch norm, no FC head (fully convolutional), 5 anchor boxes from k-means, σ-bounded offsets, 13 × 13 grid at 416, multi-scale training, Darknet-19 | 76.8 mAP at 67 fps (416), 78.6 at 40 fps (544); class per anchor instead of per cell |
| YOLOv3 | 2018 | Darknet-53 with residual blocks, predictions at 3 scales, 9 anchors, independent logistic class scores | much better on small objects; heavier backbone |
| YOLOv4 | 2020 | CSPDarknet-53, SPP + PANet neck, Mosaic augmentation, CIoU loss | “bag of freebies”: accuracy from training tricks at the same inference cost |
| YOLOv5 → YOLOv8 | 2020–23 | PyTorch code base, auto-anchors, later anchor-free decoupled heads | easy to train and deploy; design choices documented in code more than papers |
| YOLOX | 2021 | anchor-free, decoupled classification/regression head, SimOTA label assignment | replaces the hard “one cell, best IoU” rule with an optimal-transport assignment |
| YOLOv10 | 2024 | consistent dual assignment so one box per object is trained directly | no NMS at inference: lower latency and no NMS threshold to tune |
Reference implementation of the key block (PyTorch-style)
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.
All 26 steps in one table
| letter | step | input | output | key figure |
|---|