Computer Vision Lab Algorithms Focal loss

Focal loss

A modification of cross-entropy that lowers the weight of easy, well-classified examples, so training focuses on the hard ones.

Concept and explanationObject detectionDetection

This content was prepared automatically from documented sources and its human scientific review is not yet complete. If you find an error, let us know.

Mathematical formula

\mathrm{FL}(p_t) = -\alpha_t\,(1-p_t)^{\gamma}\log(p_t)

Explanation

In dense detectors, tens of thousands of anchors are easy background, and their small losses add up and dominate. The factor (1−p_t)^γ approaches zero when the example is easy (p_t close to 1). With γ=2, the loss of an example with p_t=0.9 falls a hundredfold compared with ordinary cross-entropy.

Detailed explanation

Intuition

In a dense detector there may be 100 thousand anchors in the image, of which only a few dozen are positive. Most negatives are easy (sky, wall), and the loss of each is small, but their sum overwhelms the signal of the important examples. Focal loss adds a modulating factor (1-p_t)^\gamma that lowers the weight of what the model has learned well, so attention focuses on the hard cases.

How it works step by step

  1. Compute the probability of the correct class p_t for each example.
  2. Multiply the cross-entropy by (1-p_t)^\gamma.
  3. Balance positives and negatives with \alpha_t.
  4. Normalise by the number of positive anchors, not all anchors.

Mathematical formulation

\mathrm{CE}(p_t) = -\log p_t,\qquad \mathrm{FL}(p_t) = -\alpha_t(1-p_t)^{\gamma}\log p_t
p_tthe modulating weight with \gamma=2
0.50.25
0.90.01
0.990.0001

Computational complexity

like cross-entropy.

Advantages

  • It handles severe imbalance without manual negative mining.
  • Simple to implement.

Limitations

  • Two extra parameters.
  • It may make the probabilities less calibrated.

When do you use it?

In one-stage detectors, medical segmentation of small lesions, and any severely imbalanced classification.

Code example (PyTorch)

from torchvision.ops import sigmoid_focal_loss
loss = sigmoid_focal_loss(logits, targets, alpha=0.25, gamma=2.0, reduction="sum") / num_pos

Applications

RetinaNet and FCOS, imbalanced medical segmentation, and imbalanced classification in general.

Limitations

Two parameters (α, γ) that need tuning; useful easy examples may be neglected if γ is large.

References

  1. T.-Y. Lin, P. Goyal, R. Girshick, K. He, P. Dollár (2017).Focal Loss for Dense Object Detection. arXiv:1708.02002 (ICCV 2017). doi:10.48550/arXiv.1708.02002

Related models

Related lessons

Try it in object detection