Sub topic 4
The YOLO idea: detection in a single pass
This chapter explains how YOLO ("You Only Look Once") turns detection into one forward pass through a network. It assumes you know Python, how convolutional neural networks (CNNs) classify images, and the box formats and intersection over union (IoU) from earlier chapters. Later chapters cover decoding the raw output, non-maximum suppression, and the network's internal structure. Here we build the working model.
Why single-pass detection matters
A classifier answers one question per image: what is in it? A detector must answer three questions for each object: what is it, where is it, and how sure are you? The number of objects is unknown in advance, so the output size cannot be fixed by the image alone.
Earlier detectors handled this in two stages:
- A region proposal step suggested several thousand boxes that might contain an object.
- A second network classified each proposal and refined its box.
This works well, but the second stage runs once per proposal. Speed depends on how many proposals there are, and the stages are hard to optimize as one system.
YOLO removes the proposal stage. One network looks at the whole image once and predicts every box, class and score together. This is called a single-stage detector. It trains end to end with one loss, and its run time is nearly constant for a given input size.
The grid idea
The original YOLO idea is to divide the image into a grid of cells. Each cell is responsible for objects whose center falls inside it. For each cell the network predicts:
- Box values: where the object is, relative to the cell, and how wide and tall it is.
- A confidence value: how likely it is that a box here contains an object, and how well the box fits.
- Class scores: how likely each class is, given that an object is present.
Consider a 640x640 image and a grid with a spacing of 32 pixels. The grid has 20x20 = 400 cells. A dog whose center is at pixel (330, 250) falls into column 10 and row 7, because 330 / 32 is about 10.3 and 250 / 32 is about 7.8. That cell is the one trained to predict the dog.
Every cell produces predictions in parallel. Most cells see only background, and the network learns to give them a low confidence. A cell with an object gives a high confidence plus a box. Because the whole prediction is one tensor (a multi-dimensional array), a single forward pass fills it.
Several scales
A single grid has a problem. A coarse grid of 20x20 cells handles large objects well, but a small object such as a distant bird may be smaller than one cell. Modern YOLO models therefore predict on several grids at once, typically with strides of 8, 16 and 32 pixels. The stride is the number of input pixels between neighboring cells.
| Stride | Grid size for a 640x640 input | Cells | Best suited to |
|---|---|---|---|
| 8 | 80x80 | 6,400 | Small objects |
| 16 | 40x40 | 1,600 | Medium objects |
| 32 | 20x20 | 400 | Large objects |
The total is 8,400 candidate predictions for a 640x640 image. Models that predict extra boxes per cell (anchors) have more candidates. That count is a useful number to remember when you inspect raw outputs.
How a prediction is shaped
Earlier YOLO versions (v1 to v7) used anchor boxes. An anchor is a preset box shape, such as tall and thin or short and wide. Each cell predicted offsets from several anchors, so the network adjusted a good starting shape instead of inventing one.
Many newer versions, including YOLOv8, are anchor-free. Each cell predicts the box directly, as distances from the cell location to the four box edges. This removes the need to tune anchor sizes to your dataset. Another change in YOLOv8 is that it drops the separate objectness score. Each prediction holds only box values and per-class scores, and the class score also serves as confidence. Chapter details on decoding follow later, so keep the general picture: each candidate has a box and a score per class.
A candidate in a YOLOv8-style model with 80 classes is a vector of 4 box values plus 80 class scores, which is 84 numbers. All 8,400 candidates together form an output of shape 84 x 8400 for one image, before a batch dimension.
You can check this shape yourself. The following code runs a randomly initialized network, so the numbers are meaningless, but the shape is real. It needs the ultralytics and torch packages.
import torch
from ultralytics import YOLO
# Build the architecture from a config file, with no pretrained weights.
model = YOLO("yolov8n.yaml")
net = model.model.eval()
x = torch.zeros(1, 3, 640, 640) # a batch of one blank RGB image
with torch.no_grad():
out = net(x)
pred = out[0] if isinstance(out, (list, tuple)) else out
print(pred.shape) # torch.Size([1, 84, 8400])The printed shape confirms 4 + 80 = 84 values for each of 8,400 candidates.
Assigning predictions to objects
Training needs a rule that decides which candidates should predict which ground-truth object. If every candidate in the grid tried to predict every object, the signal would be noisy.
The basic rule: the candidate whose cell contains the object's center is responsible. Newer YOLO versions use more flexible assignment. They pick a handful of the best-matching candidates per object, judged by how well their predicted box overlaps the truth (IoU) and how well their class score matches. Candidates not assigned to any object are trained to predict background.
This design explains a behavior you will see in practice: several neighboring candidates often predict the same object with high confidence. Nothing in the single pass forces one winner. Non-maximum suppression, the next stage after the network, removes these duplicates.
What you gain and what you give up
Single-pass detection brings clear benefits:
- Speed: one forward pass gives real-time rates on a modern GPU, and small models can run on a CPU or an edge device.
- Simplicity: one network, one loss, one training run.
- Global context: the network sees the whole image, so it makes fewer background mistakes, such as calling a patch of sky an object because of local texture.
It also has costs:
- Dense duplicate predictions need post-processing.
- Very small or tightly packed objects can be missed because a limited number of cells cover them. Higher input resolution helps, at a cost in speed.
- Fixed grids and strides tie the model to a range of object sizes. Objects far outside that range are detected poorly.
Common mistakes
- Thinking the network outputs a list of objects. It outputs a fixed-size dense array, and a list of objects only appears after filtering.
- Assuming the number of detections is the number of grid cells. Most candidates are background and are discarded.
- Expecting a model trained at 640 pixels to work equally well on tiny objects in a large photo. Check object size in pixels after resizing.
- Mixing up the stride with the grid size. A larger stride means a coarser, smaller grid.
Exercise
A YOLOv8-style model with 10 classes runs on a 320x320 input and predicts at strides 8, 16 and 32. How many candidate predictions does it produce per image, and how many values describes each candidate?
Show answer
The grids are 320/8 = 40, 320/16 = 20 and 320/32 = 10 cells per side. The candidates total 40x40 + 20x20 + 10x10 = 1,600 + 400 + 100 = 2,100. Each candidate has 4 box values plus 10 class scores, so 14 values. The output shape is 14 x 2100 for one image.
Exercise
Why does a single-stage detector often produce several high-confidence boxes for one object, and which later step handles this?
Show answer
Neighboring candidates, in the same cell or in adjacent cells and scales, are all trained to fire for an object they overlap. Nothing in the one forward pass picks a single winner. Non-maximum suppression removes the lower-scoring boxes that overlap a higher-scoring box beyond an IoU threshold.