How do you do object detection in an image? maybe you preprocess image, extract features (CNN), try to find patterns, shapes and edges and generalise them into seeing what the object is... How does this work? How do kids see a car and decide if it's a car, more importantly, how did people teach this to a computer through the years?
before YOLO
traditional computer vision
Earlier approaches used hand-engineered features. Compute pixel gradients, build feature descriptors by hand, and feed them into classifiers like support vector machines (SVMs). None of this was data driven. Domain experts designed them from what they knew about edges, textures, and shapes. This is highly inefficient.
These hand-built features fail in complex scenes, such as CCTV footage with:
Dozens of objects
Heavy occlusion
Complex features
Real-time requirements (sliding window detectors run the classifier at every position and scale, which is expensive)
two-stage detectors: R-CNN & Faster R-CNN
Two-stage detection pipeline, deriving results from data:
The feature map encodes what's in the image. Stage 1 proposes where objects might be. Stage 2 refines those proposals and assigns class labels.
The problem with this is multi-stage pipeline is complex, you train it piece by piece, and it is too slow for real-time use (~5 fps on a GPU).
comparison: object detection methods (2014-2016)
Method
Year
Speed (fps)
mAP (%)
Pipeline Type
Proposals
Real-time?
R-CNN
2014
0.02
66.0
Two-stage
Selective Search (2000+)
❌
Fast R-CNN
2015
0.5
70.0
Two-stage
Selective Search
❌
Faster R-CNN
2015
7
73.2
Two-stage
RPN (300)
❌
Fastest DPM
2014
15
30.4
Sliding window
Dense sampling
❌
YOLOv1
2016
45
63.4
Single-stage
None
✅
why YOLO: the motivation
The core idea: treat object detection as a single regression problem.
Instead of:
Generate proposals → 2. Classify proposals
Yolo does:
Single network → Box detection + Category prediction at the same time
One forward pass, one loss, and the network sees the whole image at once, which gives it global context. Real-time speed (45+ fps vs ~5 fps for two-stage detectors) and pay for it with lower accuracy.
YOLO high level overview
Object detection as a single regression problem:
concept
Input: Image of any size (resized to 448×448)
Process: Divide image into S×S grid cells (S=7 in the paper)
Predict: For each grid cell, predict B bounding boxes and C class probabilities
Output: Tensor of shape S×S×(B×5+C)
why "you only look once"?
Sliding window approaches, like the deformable part model (DPM), run a classifier at every position. Two-stage detectors process thousands of region proposals. YOLO looks at the image once, in a single forward pass.
Figure: YOLO's single-stage detection pipeline. The network processes the entire image once and outputs bounding boxes and class predictions
Figure: The complete YOLO detection algorithm from input image to final predictions
the architecture
YOLO is a CNN. 24 convolutional layers for feature extraction, 2 fully connected (FC) layers at the end to produce the final output.
Early layers detect low-level stuff (edges, color patches). Deeper layers combine those into higher-level features (eyes, wheels, textures). The FC layers at the end take all of that and produce bounding box predictions.
Backbone (Feature Extraction):
24 convolutional layers with alternating 1×1 and 3×3 filters
4 max-pooling layers for spatial downsampling
Leaky ReLU (rectified linear unit) activation (for all layers except the last)
Convolutions extract spatial features and keep the spatial structure. But a stack of convolutions alone adds no non-linearity (More on this on my Hello World of Neural Network blog) So you put non-linear activations (Leaky ReLU) between layers. 1×1 convolutions cut the channel count and add non-linearity. 3×3 convolutions extract spatial features and downsample.
why leaky ReLU?
Standard ReLU: f(x) = max(0, x) → can cause "dying neurons" (always output 0)
Leaky ReLU: f(x) = x if x > 0 else 0.1*x → keeps a small gradient (0.1) for negative inputs, which prevents dead neurons
regularization techniques
Dropout (rate=0.5) after the first FC layer
Data augmentation (random scaling, translation, HSV (hue, saturation, value) adjustments)
Figure: Complete YOLOv1 network architecture with 24 convolutional layers and 2 fully connected layers
Figure: The full network from input (448×448×3) to output (7×7×30) tensor
how YOLO works
Take the image and lay a grid over it. The original YOLO uses a 7×7 grid. This divides the image into 49 cells.
Each grid cell gets a job. It's responsible for detecting any object whose center point falls within that cell.
Make a prediction for every cell. A single neural network looks at the whole image and spits out a prediction for each of the 49 grid cells. Each prediction answers three questions:
"Is an object's center in here? How confident am I?"
"If so, where is the bounding box for that object?"
"And what class is it (a dog, a person, a car)?"
That's it. One look, one pass through the network, and out comes a flood of predictions from all 49 cells at once. No proposals, no second stage. A direct mapping from image pixels to bounding boxes and class probabilities.
the grid system
Step 1: Divide the 448×448 image into a 7×7 grid (S=7 in the paper)
Each grid cell: 64×64 pixels (448/7 = 64)
Step 2: Assign responsibility
Each cell is responsible for detecting one object
Which object? The one whose center point falls into that cell
Figure: Image divided into 7×7 grid with object center points marked. Each cell is responsible for objects whose centers fall within it
Figure: Identifying which grid cell is responsible for each object based on center point location
Figure: Close-up view of how object center points determine grid cell responsibility
Figure: Computing the center point and assigning it to the appropriate grid cell
what does "responsible" mean?
If an object's center point falls into a grid cell, that cell must:
Predict the bounding box coordinates
Predict the confidence that an object is present
Predict the class probabilities
example
Person's center at (100, 200) → falls into grid cell (1, 3)
Horse's center at (300, 150) → falls into grid cell (4, 2)
Grid cell (1, 3) is responsible for detecting "person"
Grid cell (4, 2) is responsible for detecting "horse"
But there's a catch... a big one.
What happens if the center of two objects falls into the same grid cell? Imagine a person standing directly in front of a car.
YOLOv1's limitation: Each grid cell can only detect ONE object.
The original YOLO has this rule built in. Each cell proposes two bounding boxes (more on that below), but it can only output one set of class probabilities. Two objects in the same cell? The model ignores one.
This is YOLOv1's biggest weakness. It fails on crowds, flocks of birds, and anything with clustered small objects. For now: one cell, one vote.
YOLOv2 and later fix this with anchor boxes, which allow multiple detections per cell.
The maximum is 49 objects per image (7×7 grid).
bounding box format and encoding
Ground truth bounding box for person: (100, 200, 130, 202)
These are large absolute values
Hard for the network to predict directly
Solution: Make predictions relative to the grid cell
target encoding (ground truth → YOLO format)
For a bounding box with center (x, y), width w, height h:
Figure: 30-dimensional vector format with bounding box coordinates, confidence, and class probabilities
prediction vector
what does each grid cell predict?
Each grid cell outputs a 30-dimensional vector:
Bounding Boxes (B=2 boxes):
Box 1: (x₁', y₁', w₁', h₁', c₁), 5 values
Box 2: (x₂', y₂', w₂', h₂', c₂), 5 values
Where:
x', y' = center offset relative to top-left corner of grid cell (0 to 1)
w', h' = width/height relative to entire image (0 to 1)
c = objectness confidence = Pr(Object) × IOU_pred^truth (IOU = intersection over union, see the figure below)
IOU (intersection over union) measures how well two boxes overlap. Divide the area that the boxes share by the total area that they cover together. Identical boxes give 1. Boxes that do not touch give 0.
Figure: The ground truth box and the prediction are each 120 × 100. They share a 60 × 70 area, so IOU ≈ 0.21. The IOU section shows how to compute it.
Class Probabilities (C=20 for Pascal VOC):
[p₁, p₂, ..., p₂₀], 20 values
These are conditional probabilities: Pr(Class_i | Object)
"What is the probability of each class, given that an object exists in this cell?"
Total: 5×2 + 20 = 30 values per grid cell
For the entire image: 7×7×30 = 1,470 values
why predict 2 boxes per cell?
Objects come in different aspect ratios and sizes, so each cell predicts 2 boxes. During training, YOLO assigns each ground truth object to the box with the highest IOU with it.
At inference: We keep only the box with the highest confidence score for each cell.
understanding confidence score
The confidence c encodes two things:
Pr(Object): Probability that the box contains an object
IOU_pred^truth: How well the predicted box fits the object
text
c = Pr(Object) × IOU_pred^truth
Three scenarios:
No object in cell: c = 0
Object present, poor fit: c = low (e.g., 0.3)
Object present, good fit: c = high (e.g., 0.9)
Figure: How class probabilities are combined with objectness confidence to produce final class-specific confidence scores
Figure: Six ways that two boxes can overlap. The yellow dots mark the intersection corners from Step 1: the larger x₁, y₁ and the smaller x₂, y₂. The blue area is the intersection. The two boxes at the bottom right do not overlap, so the intersection is 0 (Step 2).
Figure: Two common bounding box representations: corner format (x₁,y₁,x₂,y₂) vs center format (x_center, y_center, w, h) and how to convert between them
IOU implementation
python
def iou(pred, gt): """ Calculate Intersection over Union between two bounding boxes. Args: pred: [x1, y1, x2, y2] predicted box gt: [x1, y1, x2, y2] ground truth box Returns: iou: float between 0 and 1 """ pred_x1, pred_y1, pred_x2, pred_y2 = pred gt_x1, gt_y1, gt_x2, gt_y2 = gt # Find intersection rectangle x_topleft = max(pred_x1, gt_x1) y_topleft = max(pred_y1, gt_y1) x_bottomright = min(pred_x2, gt_x2) y_bottomright = min(pred_y2, gt_y2) # Check if boxes overlap at all if x_bottomright < x_topleft or y_bottomright < y_topleft: return 0.0 # Calculate areas intersection = (x_bottomright - x_topleft) * (y_bottomright - y_topleft) pred_area = (pred_x2 - pred_x1) * (pred_y2 - pred_y1) gt_area = (gt_x2 - gt_x1) * (gt_y2 - gt_y1) union = pred_area + gt_area - intersection iou = intersection / union return iou
non-maximum suppression (NMS)
Multiple grid cells often detect the same object, so you get duplicate boxes. NMS keeps the highest-confidence box and removes the other boxes whose overlap with it is above a threshold.
NMS algorithm
For each class separately:
Sort all detections by confidence (descending)
Select the box with highest confidence
Remove all boxes with IOU > threshold (e.g., 0.5) with the selected box
Repeat until no boxes remain
Why per-class? We want to suppress duplicate detections of the same object, but not suppress a person detection because it overlaps with a car detection.
Picking NMS Threshold
The IOU threshold for NMS has a large effect on detection quality.
Threshold too low (e.g., 0.3):
Suppresses too many boxes
Misses objects that are close together
Example: two people standing next to each other → only one detected
Threshold too high (e.g., 0.7):
Suppresses too few boxes
Multiple boxes per object (duplicates)
Example: a single person gets 3 bounding boxes
0.5 is a common default:
Balances duplicate suppression and multi-object detection
In short, NMS keeps the best box and kills everything that overlaps too much with it. Repeat until nothing's left to suppress.
NMS implementation
python
def nms(detections, nms_threshold=0.5): """ Apply Non-Maximum Suppression to remove duplicate detections. Args: detections: list of [x1, y1, x2, y2, score] nms_threshold: IOU threshold for suppression Returns: keep_detections: filtered list of detections """ # Sort detections by score (descending) sorted_det = sorted(detections, key=lambda k: -k[-1]) keep_detections = [] while len(sorted_det) > 0: # Keep the highest confidence box best_box = sorted_det[0] keep_detections.append(best_box) # Remove this box and all boxes with high overlap sorted_det = [ box for box in sorted_det[1:] if iou(best_box[:-1], box[:-1]) < nms_threshold ] return keep_detections
metrics
Metric
Value
Comparison
Speed
45 fps (frames per second)
9× faster than Faster R-CNN
Accuracy
63.4% mAP (mean average precision)
-9.8 points vs Faster R-CNN (73.2%)
Grid Size
7×7 cells
49 possible detections
Parameters
~272M (~212M in the two FC layers)
Custom GoogLeNet-inspired backbone (the implementation below uses ResNet34)
Input Size
448×448
Fixed resolution
pipeline
Figure: YOLO's single-stage pipeline. One forward pass turns the image into 7×7×30 predictions. Post-processing then filters them.
training process
Training needs three things:
A target for each prediction. The labels are boxes in pixels, so we first convert each box to the 7×7×30 format. The target encoding section shows this conversion.
A loss: one number that tells how far the 7×7×30 prediction is from the 7×7×30 target. The loss function section builds it step by step.
An optimizer that changes the weights to make the loss smaller. YOLOv1 uses stochastic gradient descent (SGD) with momentum.
dataset: Pascal VOC
20 object classes
Training images: Pascal VOC 2007 + 2012 train and validation sets, approximately 16,500 images with bounding box annotations
Standard benchmark for object detection
two-stage training strategy
Why two stages? The network must first learn general visual features: edges, textures, parts of objects. 16,500 images are not sufficient to learn them from zero. ImageNet has approximately 1.2 million labeled images, so YOLOv1 learns the features there first and then trains for detection.
stage 1: pretraining (classification)
Task: image classification on ImageNet (1,000 classes)
Input size: 224×224
Network: the first 20 convolutional layers, then an average-pooling layer and one FC layer
Result: the paper reports approximately one week of training and 88% top-5 accuracy on the ImageNet 2012 validation set
stage 2: detection training
Task: object detection on Pascal VOC
Input size: 448×448
Network: keep the 20 pretrained layers, then add 4 convolutional layers and 2 FC layers with random weights
Why higher resolution? Detection needs fine detail to put a box in the correct position. Two times the side length gives four times the pixels.
training hyperparameters
Epochs: 135
Batch size: 64
Optimizer: SGD with momentum
Momentum: 0.9
Weight decay: 0.0005
Learning rate schedule (from the paper):
First epochs: increase from 10⁻³ to 10⁻² (the paper does not give the number of epochs)
Then 10⁻² for 75 epochs
Then 10⁻³ for 30 epochs
Then 10⁻⁴ for 30 epochs
Why warm-up? The paper reports that the model often diverges if training starts at a high learning rate, because the gradients are unstable.
data augmentation
To prevent overfitting:
Random scaling and translation: up to 20% of the original image size
Random exposure and saturation: up to a factor of 1.5 in the HSV color space. This helps with different light conditions.
The network gives 7×7×30 = 1,470 numbers. The target has the same shape. YOLO treats object detection as a regression problem: each output is a number, and we want it close to its target number.
The simplest loss is the sum of squared errors over all 1,470 numbers:
text
L = Σ (target − prediction)²
This loss is easy to optimize. But plain squared error has five problems for detection, and the YOLOv1 loss fixes each one:
Problem with plain squared error
Fix in YOLOv1
Each cell has 2 boxes, but only one box must learn the object
Train the coordinates of the responsible box only
An empty cell has no box and no class, so its coordinate and class targets mean nothing
No coordinate loss and no class loss for empty cells
Most boxes have no object, so their confidence errors are much larger in total than the rest
Multiply the empty-box confidence loss by λ_noobj = 0.5
A box error counts the same as a class error
Multiply the coordinate loss by λ_coord = 5
A 10-pixel error counts the same on a large box and a small box
Use √w and √h instead of w and h
Figure: The three parts of the YOLO loss. Localization: where is the box? Confidence: is there an object, and how well does the box fit it? Classification: which object is it?
notation
S = 7 is the grid size, so i goes over S² = 49 cells
B = 2 is the number of boxes per cell, so j goes over 2 boxes
𝟙ᵢᵒᵇʲ = 1 if the center of an object falls in cell i, else 0
𝟙ᵢⱼᵒᵇʲ = 1 if box j in cell i is responsible for that object, else 0. Of the 2 boxes in the cell, the responsible box is the box with the higher IOU with the ground truth.
𝟙ᵢⱼⁿᵒᵒᵇʲ = 1 if box j in cell i is not responsible for any object, else 0
A value with a hat (x̂, Ĉ, p̂) is a prediction. A value without a hat is a target.
1. localization loss (box regression)
Goal: make the predicted box coordinates close to the ground truth.
x, y = center offset inside the cell (0 to 1). w, h = box size as a fraction of the image (0 to 1). These are the values from target encoding.
𝟙ᵢⱼᵒᵇʲ makes the term 0 for all boxes except the responsible box. In an image with 2 objects, only 2 of the 98 boxes (49 cells × 2) get a coordinate loss.
λ_coord = 5: the paper says that plain squared error weights localization error the same as classification error, "which may not be ideal". λ_coord = 5 makes box errors count more.
Intuition: Why √w and √h?
The same absolute error matters more for a small object.
Now the small box error is ~8× larger in the loss → the network learns to be precise on small objects!
In the real loss, w and h are fractions of the image, not pixels. Division by the image size changes both errors by the same factor, so the ratio stays at ~8×.
2. confidence loss
Goal: train the confidence score to show two things:
Responsible box: Pr(Object) = 1, so C = IOU between the predicted box and the ground truth. The label vector in label encoding stores 1.0 to mark the object, and the loss multiplies it by this IOU.
All other boxes: Pr(Object) = 0, so C = 0.
Example: the responsible box has IOU = 0.9 with the ground truth and predicts confidence 0.6. Its loss is (0.9 − 0.6)² = 0.09.
Figure: Confidence loss. The target for a responsible box is Pr(Object) × IOU. If no object exists, the target is 0.
Why λ_noobj = 0.5? Count the boxes. The grid has 49 cells × 2 boxes = 98 boxes. In an image with 2 objects, 2 boxes are responsible and 96 are not. So 96 of the 98 confidence terms push toward 0. The paper says these terms often overpower the gradient from the cells with objects, and this can make training diverge early. λ_noobj = 0.5 halves each empty-box term.
λ_coord=5 says "getting box positions right matters a lot." λ_noobj=0.5 says "empty cells, chill out, you're not that important." The paper states both values but reports no ablation study for them.
3. classification loss
Goal: predict the correct class probabilities for cells that contain an object.
text
L_class = Σᵢ 𝟙ᵢᵒᵇʲ Σ_c (pᵢ(c) − p̂ᵢ(c))²
𝟙ᵢᵒᵇʲ = 1 if cell i contains an object. Empty cells get no class loss.
pᵢ(c) = target probability for class c: 1 for the correct class, 0 for the other 19
p̂ᵢ(c) = predicted probability for class c
This loss uses 𝟙ᵢᵒᵇʲ (per cell), not 𝟙ᵢⱼᵒᵇʲ (per box). Each cell predicts one set of class probabilities for its 2 boxes. This is why one cell can detect only one object.
Example: a cell contains a person. The target is 1 for person and 0 for the other 19 classes. The cell predicts person 0.8, dog 0.1, car 0.1 and 0 for the other classes:
False Positive (FP): Predicted box doesn't match any ground truth
False Negative (FN): Ground truth object that wasn't detected
precision and recall
With these numbers, we can ask two questions:
Precision: "Of the answers you gave, how many were right?"
Precision = TP / (TP + FP) = 6 / (6 + 2) = 75%
This measures how trustworthy the model's predictions are. A high precision model doesn't make many silly mistakes.
Recall: "Of all the things you should have found, how many did you find?"
Recall = TP / (TP + FN) = 6 / (6 + 4) = 60%
This measures how comprehensive the model is. A high recall model doesn't miss much.
The trade-off
Precision and recall fight each other.
Only predict when you're 100% sure? High precision, low recall. You miss stuff.
Predict aggressively on everything? High recall, low precision. Lots of garbage boxes.
so, what is mAP?
We want both. Average Precision (AP) captures this for a single class. AP is the area under the precision-recall curve. Higher AP means the model stays precise even as it tries to find more objects.
Precision-Recall Curve: Plot precision vs recall at different confidence thresholds.
Steps to calculate AP:
Sort all predictions by confidence
For each confidence threshold, compute precision and recall
Plot the curve
Compute area under curve
mAP = average AP across all classes. 20 classes? Compute AP for each, average them.
mAP@0.5: Use IOU threshold of 0.5 to determine TP
mAP@0.75: Use IOU threshold of 0.75 (stricter)
mAP@[0.5:0.95]: Average mAP across IOU thresholds from 0.5 to 0.95 in steps of 0.05
mAP Implementation
python
def compute_map(pred_boxes, gt_boxes, iou_threshold=0.5): """ Calculate mean Average Precision for object detection. Args: pred_boxes: List of predictions per image [{class: [[x1,y1,x2,y2,score], ...], ...}, ...] gt_boxes: List of ground truths per image [{class: [[x1,y1,x2,y2], ...], ...}, ...] iou_threshold: IOU threshold to consider a detection as TP Returns: mean_ap: Mean average precision across all classes all_aps: Dictionary of AP for each class """ # Get all class labels from ground truth gt_labels = set() for im_gt in gt_boxes: for cls_key in im_gt.keys(): gt_labels.add(cls_key) gt_labels = sorted(list(gt_labels)) all_aps = {} aps = [] # Compute AP for each class for label in gt_labels: # Collect all predictions for this class across all images cls_preds = [] for im_idx, im_pred in enumerate(pred_boxes): if label in im_pred: for box in im_pred[label]: cls_preds.append((im_idx, box)) # Sort predictions by confidence (descending) cls_preds = sorted(cls_preds, key=lambda k: -k[1][-1]) # Track which GT boxes have been matched gt_matched = [[False for _ in im_gts.get(label, [])] for im_gts in gt_boxes] # Count total GT boxes for this class (for recall) num_gts = sum([len(im_gts.get(label, [])) for im_gts in gt_boxes]) # Track TP and FP for each prediction tp = [0] * len(cls_preds) fp = [0] * len(cls_preds) # For each prediction, determine if TP or FP for pred_idx, (im_idx, pred_box) in enumerate(cls_preds): # Get GT boxes for this image and class im_gts = gt_boxes[im_idx].get(label, []) # Find best matching GT box max_iou_found = -1 max_iou_gt_idx = -1 for gt_box_idx, gt_box in enumerate(im_gts): gt_box_iou = iou(pred_box[:-1], gt_box) if gt_box_iou > max_iou_found: max_iou_found = gt_box_iou max_iou_gt_idx = gt_box_idx # TP only if IOU >= threshold AND GT box hasn't been matched yet if max_iou_found < iou_threshold or \ (max_iou_gt_idx >= 0 and gt_matched[im_idx][max_iou_gt_idx]): fp[pred_idx] = 1 else: tp[pred_idx] = 1 gt_matched[im_idx][max_iou_gt_idx] = True # Compute cumulative TP and FP tp = np.cumsum(tp) fp = np.cumsum(fp) # Compute precision and recall at each threshold recalls = tp / num_gts precisions = tp / (tp + fp) # Smooth precision curve (ensures precision is monotonic) # Add boundary values recalls = np.concatenate(([0.0], recalls, [1.0])) precisions = np.concatenate(([0.0], precisions, [0.0])) # Make precision monotonically decreasing for i in range(precisions.size - 1, 0, -1): precisions[i - 1] = np.maximum(precisions[i - 1], precisions[i]) # Compute AP as area under curve # Get points where recall changes i = np.where(recalls[1:] != recalls[:-1])[0] ap = np.sum((recalls[i + 1] - recalls[i]) * precisions[i + 1]) if num_gts > 0: aps.append(ap) all_aps[label] = ap else: all_aps[label] = np.nan mean_ap = sum(aps) / len(aps) if len(aps) > 0 else 0.0 return mean_ap, all_aps
performance and results
Figure: Performance comparison of YOLOv1 with other detection methods on Pascal VOC 2007 dataset
Figure: Detailed accuracy and speed metrics showing YOLO's speed lead at competitive accuracy
limitations of YOLOv1
One object per cell. Each cell predicts 2 boxes but only one set of class probabilities. So it detects at most 49 objects (7×7). It breaks on crowds: flocks of birds, dense crowds, or a dog and a bicycle whose centers land in the same cell. The model misses one of them.
Small objects. The 7×7 grid is coarse (each cell ≈ 64×64 px). Small objects give weak activations, and groups of them collide in one cell.
Unusual aspect ratios. The network learns aspect-ratio priors from the training data, so it misses long, thin, or oddly shaped objects (a limousine, a tall narrow doorway).
Localization. A coarse 7×7 feature map and no second-stage box refinement (unlike Faster R-CNN) mean looser boxes. Looser boxes hurt mAP at higher IOU thresholds.
Box-size sensitivity. Even with √w and √h, MSE still weights small and large box errors unevenly.
Class imbalance. Even with λ_noobj = 0.5, the ~20× more "no object" cells push confidence scores down, so the model still misses hard objects.
evolution: from v1 to v10
the YOLO family tree
Each version after v1 tried to fix its problems without killing the speed.
key improvements across versions
YOLOv2 (YOLO9000), 2017:
Anchor boxes: Instead of predicting boxes directly, predict offsets from predefined anchors
Batch normalization: Added to all conv layers, improved convergence
High-resolution classifier: Pretrain at 448×448 (not 224×224)
Multi-scale training: Train on different input sizes
Binary classification: Use logistic regression instead of softmax (allows multi-label)
Performance: 57.9% mAP@0.5, comparable to RetinaNet but 3-4× faster
YOLOv4, 2020:
Bag of freebies: Techniques that improve accuracy without increasing inference cost
Data augmentation (Mosaic, MixUp)
Label smoothing
DropBlock regularization
Bag of specials: Techniques with small inference cost increase
Mish activation
CSPNet backbone
SPP (Spatial Pyramid Pooling)
PANet (Path Aggregation Network) neck
Performance: 43.5% mAP@0.5:0.95 on COCO (Common Objects in Context) at ~65 fps, the best real-time result at the time
YOLOv5, 2020 (Ultralytics):
PyTorch implementation: Easier to use and customize
Auto-learning anchors: Cluster anchors from the training data with k-means
Model family: Nano, Small, Medium, Large, XLarge variants
Better augmentations: Albumentations integration
Export options: ONNX, TensorRT, CoreML, etc.
YOLOv6, v7, v8 (2022-2023): Incremental improvements. v6 (Meituan) focused on industrial deployment with a hardware-aware design. v7 introduced re-parameterized convolutions and a more efficient training pipeline. v8 (Ultralytics) went anchor-free and decoupled the classification and regression heads. All three pushed accuracy up a few points on COCO, but the next real architectural jump is v10.
YOLOv10, 2024:
NMS-free detection: Removes the need for NMS post-processing
Consistent matching strategy during training
Dual label assignment
Faster inference (no NMS step)
Efficiency optimizations:
Compact inverted block design
Partial self-attention
Spatial-channel decoupled downsampling
Model variants: N/S/M/B/L/X for different speed/accuracy trade-offs
Performance:
YOLOv10-X: ~54% mAP@0.5:0.95 on COCO
YOLOv10-N: Real-time on edge devices
key shifts across versions
v1→v2: Direct prediction → Anchor-based
v2→v3: Single-scale → Multi-scale detection
v3→v4: Darknet-53 → CSPDarknet53 plus bag-of-freebies and bag-of-specials
Single-stage detection: One network, one forward pass
Real-time performance: Speed is a primary goal
End-to-end training: Unified loss function
Practical focus: Easy to deploy and use
YOLOv10: the one I tried for production and scale
Two things matter in v10: NMS-free detection and a rethought architecture.
NMS-free training with dual heads
Earlier YOLO models output multiple overlapping boxes per object and then use NMS as post-processing. NMS adds latency and isn't differentiable, so you can't optimize it end-to-end. YOLOv10 gets rid of it. Since it's NMS free, the post processing CPU cost for code goes down heavily. Makes inference faster.
The trick is two detection heads during training:
One-to-Many (o2m) Head: Matches each ground truth object with multiple predictions. This gives a rich supervision signal from several locations for the same object.
One-to-One (o2o) Head: Matches each ground truth object with exactly one prediction. Learns to output one clean box per object.
Both heads use the same matching metric, so their supervision stays consistent. During training, the backbone and neck learn from the rich o2m signal, and the o2o head learns to output one clean prediction per object. At inference you drop the o2m head, so it costs nothing. You use the o2o head, pick the top-K class scores, filter by confidence, and you're done. No NMS needed.
With no NMS step, YOLOv10 has lower end-to-end latency than YOLOv8 at every size on COCO. The paper reports 10.70 ms vs 16.86 ms for X (37% less) and 1.84 ms vs 6.16 ms for N. Each object also gets one strong box.
comparison: YOLOv1 vs YOLOv10
Metric
YOLOv1 (2016)
YOLOv10 (2024)
mAP50
63.4% (VOC)
90.6% (ODN dataset)
mAP50-95
Not reported
76%
Speed (fps)
45 fps
~63 fps (40% faster than v8)
Grid Size
7×7 (fixed)
Multi-scale, adaptive
Boxes per Cell
2
Dynamic (o2o/o2m)
Max Objects
49 (7×7 grid limit)
300 (default top-k)
Post-processing
NMS required
NMS-free
Small Objects
Struggles
Excellent (multi-scale detection)
Architecture
24 conv + 2 FC
Efficient CSPNet + lightweight heads
Training
Single-head
Dual-head (o2m + o2o)
v1 proved single-stage detection works. v10 makes it end-to-end, with no post-processing and more speed. Same core idea, way more refined.
implementation: PyTorch code examples
Full PyTorch implementation of YOLOv1 below.
1. model architecture
This implementation swaps the original backbone for a ResNet34 (pretrained on ImageNet) and adds detection layers on top:
python
import torchimport torch.nn as nnimport torchvisionclass YOLOV1(nn.Module): """ YOLOv1 Implementation using ResNet34 backbone Args: img_size: Input image size (448x448) num_classes: Number of classes (20 for Pascal VOC) model_config: Configuration dict with S, B, and architectural params Output: Tensor of shape (batch_size, S, S, 5*B + C) """ def __init__(self, img_size, num_classes, model_config): super(YOLOV1, self).__init__() self.img_size = img_size self.S = model_config['S'] # Grid size (7x7) self.B = model_config['B'] # Boxes per cell (2) self.C = num_classes # Number of classes (20) # Load pretrained ResNet34 backbone (trained on ImageNet 224x224) backbone = torchvision.models.resnet34( weights=torchvision.models.ResNet34_Weights.IMAGENET1K_V1 ) # Feature extraction layers (before FC layers) self.features = nn.Sequential( backbone.conv1, # 7x7 conv, stride 2 backbone.bn1, backbone.relu, backbone.maxpool, backbone.layer1, # ResNet blocks backbone.layer2, backbone.layer3, backbone.layer4, # Output: 512 channels ) # Detection head: 3 conv layers for feature refinement yolo_conv_channels = model_config['yolo_conv_channels'] # 1024 leaky_relu_slope = model_config['leaky_relu_slope'] # 0.1 self.conv_layers = nn.Sequential( nn.Conv2d(512, yolo_conv_channels, 3, padding=1, bias=False), nn.BatchNorm2d(yolo_conv_channels), nn.LeakyReLU(leaky_relu_slope), nn.Conv2d(yolo_conv_channels, yolo_conv_channels, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(yolo_conv_channels), nn.LeakyReLU(leaky_relu_slope), nn.Conv2d(yolo_conv_channels, yolo_conv_channels, 3, padding=1, bias=False), nn.BatchNorm2d(yolo_conv_channels), nn.LeakyReLU(leaky_relu_slope) ) # Final 1x1 conv to get S*S*(5B+C) output self.final_conv = nn.Conv2d(yolo_conv_channels, 5 * self.B + self.C, 1) def forward(self, x): # x: (batch, 3, 448, 448) out = self.features(x) # (batch, 512, 14, 14) out = self.conv_layers(out) # (batch, 1024, 7, 7) out = self.final_conv(out) # (batch, 30, 7, 7) # Permute to (batch, S, S, 5B+C) out = out.permute(0, 2, 3, 1) # (batch, 7, 7, 30) return out
2. loss function
The complete YOLOv1 loss with all three components:
import torchimport albumentations as albimport cv2from torch.utils.data import Datasetclass VOCDataset(Dataset): """Pascal VOC Dataset with YOLO target encoding""" def __init__(self, split='train', img_size=448, S=7, B=2, C=20): self.split = split self.img_size = img_size self.S = S # Grid size self.B = B # Boxes per cell self.C = C # Number of classes # Data augmentation for training self.transforms = { 'train': alb.Compose([ alb.HorizontalFlip(p=0.5), alb.Affine(scale=(0.8, 1.2), translate_percent=(-0.2, 0.2)), alb.ColorJitter(brightness=(0.8, 1.2), saturation=(0.8, 1.2)), alb.Resize(self.img_size, self.img_size) ], bbox_params=alb.BboxParams(format='pascal_voc', label_fields=['labels'])), 'test': alb.Compose([ alb.Resize(self.img_size, self.img_size) ], bbox_params=alb.BboxParams(format='pascal_voc', label_fields=['labels'])) } # Load Pascal VOC annotations... # (XML parsing code omitted for brevity) def __getitem__(self, index): # Load image and annotations img_info = self.images_info[index] img = cv2.imread(img_info['filename']) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) bboxes = [det['bbox'] for det in img_info['detections']] # (x1,y1,x2,y2) labels = [det['label'] for det in img_info['detections']] # Apply augmentations transformed = self.transforms[self.split]( image=img, bboxes=bboxes, labels=labels ) img = transformed['image'] bboxes = torch.tensor(transformed['bboxes']) labels = torch.tensor(transformed['labels']) # Normalize image to [0, 1] img_tensor = torch.from_numpy(img / 255.0).permute(2, 0, 1).float() # --- Create YOLO target tensor --- target_dim = 5 * self.B + self.C yolo_target = torch.zeros(self.S, self.S, target_dim) h, w = img.shape[:2] cell_size = h // self.S # Pixels per grid cell if len(bboxes) > 0: # Convert (x1, y1, x2, y2) → (x_center, y_center, width, height) box_width = bboxes[:, 2] - bboxes[:, 0] box_height = bboxes[:, 3] - bboxes[:, 1] box_center_x = bboxes[:, 0] + 0.5 * box_width box_center_y = bboxes[:, 1] + 0.5 * box_height # Determine which grid cell each object belongs to grid_i = torch.floor(box_center_x / cell_size).long() grid_j = torch.floor(box_center_y / cell_size).long() # Compute relative coordinates within grid cell (0 to 1) box_x_offset = (box_center_x - grid_i * cell_size) / cell_size box_y_offset = (box_center_y - grid_j * cell_size) / cell_size # Normalize width and height to image size box_w_norm = box_width / w box_h_norm = box_height / h # Fill YOLO target tensor for idx in range(len(bboxes)): # Assign same target to all B boxes (model picks responsible one) for b in range(self.B): s = 5 * b yolo_target[grid_j[idx], grid_i[idx], s] = box_x_offset[idx] yolo_target[grid_j[idx], grid_i[idx], s+1] = box_y_offset[idx] yolo_target[grid_j[idx], grid_i[idx], s+2] = box_w_norm[idx].sqrt() yolo_target[grid_j[idx], grid_i[idx], s+3] = box_h_norm[idx].sqrt() yolo_target[grid_j[idx], grid_i[idx], s+4] = 1.0 # Confidence # One-hot encode class label = int(labels[idx]) yolo_target[grid_j[idx], grid_i[idx], 5*self.B + label] = 1.0 return img_tensor, yolo_target
4. training loop
Training loop:
python
import torchfrom torch.optim import SGDfrom torch.optim.lr_scheduler import MultiStepLRfrom torch.utils.data import DataLoader# Initialize model, loss, and datasetdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')model = YOLOV1(img_size=448, num_classes=20, model_config={ 'S': 7, 'B': 2, 'yolo_conv_channels': 1024, 'leaky_relu_slope': 0.1}).to(device)criterion = YOLOLoss(S=7, B=2, C=20)train_dataset = VOCDataset(split='train', img_size=448)train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)# Optimizer: SGD with momentum (as per paper)optimizer = SGD(model.parameters(), lr=0.001, momentum=0.9, weight_decay=5e-4)# Learning rate schedule: reduce at epochs [75, 105]# Paper uses warm-up from 1e-3 to 1e-2 for first epochs, then steps downscheduler = MultiStepLR(optimizer, milestones=[75, 105], gamma=0.1)# Training loopnum_epochs = 135 # As per papermodel.train()for epoch in range(num_epochs): epoch_loss = 0.0 for images, targets in train_loader: images = images.to(device) targets = targets.to(device) # Forward pass predictions = model(images) loss = criterion(predictions, targets) # Backward pass optimizer.zero_grad() loss.backward() optimizer.step() epoch_loss += loss.item() scheduler.step() print(f'Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss/len(train_loader):.4f}')
5. inference with NMS
Converting raw predictions to actual boxes:
python
def convert_predictions_to_boxes(predictions, S=7, B=2, C=20, conf_threshold=0.2, nms_threshold=0.5): """ Convert YOLO predictions to bounding boxes with NMS. Args: predictions: (S, S, 5*B + C) tensor conf_threshold: Minimum confidence to keep box nms_threshold: IOU threshold for NMS Returns: boxes: (N, 4) tensor in (x1, y1, x2, y2) format scores: (N,) confidence scores labels: (N,) class labels """ predictions = predictions.reshape(S, S, 5*B + C) # Get class predictions (same for all boxes in a cell) class_probs, class_labels = predictions[..., 5*B:].max(dim=-1) # Create coordinate shift grid shifts_x = torch.arange(S, device=predictions.device) / float(S) shifts_y = torch.arange(S, device=predictions.device) / float(S) shifts_y, shifts_x = torch.meshgrid(shifts_y, shifts_x, indexing='ij') all_boxes = [] all_scores = [] all_labels = [] # Process each of B boxes per cell for b in range(B): # Extract box parameters x_offset = predictions[..., b*5 + 0] y_offset = predictions[..., b*5 + 1] w = predictions[..., b*5 + 2] h = predictions[..., b*5 + 3] conf = predictions[..., b*5 + 4] # Convert to absolute coordinates x_center = (x_offset / S + shifts_x) y_center = (y_offset / S + shifts_y) width = torch.square(w) # w = √w_pred² height = torch.square(h) # Convert to (x1, y1, x2, y2) format x1 = (x_center - 0.5 * width).reshape(-1, 1) y1 = (y_center - 0.5 * height).reshape(-1, 1) x2 = (x_center + 0.5 * width).reshape(-1, 1) y2 = (y_center + 0.5 * height).reshape(-1, 1) boxes = torch.cat([x1, y1, x2, y2], dim=-1) # Compute class-specific confidence scores scores = conf.reshape(-1) * class_probs.reshape(-1) labels = class_labels.reshape(-1) all_boxes.append(boxes) all_scores.append(scores) all_labels.append(labels) # Concatenate all boxes boxes = torch.cat(all_boxes, dim=0) scores = torch.cat(all_scores, dim=0) labels = torch.cat(all_labels, dim=0) # Confidence thresholding keep = scores > conf_threshold boxes = boxes[keep] scores = scores[keep] labels = labels[keep] # Apply NMS per class keep_mask = torch.zeros_like(scores, dtype=torch.bool) for class_id in torch.unique(labels): class_indices = labels == class_id class_boxes = boxes[class_indices] class_scores = scores[class_indices] # NMS (using torchvision) keep_indices = torch.ops.torchvision.nms( class_boxes, class_scores, nms_threshold ) # Mark these boxes as kept class_keep_indices = torch.where(class_indices)[0][keep_indices] keep_mask[class_keep_indices] = True final_boxes = boxes[keep_mask] final_scores = scores[keep_mask] final_labels = labels[keep_mask] return final_boxes, final_scores, final_labels# Example usagemodel.eval()with torch.no_grad(): img_tensor = ... # Load and preprocess image predictions = model(img_tensor.unsqueeze(0))[0] # Remove batch dim boxes, scores, labels = convert_predictions_to_boxes( predictions, conf_threshold=0.2, nms_threshold=0.5 ) # boxes: (N, 4) in normalized 0-1 coordinates # Multiply by image dimensions to get pixel coordinates
key implementation details
√w and √h: The model predicts the square root of width/height to balance loss across different box sizes
Relative Coordinates: x,y offsets are relative to grid cell top-left corner
Responsible Box Selection: During training, the loss penalizes coordinates only for the box with the highest IOU with the ground truth (GT)
Class Probabilities: Shared across all B boxes in a cell (limitation of v1)
Lambda Weighting: λ_coord=5 to emphasize localization, λ_noobj=0.5 to de-emphasize empty cells
The loss follows the original paper. It gets ~63% mAP on Pascal VOC 2007 after 135 epochs.
deploying for speed
The usual production path is an export to ONNX (Open Neural Network Exchange), then TensorRT, then lower precision. FP16 gives ~2x throughput at near-baseline accuracy. INT8 quantization shrinks the model ~4x versus FP32, for edge devices like Jetson. Quantization-aware training keeps INT8 accuracy highest. TensorRT also fuses Conv → BatchNorm → ReLU into single kernels and reuses memory buffers across layers.
The core insight from 2016: treat detection as a single regression problem instead of a multi-stage pipeline. Ten versions later, the models are faster and more accurate, but that basic idea hasn't changed.
references
Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You Only Look Once: Unified, Real-Time Object Detection. CVPR 2016.