YOLO (You Only Look Once) is an object detection method that divides an image into an S×S grid and regresses each cell's box coordinates, confidences, and class probabilities all at once with a single convolutional neural network. It was proposed in 2016 by Redmon et al. of the University of Washington (CVPR 2016). As the name says, it looks at the image only once and answers what is where.
Earlier detectors repurposed classifiers for detection. The R-CNN family generates region proposals, classifies each proposal, and refines the boxes in post-processing. Because each component is trained separately, these pipelines were slow and hard to optimize as a whole. YOLO solves the problem from image pixels to box coordinates and class probabilities as a single regression problem and trains the whole thing jointly for detection performance.
The main results of the paper are as follows:
On PASCAL VOC 2007 test, it reaches 63.4% mAP at 45 images per second (Titan X, no batching). The smaller Fast YOLO reaches 52.7% at 155 fps.
Its errors of mistaking background for objects were about one third of those of Fast R-CNN. Using this property to rescore Fast R-CNN's detections with YOLO raised mAP from 71.8% to 75.0%.
On the task of detecting people in artwork after training on natural photos, its accuracy dropped less than that of R-CNN and DPM.
On the other hand, it made many localization errors, especially for small objects, and its accuracy fell short of the two-stage detectors of the time. YOLO's form of "predicting from the whole image in one pass" was inherited by one-stage detectors such as SSD and by later improved versions of YOLO.
The problem: making detection a single regression
The problem YOLO tackled is that detection pipelines were split into many components, making them slow and impossible to optimize jointly.
According to the paper, R-CNN generates proposals with Selective Search, extracts features with a CNN, scores them with SVMs, refines boxes with a linear model, and removes duplicates with non-maximum suppression. Each component has to be tuned separately, and testing took over 40 seconds per image. Faster R-CNN is faster, but still runs at 7 images per second (VGG-16), short of real time (30 or more images per second).
Rather than speeding up each component, YOLO replaced the detection pipeline itself with a single network. This form has the following advantages:
Fast: At test time, the image only needs to pass through the network once.
Predicts from the whole image: Unlike methods that look only at proposal regions, it sees the whole image during both training and testing, so it can use the context around objects as clues.
Generalizes well: It learns objects' sizes, shapes, and typical locations, so its accuracy drops less on image types different from those it was trained on.
As an everyday analogy, the R-CNN family is like "examining each suspicious spot in a room one at a time with a magnifying glass." YOLO is like "glancing at the whole room once and saying what is where, all together."
Theory: the grid and the output tensor
YOLO turns detection into regression of a fixed-size tensor by dividing the image into an S×S grid and making the cell that contains an object's center responsible for that object. In the figure at the top of the article, the left shows the overall flow and the right shows the contents of the output tensor.
Each cell outputs two kinds of values:
B boxes: 5 values per box, x,y,w,h and a confidence. (x,y) is the box center as a position within the cell (0 to 1), and w,h are fractions of the whole image.
C class probabilities: the conditional probabilities Pr(Classi∣Object) given that the cell contains an object. Only one set is output per cell, regardless of the number of boxes B.
The output is an S×S×(B⋅5+C) tensor. For PASCAL VOC, S=7, B=2, and C=20, giving 7×7×30.
The confidence is defined as follows, as a value that expresses both whether the box contains an object and how accurate the box is:
Confidence=Pr(Object)×IoUpredtruth
If the cell contains no object, the confidence target is 0; otherwise it is the IoU (the overlap ratio of two boxes) between the predicted box and the ground-truth box. At test time, the class probabilities are multiplied by the box confidence to give a per-box, per-class score.
This score includes both the probability that the class appears in the box and how well the box fits the object.
The network processes one image as follows:
Resize the image to 448×448.
Pass it through 24 convolutional layers modeled on GoogLeNet. Instead of Inception modules, it stacks pairs that first reduce channels with a 1×1 convolution, as in Network In Network, and then apply a 3×3 convolution, producing a 7×7×1024 feature map.
Pass it through 2 fully connected layers (4096 dimensions and the 7×7×30 output). Only the last layer uses a linear activation; the other layers use Leaky ReLU with slope 0.1.
Compute class-specific scores for each of the 98 (7×7×2) boxes, filter them with a threshold, and remove duplicates with non-maximum suppression.
The smaller Fast YOLO uses 9 convolutional layers and fewer filters. All other training and testing settings are the same.
Because of the grid partition, an object is usually handled by only one cell, so box predictions are spread across the image. Large objects or objects on cell boundaries may be predicted by multiple cells, and non-maximum suppression helps in those cases. According to the paper, non-maximum suppression adds 2 to 3 points of mAP, but it is not as essential as it is for R-CNN or DPM.
Training: loss and settings
YOLO training pretrains the convolutional layers on ImageNet and then minimizes the squared error over the entire output tensor, weighted to suit object detection.
Pretraining and switching to detection
Attach an average pooling layer and a fully connected layer to the first 20 convolutional layers in the figure, and train on ImageNet 1000-class classification for about a week (224×224, 88% top-5 accuracy on the validation data).
Add 4 convolutional layers and 2 fully connected layers with randomly initialized weights.
Because detection needs fine-grained information, train with the input raised from 224×224 to 448×448.
The loss is based on the sum of squared errors over all output values. Squared error is easy to optimize, but used as is it has two mismatches with detection, which the paper fixes as follows:
Too many cells contain no object: The confidences of many cells are pushed toward 0, overpowering the gradients from cells that contain objects and sometimes causing training to diverge early. So the box coordinate loss is multiplied by λcoord=5, and the confidence loss for boxes without objects by λnoobj=0.5.
Errors in large and small boxes are treated the same: The same deviation affects IoU more for a small box. So instead of the width and height themselves, the network predicts their square roots.
A cell outputs B boxes, but during training each object is assigned to only one box. The responsible box is the one among the cell's boxes with the highest current IoU with the ground-truth box. The paper explains that this lets the boxes specialize in different sizes and aspect ratios, improving recall.
1iobj indicates whether cell i contains an object (center), and 1ijobj indicates whether the j-th box of cell i is responsible for that object. Ci is the confidence and pi(c) is the class probability. Class probability errors are counted only in cells that contain objects, and coordinate errors only for boxes responsible for an object (this applies the idea of mean squared error with weights that vary by output location).
Training settings (PASCAL VOC)
Train for about 135 epochs on the train and validation data of VOC 2007 and 2012. Batch size 64, momentum 0.9, weight decay 0.0005.
During the first few epochs, the learning rate is raised slowly from 10−3 to 10−2 (warmup), because starting at a high learning rate often makes the gradients unstable and causes divergence. After that, train for 75 epochs at 10−2, 30 epochs at 10−3, and 30 epochs at 10−4.
To prevent overfitting, a Dropout layer with rate 0.5 is placed after the first fully connected layer. For data augmentation, random scaling and translation of up to 20% of the original image size are applied, and exposure and saturation are randomly adjusted by up to a factor of 1.5 in HSV color space.
Squared error does not perfectly match the goal of maximizing average precision (mAP). The paper itself lists as limitations that weighting localization error equally with classification error is not ideal, and that square roots alone do not sufficiently distinguish errors in large and small boxes. YOLO's main source of error is incorrect localization.
Why it is fast, and what errors it makes
YOLO's properties can be summarized as follows from the paper's error analysis (VOC 2007 test, compared with Fast R-CNN):
Fast because the network runs only once: There are 98 boxes per image, far fewer than about 2000 from Selective Search, and there is no per-proposal computation. According to the paper, it can process video in real time with less than 25 milliseconds of latency.
Few background mistakes: Among the top detections, the fraction that mistook background for objects was 4.75% for YOLO versus 13.6% for Fast R-CNN. The paper explains that predicting from the whole image lets it use the surrounding context as a clue.
Many localization errors: "Localization errors," with the correct class and an IoU of 0.1 to 0.5, were 19.0% for YOLO versus 8.6% for Fast R-CNN, more than all of YOLO's other errors combined.
Robust to other image types because it learns objects' shapes and layout: Artwork and photos differ greatly at the pixel level, but the sizes and shapes of objects are similar. The paper argues that YOLO learns these, so it can still place boxes well in artwork.
Error type (share of top detections)
Fast R-CNN
YOLO
Correct
71.6%
65.5%
Localization error
8.6%
19.0%
Confusion with a similar class
4.3%
6.75%
Confusion with another class
1.9%
4.0%
Background error
13.6%
4.75%
If two detectors make different kinds of errors, combining them lets each compensate for the other. For each box output by Fast R-CNN, the paper checked whether YOLO predicted a similar box, and if so, boosted the score based on YOLO's probability and the overlap between the two boxes. Combining Fast R-CNN models with each other raised mAP by only 0.3 to 0.6 points, whereas combining with YOLO raised it by 3.2 points.
Experimental results
PASCAL VOC 2007 test: speed and accuracy (Titan X)
Method
Training data
mAP %
fps
100Hz DPM
2007
16.0
100
30Hz DPM
2007
26.1
30
Fast YOLO
2007+2012
52.7
155
YOLO
2007+2012
63.4
45
Fastest DPM
2007
30.4
15
R-CNN Minus R
2007
53.5
6
Fast R-CNN
2007+2012
70.0
0.5
Faster R-CNN (VGG-16)
2007+2012
73.2
7
Faster R-CNN (ZF)
2007+2012
62.1
18
YOLO (VGG-16)
2007+2012
66.4
21
The top 4 rows are real-time (30 fps or faster) detectors. Fast YOLO had more than twice the mAP of earlier real-time detectors. YOLO with a VGG-16 backbone is more accurate but does not reach real time.
Combining with Fast R-CNN (VOC 2007 test, mAP %; the best Fast R-CNN alone scores 71.8%)
Combined with
Its mAP alone
Combined mAP
Gain
Fast R-CNN (trained on 2007 data)
66.9
72.4
0.6
Fast R-CNN (VGG-M)
59.2
72.4
0.6
Fast R-CNN (CaffeNet)
57.1
72.1
0.3
YOLO
63.4
75.0
3.2
On PASCAL VOC 2012 test, YOLO's mAP was 57.9%, close to R-CNN with VGG-16 (59.2%). For classes with many small objects, such as bottle, sheep, and tv/monitor, it was 8 to 10 points lower than R-CNN and Feature Edit, while it was higher for cat and train. Fast R-CNN + YOLO scored 70.7%, 2.3 points above Fast R-CNN alone (68.4%), placing 4th on the public leaderboard at the time.
Detecting people in artwork (AP % for the person class; trained on VOC 2012 for Picasso and VOC 2010 for People-Art)
Method
VOC 2007
Picasso
People-Art
YOLO
59.2
53.3
45
R-CNN
54.2
10.4
26
DPM
43.2
37.8
32
R-CNN achieves high AP on photos, but because it relies on Selective Search, which is tuned for photos, its AP dropped sharply on artwork. YOLO had the smallest drop.
Practical considerations
When using YOLO, keep in mind the following limitations listed in the paper:
Weak on small objects that appear in groups: Each cell can output only 2 boxes and one class, which strongly limits the number of nearby objects it can predict. Scenes with clusters of small objects, such as flocks of birds, are difficult.
Weak on objects with unfamiliar aspect ratios or configurations: Because box shapes are learned from data, it generalizes poorly to objects with aspect ratios not seen in the training data.
Predicts boxes from coarse features: The input is downsampled many times, so boxes are predicted from a coarse 7×7 feature map, which leads to many localization errors.
Fixed input size: Because there are fully connected layers at the end, images of sizes other than 448×448 cannot be fed in directly.
Besides the original 2016 version covered in this article, "YOLO" has many improved versions that inherit the same name, each with different architectures (with or without anchors, number of feature map levels, and so on) and different losses. When comparing numbers or settings from papers, always check which version is meant. Also, torchvision has no built-in YOLO model, so either implement it as described in the paper or use the official implementation of each version.
Comparison with other methods
YOLO is one of the earliest representative one-stage detectors, with no proposal stage. Placing them side by side from the same perspective gives the following (times are the values from each paper and use different GPUs, so treat them as rough guides):
A Transformer outputs a fixed number of boxes as a set
100
― (evaluated on COCO)
YOLO and SSD differ mainly in two ways:
Feature maps used for prediction: YOLO uses only the single top feature map, while SSD uses 6 maps of different sizes. The SSD paper attributes its accuracy gap on small objects and objects of varying sizes to this.
Prediction layers: YOLO outputs boxes from the whole image with fully connected layers, which lets it use the context of the whole image but loses localization precision. SSD predicts from each location with convolutions, using default boxes of different aspect ratios as references.
Rough guidelines for choosing:
Understanding the mechanism, or a starting point for one-stage detectors: The original YOLO has a simple output tensor and loss, making it good for learning.
Both speed and accuracy needed: One-stage detectors that use feature maps of multiple sizes, like SSD, or later improved versions of YOLO are candidates.
Prioritizing localization precision and small objects: Two-stage detectors such as Faster R-CNN combined with FPN are a good fit.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import batched_nms
'''
A small implementation of YOLO (the original version) built as in Figure 3 and Equation (3) of the paper. torchvision has no built-in YOLO model.
Output is (batch, 7, 7, 30). The 30 values per cell are box 1 (x, y, √w, √h, confidence), box 2 (same), and 20 class probabilities
'''
S, B, C = 7, 2, 20 # grid size, boxes per cell, number of classes (PASCAL VOC)
def conv(c_in, c_out, k, stride=1):
return [nn.Conv2d(c_in, c_out, k, stride, k // 2), nn.LeakyReLU(0.1)] # activation is Leaky ReLU with slope 0.1 (Eq. 2)
class YOLOv1(nn.Module):
def __init__(self):
super().__init__()
pool = lambda: nn.MaxPool2d(2, 2)
layers = conv(3, 64, 7, 2) + [pool()] # 448 → 112
layers += conv(64, 192, 3) + [pool()] # → 56
layers += conv(192, 128, 1) + conv(128, 256, 3) + conv(256, 256, 1) + conv(256, 512, 3) + [pool()] # → 28
for _ in range(4):
layers += conv(512, 256, 1) + conv(256, 512, 3)
layers += conv(512, 512, 1) + conv(512, 1024, 3) + [pool()] # → 14
for _ in range(2):
layers += conv(1024, 512, 1) + conv(512, 1024, 3)
layers += conv(1024, 1024, 3) + conv(1024, 1024, 3, 2) # → 7
layers += conv(1024, 1024, 3) + conv(1024, 1024, 3) # 24 convolutional layers in total
self.features = nn.Sequential(*layers)
self.head = nn.Sequential(
nn.Flatten(),
nn.Linear(1024 * S * S, 4096), nn.LeakyReLU(0.1),
nn.Dropout(0.5), # after the first FC layer (disabled by model.eval())
nn.Linear(4096, S * S * (B * 5 + C)), # the last layer is linear
)
def forward(self, x): # x: (N, 3, 448, 448)
return self.head(self.features(x)).view(-1, S, S, B * 5 + C)
def grid_offsets(device, dtype):
g = torch.arange(S, device=device, dtype=dtype)
gy, gx = torch.meshgrid(g, g, indexing='ij')
return gx, gy
def iou(a, b): # (..., 4) = (cx, cy, w, h), as fractions of the image
a1, a2 = a[..., :2] - a[..., 2:] / 2, a[..., :2] + a[..., 2:] / 2
b1, b2 = b[..., :2] - b[..., 2:] / 2, b[..., :2] + b[..., 2:] / 2
inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(min=0).prod(-1)
return inter / (a[..., 2:].prod(-1) + b[..., 2:].prod(-1) - inter + 1e-9)
def yolo_loss(pred, target, lambda_coord=5.0, lambda_noobj=0.5):
'''
pred: (N, S, S, B*5 + C)
target: (N, S, S, 5 + C) = (x, y, w, h, objectness) and one-hot classes.
x, y are positions within the cell (0 to 1); w, h are fractions of the image. Only cells containing an object center have values
'''
boxes = pred[..., :B * 5].view(*pred.shape[:3], B, 5)
bx, by, bw, bh, conf = boxes.unbind(-1) # bw, bh predict √w, √h
tx, ty, tw, th, obj = target[..., :5].unbind(-1)
gx, gy = grid_offsets(pred.device, pred.dtype)
# responsible box (1^obj_ij): among the B boxes of the cell, the one with the highest IoU with the ground truth
pred_img = torch.stack([(bx + gx[..., None]) / S, (by + gy[..., None]) / S, bw ** 2, bh ** 2], -1)
true_img = torch.stack([(tx + gx) / S, (ty + gy) / S, tw, th], -1)[..., None, :]
ious = iou(pred_img, true_img) # (N, S, S, B)
resp = F.one_hot(ious.argmax(-1), B).to(pred.dtype) * obj[..., None]
noobj = 1 - resp
coord = (bx - tx[..., None]) ** 2 + (by - ty[..., None]) ** 2 \
+ (bw - tw.sqrt()[..., None]) ** 2 + (bh - th.sqrt()[..., None]) ** 2
loss = lambda_coord * (resp * coord).sum() # coordinates (width and height compared as square roots)
loss = loss + (resp * (conf - ious.detach()) ** 2).sum() # confidence of responsible boxes is pushed toward the IoU
loss = loss + lambda_noobj * (noobj * conf ** 2).sum() # confidence of non-responsible boxes is pushed toward 0
loss = loss + (obj[..., None] * (pred[..., B * 5:] - target[..., 5:]) ** 2).sum() # classes only for cells containing an object
return loss / pred.shape[0]
@torch.no_grad()
def decode(pred, score_thresh=0.2, iou_thresh=0.5):
'''Build detections from one image's (S, S, B*5 + C). The thresholds are examples, since the paper does not state them'''
boxes = pred[..., :B * 5].view(S, S, B, 5)
gx, gy = grid_offsets(pred.device, pred.dtype)
cx = (boxes[..., 0] + gx[..., None]) / S
cy = (boxes[..., 1] + gy[..., None]) / S
w, h = boxes[..., 2] ** 2, boxes[..., 3] ** 2
xyxy = torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], -1).view(-1, 4)
# class-specific score = Pr(Class | Object) × confidence (Eq. 1)
scores = (pred[..., None, B * 5:] * boxes[..., 4:5]).view(-1, C) # (98, 20)
best, labels = scores.max(-1)
keep = best > score_thresh
xyxy, best, labels = xyxy[keep], best[keep], labels[keep]
keep = batched_nms(xyxy, best, labels, iou_thresh) # per-class non-maximum suppression
return xyxy[keep], labels[keep], best[keep]
model = YOLOv1()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9, weight_decay=0.0005)
# learning rate: raise from 1e-3 to 1e-2 over the first few epochs, then 75 epochs at 1e-2, 30 at 1e-3, 30 at 1e-4 (Section 2.2 of the paper)
def lr_factor(epoch, warmup=5):
if epoch < warmup:
return 10 ** (epoch / warmup) # ×1 → ×10 (1e-3 → 1e-2)
epoch -= warmup
return 10.0 if epoch < 75 else 1.0 if epoch < 105 else 0.1
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_factor)
# example of one step (data loading and augmentation omitted; batch size is 64 in the paper)
images = torch.randn(2, 3, 448, 448)
target = torch.zeros(2, S, S, 5 + C)
target[0, 3, 3, :5] = torch.tensor([0.4, 0.6, 0.3, 0.5, 1.0]) # one object in the center cell
target[0, 3, 3, 5 + 11] = 1.0 # class 11 (dog)
model.train()
loss = yolo_loss(model(images), target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # disable Dropout
boxes, labels, scores = decode(model(images[:1])[0])
FAQ
Q. What does YOLO's 7×7×30 output represent?
A.
It is the 30 values output by each cell when the image is divided into a 7×7 grid. They consist of x,y,w,h and a confidence for each of 2 boxes (2×5=10 values) and the conditional probabilities of 20 classes (20 values). With the PASCAL VOC settings (S=7, B=2, C=20), S×S×(B⋅5+C)=7×7×30.
Q. Why is YOLO weak on small objects?
A.
Because each cell can output only 2 boxes and one set of classes, it cannot predict all of them when small objects are clustered together. Also, boxes are predicted from coarse 7×7 features after the input has been downsampled many times, so localization is hard to get precise. Another factor is that for small boxes, even a slight deviation lowers IoU considerably.
Q. What is the difference between YOLO and SSD?
A.
Both are one-stage detectors with no proposal stage, but YOLO outputs 98 boxes from the single top feature map using fully connected layers, while SSD outputs 8732 boxes with convolutions at each location of 6 feature maps of different sizes, for each default box of a different aspect ratio. In the SSD paper, on VOC 2007 test, SSD300 scored 74.3% (59 fps) versus YOLO's 63.4% (45 fps).