Foundations to Frontier
Tests
E. Deep Learning › E9 Object Detection Architectures

RetinaNet (focal loss)

RetinaNet (Lin, Goyal, Girshick, He and Dollár, 2017) showed that one-stage detectors had lagged two-stage ones because of class imbalance: about 100,000 anchors per image, almost all easy background, whose many small losses swamp training. The focal loss −α(1 − p_t)^γ log p_t down-weights well-classified examples. With an FPN backbone and a prior-initialised classifier, RetinaNet was the first one-stage detector to beat two-stage ones on COCO (39.1 AP). This page covers the imbalance, the focal loss, initialisation and the architecture. In the exercises you implement the loss and prior bias, then measure that easy negatives supply 94% of cross-entropy but only 7.6% of focal loss at γ = 2, while a small logistic model's average precision did not change: the gain lies in training deep dense detectors.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Stop paying attention to the easy ones

A one-stage detector checks about 100,000 candidate boxes per image, and nearly all are obviously background. Each easy background box contributes only a tiny loss, but together they drown out the few boxes that actually contain objects. RetinaNet’s focal loss turns down the volume on examples the network already gets right, and turns it down more the more confident the network is. Training then concentrates on the hard cases, and a simple one-stage detector matched the best two-stage ones.

Detection lab
probability of the true class p
at p = 0.9 the focal loss is 1.0e-2 × the cross-entropy: easy examples are down-weighted, so the many easy background anchors no longer swamp the loss
Why engineers care

Class imbalance is everywhere: rare defects on a production line, rare targets in satellite imagery, rare events in sensor logs. The focal loss is a standard tool for it, inside detectors and beyond.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Most anchors in a one-stage detector are…
  2. 2. The focal loss down-weights…
  3. 3. RetinaNet is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Focal loss: FL(p_t) = −α_t(1 − p_t)^γ log p_t, where p_t is the probability of the true class.
    • With γ = 2, an example at p_t = 0.9 has its cross-entropy scaled by (0.1)² = 0.01, and at p_t = 0.968 by about 0.001.
    • With γ = 0 and α = 1 it is plain cross-entropy.
    • RetinaNet uses γ = 2 and α = 0.25.
  • Prior initialisation: set the last classification bias to b = −log((1 − π)/π) with π = 0.01, giving b ≈ −4.6. Every anchor then starts with foreground probability 0.01, so the background flood does not cause a huge initial loss.
  • Anchors:
    • levels P3–P7;
    • 9 anchors per position (3 scales × 3 ratios);
    • an 800 × 800 image gives 9·(100² + 50² + 25² + 12² + 6²) = 119,745 anchors.
  • Assignment: positive at IoU ≥ 0.5, negative below 0.4, ignored in between.
  • Normalisation: the loss is summed over all anchors and divided by the number of positive anchors.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Down-weighting at p_t = 0.9 with γ = 2:
  2. 2. RetinaNet's α:
  3. 3. Prior π for bias initialisation:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

RetinaNet in code

Exercise 1.

  • The focal loss scaled easy examples’ cross-entropy by 0.01 at p_t = 0.9.
  • The prior bias −4.595 gave starting probability 0.01.
  • An 800 × 800 image has 119,745 anchors.

Practice.

  • torchvision’s retinanet_resnet50_fpn_v2, and torchvision.ops.sigmoid_focal_loss.
  • Heads:
    • a classification subnet and a box subnet, each 4 × (3 × 3 conv, 256 channels, ReLU) then an output conv;
    • shared across pyramid levels;
    • the classification output uses one sigmoid per class (K·A channels), not a softmax.
  • Inference:
    • keep at most 1,000 top-scoring boxes per level after thresholding scores at 0.05;
    • merge the levels;
    • apply NMS at IoU 0.5.
loss_cls = torchvision.ops.sigmoid_focal_loss(logits, targets, alpha=0.25, gamma=2.0, reduction="sum") / max(1, num_pos)
nn.init.constant_(cls_head.bias, -math.log((1 - 0.01) / 0.01))      # prior initialisation
🐍 Exercise 1: focal loss and priors
Implement the focal loss, its down-weighting factor, the prior bias and RetinaNet's anchor count.
📝 Quick check (Level 2)
0/3 answered
  1. 1. torchvision's focal-loss op:
  2. 2. RetinaNet's classification outputs use…
  3. 3. The loss is normalised by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why one-stage detectors lagged. Two-stage detectors filter candidates with a proposal stage (about 2,000 per image, mostly plausible) and then sample a balanced 1:3 batch. One-stage detectors evaluate 10⁴–10⁵ anchors densely. SSD’s hard-negative mining and YOLO’s down-weighting are partial fixes. The RetinaNet paper argued the imbalance itself, not the one-stage design, was the main obstacle.

How the focal loss works.

  • The factor (1 − p_t)^γ is near 1 for misclassified examples and near 0 for confident correct ones.
  • With γ = 2 an easy negative at p_t = 0.99 contributes 10⁴ times less than under cross-entropy.
  • The total loss is then dominated by hard examples, without discarding any examples, unlike mining.
  • α balances positives and negatives; with γ > 0 the best α turned out to be below 0.5 (0.25), because the focal term already suppresses easy negatives.

Results.

  • With ResNet-50-FPN at 600 pixels, the focal loss reached 34.0 AP against 31.1 for the best α-balanced cross-entropy.
  • RetinaNet with ResNet-101-FPN reached 39.1 AP on COCO test-dev, above every two-stage detector of the time.
  • The loss distributions of a converged model showed that γ = 2 concentrates almost all of the negative loss on a tiny fraction of hard negatives.
📝 Quick check (Level 3)
0/3 answered
  1. 1. With γ = 2, an easy negative at p_t = 0.99 contributes…
  2. 2. Focal loss vs best α-balanced CE (ResNet-50, 600 px):
  3. 3. Unlike hard-negative mining, the focal loss…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Where does the loss come from?

History.

  • T.-Y. Lin, P. Goyal, R. Girshick, K. He and P. Dollár (2017) introduced RetinaNet and the focal loss at ICCV, where it won the best student paper award.
  • The focal loss was later adapted for segmentation, dense prediction and imbalanced classification. Generalised focal and varifocal losses followed in later detectors.

Exercise 2. Two parts:

  1. A detector-like score distribution: 999,000 negatives with probabilities mostly near 0, and 1,000 positives. We measure the share of the total loss from easy negatives (p < 0.1) as γ varies.
  2. A logistic model on 2-D data with 1 positive per 1,000 examples, including some hard negatives near the positives. It is trained with prior initialisation and three losses, and evaluated by average precision on held-out data.
γ share of loss from easy negatives
0 (cross-entropy) 0.944
0.5 0.810
1 0.525
2 0.076
5 0.0001
training loss average precision
cross-entropy 0.098
cross-entropy, α = 0.25 0.098
focal, γ = 2, α = 0.25 0.111
  • Easy negatives dominate cross-entropy, 94% of the loss although each is tiny. The focal loss removes them from the picture.
  • In the small logistic model the loss did not change average precision beyond noise. Seeds 1 and 2 gave differences of +0.001 and −0.003. A linear model with a few features ranks examples by nearly the same boundary however they are weighted.
  • The focal loss’s benefit is about steering the training of deep, dense detectors, where the network can change its features. This simple model cannot show that, and an honest test must use a real detector.
🐍 Exercise 2 (research): where does the loss come from?
Measure the share of loss from easy negatives under cross-entropy and focal loss, and compare losses for a simple imbalanced classifier.

Focal loss in AI, robotics and aerospace

  • Rare targets: small vehicles or ships in large satellite scenes are a needle-in-haystack problem, where dense detectors with focal loss are a standard choice.
  • Defect detection: imbalanced inspection data, with few defects, uses focal-type losses.
  • Dense prediction: focal and Dice-style losses handle class imbalance in segmentation of rare classes, for example cracks or wires.

References

  1. T.-Y. Lin, P. Goyal, R. Girshick, K. He, P. Dollár (2017). “Focal loss for dense object detection.” Proc. ICCV.
  2. T.-Y. Lin et al. (2017). “Feature pyramid networks for object detection.” Proc. CVPR.
  3. X. Li et al. (2020). “Generalized focal loss: learning qualified and distributed bounding boxes for dense object detection.” Advances in NeurIPS.