TL;DR
Object detectors find things in pictures and draw a box around each one. The two-stage detectors of 2014 to 2016 were the most accurate, but one-stage detectors, which skip the first stage and label every possible box position directly, were faster and simpler and had fallen behind. Lin and colleagues found the cause: in a one-stage detector, almost every candidate box is easy background, and those easy boxes swamp the rare hard ones during training. They fixed it with focal loss, a change to cross-entropy that shrinks the loss on well-classified examples. A simple one-stage detector, RetinaNet, trained with it matched the accuracy of the best two-stage detectors on the COCO benchmark while running faster than them.
Builds on: Cross-Entropy Loss, Class Imbalance, Anchor Box, feature pyramids · Leads to: Object Detection systems that train on dense candidates
Why it mattered
Before this paper, most people believed the best detectors had to use a two-stage design: a proposal step that cut the image down to about one or two thousand candidate boxes, then a classifier on each one. The paper showed that a one-stage detector could reach the same accuracy on COCO, the large benchmark of everyday photographs with labelled objects, provided its training loss handled the imbalance. The authors reported 39.1 AP for RetinaNet with a ResNet-101 backbone, at an 800-pixel image scale with scale jitter and longer training, and 40.8 AP with a ResNeXt-101 backbone. AP is the average precision score COCO uses; higher is better.
The problem
A one-stage detector does not look at a short list of proposals. It labels every position, scale and aspect ratio in a regular grid. The paper counts about 100,000 locations per image. Only a few of them contain an object. Each location gets a yes-or-no question: is there an object of class here? For most locations the answer is clearly no, and the model already knows it.
The paper names two harms that follow from this.
- Training is slow to learn anything useful, because most of the gradient comes from examples that carry almost no information.
- The sheer number of easy negatives adds up to a large loss, and that loss can push the model toward a degenerate solution that says "background" almost everywhere.
Two-stage detectors avoided this by design. The proposal stage removed most easy background before the classifier saw it. The second stage then built minibatches with a fixed ratio of about 1 positive to 3 negatives, or used online hard example mining (OHEM), which keeps only the highest-loss examples. Both are ways to tilt the training data toward hard examples. The paper asks whether the loss itself can do that job.
How it works
We trace the whole pipeline for one image, in the order the detector runs it. The numbers are the ones in the paper's default setting.
flowchart LR A["Input image"] --> B["ResNet backbone"] B --> C["Feature pyramid P3 to P7"] C --> D["Classification subnet: K times A sigmoid scores per location"] C --> E["Box subnet: 4 offsets per anchor"] D --> F["Focal loss over all anchors"] E --> G["Box regression loss on matched anchors"] F --> H["Training loss: sum of the two"] G --> H
- Read the image through a backbone. A ResNet network turns the picture into a set of feature maps. These are arrays of numbers that describe small patches of the image at several resolutions.
- Build a feature pyramid. A Feature Pyramid Network adds a top-down path and side connections, so that every level of the pyramid, from fine (P3) to coarse (P7), carries strong features. The paper uses 256 channels at every level. Small objects are found on the fine levels and large objects on the coarse ones.
- Place anchors. At every position on every pyramid level, the detector places nine anchor boxes: three aspect ratios (1:2, 1:1, 2:1) at three scales (1, and times a base size). The base size is 32 pixels on P3 and doubles on each level up to 512 pixels on P7. Each anchor is a fixed template box.
- Label each anchor. An anchor is marked as an object of class if its IoU with a ground-truth box is at least 0.5. It is marked as background if the IoU is below 0.4. Anchors in between are ignored during training. Each object anchor also gets four numbers that say how to move it onto the true box.
- Score every anchor. A small convolutional subnet outputs, for every location and every anchor, one sigmoid score per class. Each score is a number between 0 and 1 and is read as the probability that the anchor contains that class.
- Score the loss on every anchor. Here is the paper's contribution. The focal loss is applied to all of the roughly 100,000 anchors, not to a sampled subset. Easy negatives contribute almost nothing, so the hard anchors dominate the total.
- Normalise. The summed loss is divided by the number of anchors that were assigned to an object, not by the total number of anchors. Dividing by the total would shrink the loss toward zero, because most anchors are easy.
- Add the box loss and update the weights. The training loss is the focal loss plus a regression loss on the box offsets of the object anchors. Stochastic gradient descent updates all weights.
- At test time, keep the best boxes. Only the top 1,000 scores per pyramid level are decoded, after a confidence threshold of 0.05. Then Non-Maximum Suppression with threshold 0.5 removes duplicate boxes.
A tiny check on step 6: if one anchor has a score of 0.9 for the correct class and another has 0.1, focal loss with gives the first a loss of about 0.001 and the second a loss of about 1.87. The easy anchor is now almost silent.
The math
The paper starts from binary cross-entropy. Let be the true label, and let be the model's probability that the object is present.
Step 1 in symbols: the probability of the true label
Define as the probability the model gives to the correct answer:
Cross-entropy is then . A correct example has .
Step 2 in symbols: the modulating factor
The focal loss multiplies the cross-entropy by , where is the focusing parameter:
When the factor is 1 and the loss is cross-entropy. As approaches 1, the factor approaches 0. The paper also uses an -balanced form, , where for positives and for negatives. The default is and .
Step 3 in symbols: how much easy examples are reduced
Take the ratio of focal loss to cross-entropy at :
At the ratio is , which is the 100 times reduction the paper quotes. At the ratio is , a reduction of about 1000 times. At the ratio is , and for any below 0.5 the ratio is larger, so a misclassified example keeps at least a quarter of its loss.
Step 4 in symbols: the initial bias
The paper sets the prior probability of an object at the start of training to 0.01 by choosing the bias of the last classification layer:
With , . Without this, the initial scores are 0.5 everywhere and the frequent background dominates the first loss. The paper reports that plain cross-entropy diverged without this change.
Step 5 in symbols: normalisation
If is the set of all anchors and is the set of anchors assigned to an object, the image loss is
The denominator counts the assigned anchors only, which keeps the scale of the loss stable regardless of how many easy anchors there are.
Worked examples
- The true label is object and the model says probability 0.5. So .
- Cross-entropy is .
- With , the factor , so the focal loss is 0.6931. This matches cross-entropy, as the paper says it must.
- With , the factor is , so the focal loss is .
- Interpretation: at the same uncertain prediction, changing from 0 to 2 cuts the loss to a quarter.
Take a positive anchor (the true class is object) with predicted probability , and use , .
- The positive has , so .
- The class weight is .
- Cross-entropy is .
- The factor is .
- Multiply: .
- Now take a negative anchor (the true class is background) with the same . Here , so .
- The class weight is .
- Cross-entropy is , and the factor is .
- Multiply: .
- Interpretation: the positive costs about 38 times as much as the negative, even though both predictions have the same probability. Part of that is the class weight and part is the factor, which is already large for the positive (it is hard) and small for the negative (it is easy).
Suppose one image has 100,000 anchors. Ninety-nine thousand nine hundred are easy background with . The other 100 are hard object anchors with . Ignore here so that only the focusing parameter changes.
- Cross-entropy for an easy anchor is . Summed over 99,900 easy anchors, that is about 1004.0.
- Cross-entropy for a hard anchor is . Summed over 100 hard anchors, that is about 120.4.
- Under cross-entropy, the easy anchors make up percent of the loss.
- With , an easy anchor has factor . Its focal loss is . Summed over 99,900 anchors, that is about 0.100.
- A hard anchor has factor . Its focal loss is . Summed over 100 anchors, that is about 59.0.
- Under focal loss, the easy anchors make up percent of the loss.
- Interpretation: focal loss moves nearly all of the training signal onto the 100 hard anchors. The total loss falls from about 1124 to about 59, and the balance shifts from mostly easy to almost entirely hard.
Try it: At , how many times larger is the focal loss for an example with than for an example with ? Work it out before reading on.
Answer: and . The ratio is . The example at has about 164 times the loss of the example at .
Common mistakes and tradeoffs
Mistake 1: "Focal loss is just a class weight." It is tempting to think the focal loss is the same as weighting the rare class more, which is what does. In fact the term weights by class, and the focusing term weights each example by how hard it is. The paper's best -balanced cross-entropy reaches 31.1 AP with (Table 1a). Adding the focusing term gives 34.0 AP, a 2.9 AP gain over that best balanced version (Table 1b). The difficulty weighting is the part that matters.
Mistake 2: "Hard examples should be removed from training." Hard negative mining and OHEM keep only the highest-loss examples and throw the rest away. Table 1d reports that focal loss beats the best OHEM variants by over 3 AP. Focal loss keeps every example and only changes how much each one counts.
Mistake 3: "The loss needs to be normalised by the total number of anchors." Dividing by all 100,000 anchors would shrink the loss, because almost all of them are easy and contribute little. The paper normalises by the number of anchors assigned to an object.
Mistake 4: "Any loss that looks like this works equally well." The paper's appendix compares alternative loss functions, and in early experiments a hinge loss on was unstable, so the shape matters, not just the fact that a loss is reweighted.
When to use it: when one class of examples is far more common than another and the common ones are mostly easy, as in dense detection, rare-event screening or any heavily skewed classifier.
When not to use it: when the classes are balanced and most examples are informative, plain cross-entropy is simpler and usually enough. Focal loss adds a hyperparameter , and has to be tuned together with it. The paper notes that should be lowered slightly as rises.
Alternatives: class-weighted loss alone, hard example mining, or two-stage sampling. The paper compares against all of these in its tables.
History
Object detection before 2014 used sliding windows with hand-built features. Viola and Jones used boosted classifiers for faces in 2001, and deformable part models extended the idea to general objects. R-CNN in 2014 used a convolutional network on each proposal and improved accuracy by a large margin. Faster R-CNN in 2015 put the proposal step into the same network, which made the two-stage design both accurate and reasonably fast.
One-stage detectors such as YOLO (2016) and SSD (2016) were fast, but they trailed in accuracy. The question this paper answered was whether that gap was a basic limit of one-stage design. The paper argued it was not: the gap came from the training loss. The idea caught on because it was simple to add to an existing detector and gave large gains without changing the network.
Results
The main comparison is the single-model accuracy on COCO test-dev, from the paper's Table 2 (AP is the COCO average precision):
| Method | Backbone | AP | AP50 | AP75 |
|---|---|---|---|---|
| Faster R-CNN with FPN | ResNet-101-FPN | 36.2 | 59.1 | 39.0 |
| SSD513 | ResNet-101-SSD | 31.2 | 50.4 | 33.3 |
| DSSD513 | ResNet-101-DSSD | 33.2 | 53.3 | 35.2 |
| Faster R-CNN with Inception-ResNet-v2 and TDM | Inception-ResNet-v2-TDM | 36.8 | 57.7 | 39.2 |
| RetinaNet-101-800 (this paper) | ResNet-101-FPN | 39.1 | 59.1 | 42.3 |
| RetinaNet (this paper) | ResNeXt-101-FPN | 40.8 | 61.1 | 44.1 |
These numbers say three things. RetinaNet with focal loss beats the best one-stage detectors by a wide margin, the closest one-stage competitor being DSSD at 33.2 AP. It also beats the best two-stage detector in the table, Faster R-CNN with Inception-ResNet-v2 and TDM at 36.8 AP, by 2.3 points. And it does so at speed: the paper reports that RetinaNet-101 at 600 pixels matches the accuracy of Faster R-CNN with FPN while running in 122 ms per image against 172 ms, both measured on an NVIDIA M40 GPU.
The ablations isolate the loss. With the same network, the -balanced cross-entropy reaches at most 31.1 AP (Table 1a), while focal loss with reaches 34.0 AP, a gain of 2.9 points (Table 1b). The paper reports that the gain is robust across values in roughly 0.5 to 5.
Limits: the speed results are for the paper's own hardware and settings. The appendix explores other loss shapes, so the claim is about down-weighting easy examples rather than one exact formula. The main schedule is 90,000 iterations on COCO, with an initial learning rate of 0.01 divided by 10 at 60k and 80k iterations.
Reading guide
Read the paper in this order, with the lessons it depends on.
- Abstract and Section 1 (Introduction). Needs Object Detection and the idea of a one-stage versus two-stage detector. The key claim is the class-imbalance diagnosis.
- Section 2 (Related Work). Needs Region Proposal Network for the proposal idea, SSD for one-stage detectors, and Non-Maximum Suppression for OHEM.
- Section 3 (Focal Loss). The core of the paper. Needs Cross-Entropy Loss, Class Imbalance and Focal Loss. Read Figure 1 next to Section 3.2, and check the bookkeeping as you go.
- Section 4 (RetinaNet Detector). Needs Feature Pyramid Networks, Anchor Box, Intersection over Union, Bounding-Box Regression and Sigmoid Function. The initialisation paragraph uses Section 3.3.
- Section 4.1 (Inference and Training). Needs Stochastic Gradient Descent and the box regression loss from the regression lessons.
- Section 5 (Experiments). Compare with Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks and Deep Residual Learning for Image Recognition (ResNet). Table 1 is the best place to see the loss doing its work.
- Appendix A and B. Optional. The alternative form and the derivatives. Useful once the main text is clear.
Check yourself
QuestionRecall: what is the one-line problem the paper says limits one-stage detectors?Show answer
Class imbalance during training. A one-stage detector labels about 100,000 locations per image, and most of them are easy background. Those easy examples dominate the loss and the gradient, so the model learns slowly and can be pushed toward predicting background everywhere.
QuestionComputation: with gamma equal to 2, what is the focal loss for an example with p_t = 0.8? Give the number to three decimal places.Show answer
Cross-entropy is . The factor is . The focal loss is , which rounds to 0.009 at three decimal places.
QuestionWhy does the paper normalise the total loss by the number of anchors assigned to an object, and not by the total number of anchors?Show answer
Most of the roughly 100,000 anchors are easy negatives, and focal loss already gives them a very small loss. Dividing by the total would shrink the loss toward zero and make the scale depend on how many easy anchors there are. Dividing by the assigned anchors keeps the scale tied to the number of objects the model must find.
QuestionApplied: a colleague trains a fraud detector where 1 in 2,000 transactions is fraudulent and most legitimate transactions are scored with p_t above 0.99. They use plain cross-entropy and the model predicts legitimate for almost everything. Which change from the paper would you try first, and why would it help?Show answer
Add the focal factor with a modest , such as 2, and tune together with it. The legitimate transactions with above 0.99 get a factor below 0.0001 and stop dominating the loss. The rare fraudulent transactions, where is low, keep most of their loss, so the gradient focuses on them. The paper's idea of initialising the output bias to a low prior probability is also worth trying, since it stops the frequent class from producing a large loss in the first iterations.
Sources
- Lin, T.-Y., Goyal, P., Girshick, R., He, K., and Dollár, P. (2017). Focal Loss for Dense Object Detection. arXiv:1708.02002
- DOI 10.48550/arXiv.1708.02002