Search

Search papers and lessons

Focal Loss for Dense Object Detection

Tsung-Yi Lin, Priya Goyal, Ross Girshick et al. · 2017

Lin et al. (2017) showed that one-stage detectors lose accuracy to class imbalance, and that a reweighted cross-entropy loss, focal loss, lets a simple one-stage detector match the best two-stage ones.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Probability
  • Neural network basics
  • Computer vision
  • Linear algebra
  • ReadReady to readNot yet

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 kk here? For most locations the answer is clearly no, and the model already knows it.

The paper names two harms that follow from this.

  1. Training is slow to learn anything useful, because most of the gradient comes from examples that carry almost no information.
  2. 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
  1. 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.
  2. 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.
  3. 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, 21/32^{1/3} and 22/32^{2/3} 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.
  4. Label each anchor. An anchor is marked as an object of class kk 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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 γ=2\gamma = 2 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 y∈{+1,−1}y \in \{+1, -1\} be the true label, and let p∈[0,1]p \in [0, 1] be the model's probability that the object is present.

CE(p,y)={−log⁡(p)if y=1−log⁡(1−p)otherwise.\textrm{CE}(p, y) = \begin{cases} -\log(p) & \text{if } y = 1 \\ -\log(1 - p) & \text{otherwise.} \end{cases}

Step 1 in symbols: the probability of the true label

Define ptp_t as the probability the model gives to the correct answer:

pt={pif y=11−potherwise.p_t = \begin{cases} p & \text{if } y = 1 \\ 1 - p & \text{otherwise.} \end{cases}

Cross-entropy is then CE(pt)=−log⁡(pt)\textrm{CE}(p_t) = -\log(p_t). A correct example has pt>0.5p_t \gt 0.5.

Step 2 in symbols: the modulating factor

The focal loss multiplies the cross-entropy by (1−pt)γ(1 - p_t)^{\gamma}, where γ≥0\gamma \ge 0 is the focusing parameter:

FL(pt)=−(1−pt)γlog⁡(pt).\textrm{FL}(p_t) = -(1 - p_t)^{\gamma} \log(p_t).

When γ=0\gamma = 0 the factor is 1 and the loss is cross-entropy. As ptp_t approaches 1, the factor approaches 0. The paper also uses an α\alpha-balanced form, FL(pt)=−αt(1−pt)γlog⁡(pt)\textrm{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \log(p_t), where αt=α\alpha_t = \alpha for positives and 1−α1 - \alpha for negatives. The default is γ=2\gamma = 2 and α=0.25\alpha = 0.25.

Step 3 in symbols: how much easy examples are reduced

Take the ratio of focal loss to cross-entropy at γ=2\gamma = 2:

FL(pt)CE(pt)=(1−pt)2.\frac{\textrm{FL}(p_t)}{\textrm{CE}(p_t)} = (1 - p_t)^2.

At pt=0.9p_t = 0.9 the ratio is 0.12=0.010.1^2 = 0.01, which is the 100 times reduction the paper quotes. At pt=0.968p_t = 0.968 the ratio is 0.0322≈0.0010.032^2 \approx 0.001, a reduction of about 1000 times. At pt=0.5p_t = 0.5 the ratio is 0.250.25, and for any ptp_t 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 π\pi of an object at the start of training to 0.01 by choosing the bias bb of the last classification layer:

b=−log⁡(1−ππ)⇒σ(b)=π=0.01.b = -\log\left(\frac{1 - \pi}{\pi}\right) \quad\Rightarrow\quad \sigma(b) = \pi = 0.01.

With π=0.01\pi = 0.01, b=−log⁡(99)≈−4.60b = -\log(99) \approx -4.60. 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 A\mathcal{A} is the set of all anchors and A+\mathcal{A}_+ is the set of anchors assigned to an object, the image loss is

L=1∣A+∣∑a∈AFL(pt,a).L = \frac{1}{|\mathcal{A}_+|} \sum_{a \in \mathcal{A}} \textrm{FL}(p_{t,a}).

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

Example
1. Tiny: the factor at p_t = 0.5
  1. The true label is object and the model says probability 0.5. So pt=0.5p_t = 0.5.
  2. Cross-entropy is −log⁡(0.5)=log⁡2≈0.6931-\log(0.5) = \log 2 \approx 0.6931.
  3. With γ=0\gamma = 0, the factor (1−pt)0=1(1 - p_t)^0 = 1, so the focal loss is 0.6931. This matches cross-entropy, as the paper says it must.
  4. With γ=2\gamma = 2, the factor is (0.5)2=0.25(0.5)^2 = 0.25, so the focal loss is 0.25×0.6931≈0.17330.25 \times 0.6931 \approx 0.1733.
  5. Interpretation: at the same uncertain prediction, changing γ\gamma from 0 to 2 cuts the loss to a quarter.
Example
2. Standard: a positive and a negative with alpha-balance

Take a positive anchor (the true class is object) with predicted probability p=0.2p = 0.2, and use γ=2\gamma = 2, α=0.25\alpha = 0.25.

  1. The positive has y=1y = 1, so pt=p=0.2p_t = p = 0.2.
  2. The class weight is αt=α=0.25\alpha_t = \alpha = 0.25.
  3. Cross-entropy is −log⁡(0.2)≈1.6094-\log(0.2) \approx 1.6094.
  4. The factor is (1−0.2)2=0.82=0.64(1 - 0.2)^2 = 0.8^2 = 0.64.
  5. Multiply: 0.25×0.64×1.6094≈0.25750.25 \times 0.64 \times 1.6094 \approx 0.2575.
  6. Now take a negative anchor (the true class is background) with the same p=0.2p = 0.2. Here y=−1y = -1, so pt=1−p=0.8p_t = 1 - p = 0.8.
  7. The class weight is αt=1−α=0.75\alpha_t = 1 - \alpha = 0.75.
  8. Cross-entropy is −log⁡(0.8)≈0.2231-\log(0.8) \approx 0.2231, and the factor is (1−0.8)2=0.04(1 - 0.8)^2 = 0.04.
  9. Multiply: 0.75×0.04×0.2231≈0.00670.75 \times 0.04 \times 0.2231 \approx 0.0067.
  10. 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).
Example
3. Realistic: 100,000 anchors in one image

Suppose one image has 100,000 anchors. Ninety-nine thousand nine hundred are easy background with pt=0.99p_t = 0.99. The other 100 are hard object anchors with pt=0.3p_t = 0.3. Ignore α\alpha here so that only the focusing parameter changes.

  1. Cross-entropy for an easy anchor is −log⁡(0.99)≈0.01005-\log(0.99) \approx 0.01005. Summed over 99,900 easy anchors, that is about 1004.0.
  2. Cross-entropy for a hard anchor is −log⁡(0.3)≈1.2040-\log(0.3) \approx 1.2040. Summed over 100 hard anchors, that is about 120.4.
  3. Under cross-entropy, the easy anchors make up 1004.0/(1004.0+120.4)≈89.31004.0 / (1004.0 + 120.4) \approx 89.3 percent of the loss.
  4. With γ=2\gamma = 2, an easy anchor has factor (0.01)2=0.0001(0.01)^2 = 0.0001. Its focal loss is 0.0001×0.01005≈1.005×10−60.0001 \times 0.01005 \approx 1.005 \times 10^{-6}. Summed over 99,900 anchors, that is about 0.100.
  5. A hard anchor has factor (0.7)2=0.49(0.7)^2 = 0.49. Its focal loss is 0.49×1.2040≈0.59000.49 \times 1.2040 \approx 0.5900. Summed over 100 anchors, that is about 59.0.
  6. Under focal loss, the easy anchors make up 0.100/(0.100+59.0)≈0.170.100 / (0.100 + 59.0) \approx 0.17 percent of the loss.
  7. 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 γ=2\gamma = 2, how many times larger is the focal loss for an example with pt=0.5p_t = 0.5 than for an example with pt=0.9p_t = 0.9? Work it out before reading on.

Answer: FL(0.5)≈0.1733\textrm{FL}(0.5) \approx 0.1733 and FL(0.9)=0.01×0.10536≈0.001054\textrm{FL}(0.9) = 0.01 \times 0.10536 \approx 0.001054. The ratio is 0.1733/0.001054≈1640.1733 / 0.001054 \approx 164. The example at pt=0.5p_t = 0.5 has about 164 times the loss of the example at pt=0.9p_t = 0.9.

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 α\alpha does. In fact the α\alpha term weights by class, and the focusing term (1−pt)γ(1 - p_t)^{\gamma} weights each example by how hard it is. The paper's best α\alpha-balanced cross-entropy reaches 31.1 AP with α=0.75\alpha = 0.75 (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 ptp_t 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 γ\gamma, and α\alpha has to be tuned together with it. The paper notes that α\alpha should be lowered slightly as γ\gamma 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):

MethodBackboneAPAP50AP75
Faster R-CNN with FPNResNet-101-FPN36.259.139.0
SSD513ResNet-101-SSD31.250.433.3
DSSD513ResNet-101-DSSD33.253.335.2
Faster R-CNN with Inception-ResNet-v2 and TDMInception-ResNet-v2-TDM36.857.739.2
RetinaNet-101-800 (this paper)ResNet-101-FPN39.159.142.3
RetinaNet (this paper)ResNeXt-101-FPN40.861.144.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 α\alpha-balanced cross-entropy reaches at most 31.1 AP (Table 1a), while focal loss with γ=2\gamma = 2 reaches 34.0 AP, a gain of 2.9 points (Table 1b). The paper reports that the gain is robust across γ\gamma 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.

  1. 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.
  2. Section 2 (Related Work). Needs Region Proposal Network for the proposal idea, SSD for one-stage detectors, and Non-Maximum Suppression for OHEM.
  3. 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 ptp_t bookkeeping as you go.
  4. 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.
  5. Section 4.1 (Inference and Training). Needs Stochastic Gradient Descent and the box regression loss from the regression lessons.
  6. 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.
  7. Appendix A and B. Optional. The alternative form FL∗\textrm{FL}^* 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 −log⁡(0.8)≈0.2231-\log(0.8) \approx 0.2231. The factor is (1−0.8)2=0.04(1 - 0.8)^2 = 0.04. The focal loss is 0.04×0.2231≈0.00890.04 \times 0.2231 \approx 0.0089, 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 (1−pt)γ(1 - p_t)^{\gamma} with a modest γ\gamma, such as 2, and tune α\alpha together with it. The legitimate transactions with ptp_t above 0.99 get a factor below 0.0001 and stop dominating the loss. The rare fraudulent transactions, where ptp_t 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

Read the full paper

Tsung-Yi Lin, Priya Goyal, Ross Girshick et al., 2017. arXiv:1708.02002