AI Logic

Loss Functions

Focal Loss

Updated:

Graph of Focal Loss. The horizontal axis is the probability of the correct class p_t and the vertical axis is the loss, with curves for γ = 0 (cross-entropy), 0.5, 1, 2, and 5. The larger γ is, the smaller the loss of examples with large p_t; at p_t = 0.9, the loss with γ = 2 is 1/100 of cross-entropy. Legend on the right

Background and Overview

Focal Loss is a loss function that multiplies cross-entropy by a factor that shrinks the loss of examples the model already classifies correctly, so that training concentrates on hard examples. Lin et al. proposed it in 2017 for object detection, the task of locating and classifying objects in an image.

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

ptp_t is the probability the model assigns to the correct class. γ≥0\gamma \geq 0 controls how strongly the loss of easy examples is reduced; with γ=0\gamma = 0, Focal Loss is identical to cross-entropy.

The motivation is the extreme class imbalance that arises when training one-stage object detectors.

  • Most candidates are background: One-stage detectors such as SSD and YOLO classify roughly 100,000 candidate boxes (anchors) tiled over the whole image at once. Only a handful of them contain an object; almost all the rest are boxes that are easily judged to be "background."
  • The easy background losses dominate training in aggregate: With cross-entropy, even a well-classified example such as pt=0.9p_t = 0.9 keeps a non-negligible loss of about 0.1. Each one is small, but summed over tens of thousands of background boxes, these losses outweigh the losses of the few object boxes.

The figure at the top plots loss against ptp_t for several values of γ\gamma, as in Figure 1 of the paper. The larger γ\gamma is, the closer the loss of examples with large ptp_t (easy examples) gets to 0. With γ=2\gamma = 2, the loss of an example with pt=0.9p_t = 0.9 is 1/100 of the cross-entropy loss.

As an analogy, it is like a study plan for an exam that automatically cuts the time spent reviewing problems you can already solve and moves that time to the problems you still cannot.

Theory (Constructing the Loss)

Focal Loss is built from two-class (object vs. background) cross-entropy in the following steps.

  1. Write two-class cross-entropy in terms of the probability of the correct class, ptp_t. Let pp be the probability the model assigns to class 1, and let the ground-truth label be y∈{1,−1}y \in \{1, -1\}. pt={p(y=1)1−p(otherwise)CE(pt)=−log⁡ptp_t = \begin{cases} p & (y = 1) \\ 1 - p & (\text{otherwise}) \end{cases} \qquad \mathrm{CE}(p_t) = -\log p_t
  2. Multiply by a class weight αt\alpha_t (α-balanced cross-entropy). Class 1 gets weight α∈[0,1]\alpha \in [0, 1] and the other class gets 1−α1 - \alpha, so that the minority class counts more. CE(pt)=−αtlog⁡pt\mathrm{CE}(p_t) = -\alpha_t \log p_t However, αt\alpha_t only changes the weight according to which class an example belongs to; it cannot distinguish easy examples from hard ones.
  3. Multiply by the modulating factor (1−pt)γ(1 - p_t)^{\gamma}. This is the core of Focal Loss. FL(pt)=−(1−pt)γlog⁡pt\mathrm{FL}(p_t) = -(1 - p_t)^{\gamma} \log p_t
  4. In practice, apply αt\alpha_t as well. In the paper's experiments, this form gave slightly higher accuracy. FL(pt)=−αt(1−pt)γlog⁡pt\mathrm{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \log p_t

The paper presents the two-class form and notes that extending it to multiple classes is straightforward. The RetinaNet detector produces a probability for each class with a sigmoid function and applies the two-class Focal Loss to each.

Why It Focuses on Hard Examples

The modulating factor (1−pt)γ(1 - p_t)^{\gamma} automatically scales with how hard an example is.

  • Misclassified examples (ptp_t small): The factor is close to 1, so the loss is nearly the same as cross-entropy. Even with γ=2\gamma = 2, the loss of an example with pt≤0.5p_t \leq 0.5 is reduced by at most a factor of 4.
  • Well-classified examples (ptp_t close to 1): The factor approaches 0 and the loss nearly vanishes. With γ=2\gamma = 2, the loss is 1/100 of cross-entropy at pt=0.9p_t = 0.9 and 1/1000 at pt≈0.968p_t \approx 0.968.

As a result, the numerous but easy background boxes contribute little even in total, and hard examples come to dominate the overall loss and gradient. The paper examines the loss distribution of a trained model and shows that with γ=2\gamma = 2, most of the background loss comes from a small fraction of hard background boxes. For object boxes (positives), the loss distribution changed little as γ\gamma varied.

Focal Loss works in the opposite direction from robust losses such as the Huber loss, which reduce the influence of outliers. Robust losses down-weight "examples with large errors," whereas Focal Loss down-weights "easy examples" to concentrate on hard ones.

Experimental Results

The paper trains the one-stage detector RetinaNet (built on ResNet and FPN) for object detection on the COCO dataset and compares alternatives. The metric, AP, is average precision, which measures detection accuracy; higher is better.

Compared methodSettingAP
α-balanced cross-entropy (best α=0.75\alpha = 0.75)ResNet-50, validation set31.1
Focal Loss (γ=2\gamma = 2, α=0.25\alpha = 0.25)ResNet-50, validation set34.0
OHEM, which selects hard examples for training (best setting)ResNet-101, validation set32.8
Focal LossResNet-101, validation set36.0
Two-stage Faster R-CNN (with FPN)ResNet-101, test set36.2
RetinaNet (Focal Loss)ResNet-101, test set39.1
  • 2.9 points higher than cross-entropy: With the same network, simply replacing the loss with Focal Loss raised AP from 31.1 to 34.0.
  • Better than selecting hard examples: OHEM trains only on examples with large losses and discards easy examples entirely. Focal Loss uses every candidate box while changing their weights, and beat the best OHEM setting by 3.2 points.
  • A one-stage detector surpassed two-stage accuracy: RetinaNet outperformed the two-stage detectors of the time, such as Faster R-CNN.
  • γ\gamma has a wide working range: γ=2\gamma = 2 was best, but every γ\gamma from 0.5 to 5 gave a higher AP than cross-entropy (32.2 at γ=5\gamma = 5).

Practical Considerations

Choose α\alpha and γ\gamma together. In the paper, the best α\alpha became smaller as γ\gamma grew (α=0.25\alpha = 0.25 for γ=2\gamma = 2). Because γ\gamma already reduces the loss of easy background examples enough, there is less need to up-weight the rare object class through α\alpha. Fixing α\alpha by the rule "larger for rarer classes" can backfire.

Keep the following points in mind as well.

  • Initialize the output-layer bias so the rare class starts with a low probability: In the paper, ordinary training with cross-entropy diverged because the background loss was too large early in training. Setting the bias of the final classification layer to b=−log⁡1−ππb = -\log\frac{1 - \pi}{\pi} (π=0.01\pi = 0.01), so that every box initially outputs "object probability 0.01," made training stable. This is an initialization trick rather than part of the loss, and it helps both cross-entropy and Focal Loss.
  • Divide the summed loss by the number of objects: RetinaNet sums the losses over all candidate boxes and divides by the number of boxes assigned to objects. Dividing by the total number of candidate boxes would make the loss far too small, since almost all of them are background boxes with near-zero loss.
  • Compute from logits: The paper's implementation fuses the sigmoid that produces probabilities with the loss computation for numerical stability. torchvision's sigmoid_focal_loss also takes logits.
  • Watch the default reduction: torchvision's sigmoid_focal_loss defaults to reduction="none" (it returns the per-example loss). Compute the sum or mean yourself.

Comparison with Other Methods

The table below lines up ways of handling class imbalance from the same viewpoints.

MethodWhat it changesTreatment of easy examplesHyperparameters
Cross-entropyNothingAll counted with the same formulaNone
α-balanced cross-entropyPer-class weightsNo distinctionα\alpha
OHEM (selecting hard examples)Which examples are used for trainingDiscardedNumber to select, etc.
Focal LossPer-example weights (by difficulty)Kept with lower weightγ\gamma, α\alpha
Dice lossForm of the loss (overlap ratio)Measured as a ratio, so less affected by abundant backgroundNone (a small smoothing constant)

Rough guidelines for choosing among them:

  • Try Focal Loss for classification dominated by easy examples such as background: Besides object detection, it is a candidate when accuracy on rare classes will not improve. Start from the paper's γ=2\gamma = 2, α=0.25\alpha = 0.25.
  • For moderate imbalance, try class weights first: The weight argument of cross-entropy is all you need, and there are fewer values to tune.
  • For tasks that label image regions (segmentation), compare with Dice loss: A loss that directly measures region overlap often aligns better with the evaluation metric.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import sigmoid_focal_loss


def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
    """Eq. (5) of the paper: FL(p_t) = −α_t (1 − p_t)^γ log(p_t). targets are 0 or 1"""
    ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")  # −log(p_t)
    p = torch.sigmoid(logits)
    p_t = p * targets + (1 - p) * (1 - targets)
    alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
    return alpha_t * (1 - p_t) ** gamma * ce


# Example from the text: an example with p_t = 0.9 (logit log(9) gives probability 0.9; the label is 1)
logit = torch.log(torch.tensor([9.0]))
target = torch.tensor([1.0])
ce = F.binary_cross_entropy_with_logits(logit, target)
fl = focal_loss(logit, target, alpha=1.0, gamma=2.0)    # form without α
print(ce.item(), fl.item())                              # about 0.105 and about 0.00105 (1/100)

# torchvision implementation (default is reduction="none")
fl_tv = sigmoid_focal_loss(logit, target, alpha=0.25, gamma=2.0, reduction="none")


# Usage in an object-detection classification head (K classes × A anchors, a sigmoid per class)
K, A = 80, 9
cls_head = nn.Conv2d(256, K * A, kernel_size=3, padding=1)
pi = 0.01                                                # "object probability" at the start of training
nn.init.constant_(cls_head.bias, -torch.log(torch.tensor((1 - pi) / pi)).item())

features = torch.randn(2, 256, 32, 32)                   # dummy feature map
logits = cls_head(features)
targets = torch.zeros_like(logits)                       # mostly background (0)
targets[:, :5] = 1.0                                     # dummy positives
num_pos = targets.sum().clamp(min=1.0)                   # divide by the number assigned to objects
loss = sigmoid_focal_loss(logits, targets, alpha=0.25, gamma=2.0, reduction="sum") / num_pos
loss.backward()

FAQ

Q. What value should γ be?
A.

In the paper, γ = 2 (with α = 0.25) worked best, and starting from this combination is common practice. γ = 0 is identical to cross-entropy, and larger γ reduces the loss of easy examples more strongly. In the paper, every γ from 0.5 to 5 still gave higher accuracy than cross-entropy.

Q. Can it be used for classification tasks other than object detection?
A.

Yes. The idea is simply to reduce the loss of easy examples, so it is tried in settings such as classification where rare classes are hard to get right. Note, however, that the paper demonstrated its benefit on one-stage object detectors. On tasks with little imbalance, it may perform no differently from cross-entropy.

Q. How does it differ from OHEM, which trains only on selected hard examples?
A.

OHEM builds mini-batches only from examples with large losses and does not use easy examples for training. Focal Loss keeps using all examples while lowering the weight of the easy ones' losses. On the paper's one-stage detector, Focal Loss achieved an AP 3.2 points higher than the best OHEM setting.

References

  1. T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollár, "Focal Loss for Dense Object Detection," ICCV, 2017.
  2. torchvision Documentation, "torchvision.ops.sigmoid_focal_loss."