Sign in

Focal

Focal loss

A cross-entropy that scales down the loss of well-classified examples, so training concentrates on the hard and rare ones.

Overview

In detection and other imbalanced tasks, almost every example is an easy negative. Each one has a tiny cross-entropy loss, but there are so many that together they drown out the few hard examples. Focal loss multiplies the cross-entropy of each example by a factor that depends on how well it is already classified. If the model gives the true label a probability of 0.99, the factor is tiny. If it gives 0.1, the factor is near 1. Easy examples fade and hard ones keep nearly their full weight. A separate class weight can also favour positives.

A short history

Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He and Piotr Dollár introduced focal loss in the 2017 paper 'Focal Loss for Dense Object Detection'. One-stage detectors score many thousands of candidate boxes per image, nearly all of them background, and these easy negatives swamped the loss. Scaling down the loss of well-classified examples let their RetinaNet detector match the accuracy of slower two-stage detectors.

How it works

  1. Take a logit zz and a 0 or 1 target for each element.
  2. Compute ptp_t, the probability the model gives to the true label: σ(z)\sigma(z) for a positive, 1−σ(z)1 - \sigma(z) for a negative.
  3. Compute the ordinary cross-entropy −ln⁡pt-\ln p_t.
  4. Multiply by the modulating factor (1−pt)γ(1 - p_t)^{\gamma}, which is small for confident correct predictions.
  5. Multiply by the class weight: α\alpha for positives and 1−α1 - \alpha for negatives, when alpha is set.
  6. Reduce over all elements with reduction.

Watch out for

  • Mislabelled examples look hard, so focal loss focuses on them. On noisy labels it can do worse than plain cross-entropy.
  • The default alpha of 0.25 gives positives less weight than negatives. That suits a γ\gamma of 2 on detection data and is easy to misread as up-weighting positives.
  • With the mean reduction the loss is divided by all elements. Because most are down-weighted to near zero, the value is very small and the learning rate may need retuning.
  • The down-weighting distorts the predicted probabilities. A model trained this way is often poorly calibrated and needs recalibration if the scores are used as probabilities.
  • This template is the sigmoid form for binary and multi-label targets. It is not the softmax form for exclusive classes.

Use cases

When to use it

Dense object detection, segmentation with a small foreground, and any binary or multi-label task where easy negatives vastly outnumber the examples that matter.

In industry

Object detection
One-stage detectors in the RetinaNet line use focal loss on the classification head, where background boxes vastly outnumber objects.
Medical imaging
Segmentation models for small lesions use focal loss because the pixels of interest are a tiny fraction of each scan.
Fraud and risk
Teams training neural classifiers on transactions, where fraud is a small fraction of cases, use focal loss to keep rare positives from being ignored.

Choosing it: what must hold

  • A classification problem with strong imbalance, where most examples are easy and belong to one class.
  • Willingness to tune two settings, the focusing parameter gamma and the class weight alpha.
  • No strict need for calibrated probabilities, or a calibration step afterwards, since focal loss distorts them.

When to choose something else

IfUse instead
Classes are roughly balancedSoftmax cross-entropy or binary cross-entropy
Imbalance is mild and you need calibrated probabilitiesBinary cross-entropy with a positive class weight
Many of the hard examples are mislabelledLabel-smoothed cross-entropy, after cleaning the labels

Math foundations

  1. Probability of the true label

    pt={σ(z),y=11−σ(z),y=0p_t = \begin{cases} \sigma(z), & y = 1 \\ 1 - \sigma(z), & y = 0 \end{cases}

    One number that says how right the model is, whichever the label. Cross-entropy is −ln⁡pt-\ln p_t.

  2. The focal loss

    FL⁡(pt)=− αt (1−pt)γ ln⁡pt\operatorname{FL}(p_t) = -\,\alpha_t\,(1 - p_t)^{\gamma}\,\ln p_t

    Cross-entropy times a modulating factor. With γ=0\gamma = 0 and no class weight it is plain binary cross-entropy.

  3. The class weight

    αt={α,y=11−α,y=0\alpha_t = \begin{cases} \alpha, & y = 1 \\ 1 - \alpha, & y = 0 \end{cases}

    A fixed weight per class, separate from the focusing. When alpha is null the weight is 1 for both.

  4. How strongly easy examples are reduced

    pt=0.9,  γ=2:(1−pt)γ=0.01p_t = 0.9,\; \gamma = 2: \quad (1 - p_t)^{\gamma} = 0.01

    An example classified with probability 0.9 keeps 1 percent of its cross-entropy. One at 0.5 keeps 25 percent. The factor decides who is heard.

  5. Gradient with respect to the logit

    ∂ FL⁡∂z=s αt[γ (1−pt)γ ptln⁡pt−(1−pt)γ+1],s=2y−1\frac{\partial\,\operatorname{FL}}{\partial z} = s\,\alpha_t\Big[\gamma\,(1 - p_t)^{\gamma}\,p_t \ln p_t - (1 - p_t)^{\gamma + 1}\Big], \qquad s = 2y - 1

    With γ=0\gamma = 0 this reduces to −s αt(1−pt)-s\,\alpha_t(1 - p_t), the cross-entropy gradient. The extra factors shrink it for confident correct predictions.

Symbols

zz
the logit for one element
yy
the target, 0 or 1
ptp_t
the probability the model gives to the true label
γ\gamma
focusing strength, gamma in the config, default 2
α\alpha
weight on positives, alpha in the config, default 0.25
αt\alpha_t
the class weight that applies to this element
ss
the sign: +1 for a positive target, -1 for a negative one
σ\sigma
the logistic sigmoid

Worked by hand

Two positive examples with γ=2\gamma = 2 and α=0.25\alpha = 0.25. The easy one has logit 2, so pt=0.8808p_t = 0.8808. The hard one has logit −2-2, so pt=0.1192p_t = 0.1192.

easy:0.25×(0.1192)2×(−ln⁡0.8808)=0.25×0.01421×0.1269=0.000451\text{easy:} \quad 0.25 \times (0.1192)^{2} \times (-\ln 0.8808) = 0.25 \times 0.01421 \times 0.1269 = 0.000451
hard:0.25×(0.8808)2×(−ln⁡0.1192)=0.25×0.7758×2.1269=0.4125\text{hard:} \quad 0.25 \times (0.8808)^{2} \times (-\ln 0.1192) = 0.25 \times 0.7758 \times 2.1269 = 0.4125
cross-entropy ratio: 2.12690.1269=16.8,focal ratio: 0.41250.000451≈915\text{cross-entropy ratio: } \frac{2.1269}{0.1269} = 16.8, \qquad \text{focal ratio: } \frac{0.4125}{0.000451} \approx 915

Under cross-entropy the hard example weighs about 17 times the easy one. Under focal loss it weighs about 900 times as much.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import FocalLoss
from config import FocalLossConfig

loss = FocalLoss(FocalLossConfig(gamma=2.0, alpha=0.25))
logits = np.array([4.0, -1.0, -3.0, 0.5])      # raw scores
labels = np.array([1.0, 1.0, 0.0, 0.0])
print(loss.forward(logits, labels))            # the hard second example dominates the average
print(loss.backward(logits, labels))           # gradient with respect to the logits
Read the implementation (76 lines)
"""Focal loss on logits for binary and multi-label targets: -alpha_t * (1 - p_t)^gamma * log(p_t).

NumPy only. `forward` returns the loss, `backward` its gradient with respect to the logits.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import FocalLossConfig
except ImportError:  # run from the template's own folder
    from config import FocalLossConfig

def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
    """Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
    pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
    if pred.shape != target.shape:
        raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
    return pred, target


def _reduce(values: np.ndarray, reduction: str):
    """Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
    if reduction == "mean":
        return float(values.mean())
    if reduction == "sum":
        return float(values.sum())
    return values


def _grad_scale(count: int, reduction: str) -> float:
    """Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
    return 1.0 / count if reduction == "mean" else 1.0


class FocalLoss:
    """Binary cross-entropy on logits, scaled by (1 - p_t)^gamma and an optional class weight."""

    def __init__(self, config: FocalLossConfig | None = None) -> None:
        self.config = config or FocalLossConfig()

    def _terms(self, logits: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, ...]:
        """Per-element pieces: sign s (+1 for y = 1, -1 for y = 0), log(p_t), 1 - p_t and the class weight.

        p_t = sigmoid(s * z) is the probability given to the true label. Both logs come from logaddexp, so
        logits of any size are safe.
        """
        if not np.isin(target, (0.0, 1.0)).all():
            raise ValueError("target must hold only 0 and 1")
        sign = 2.0 * target - 1.0
        log_pt = -np.logaddexp(0.0, -sign * logits)
        one_minus_pt = np.exp(-np.logaddexp(0.0, sign * logits))
        alpha = self.config.alpha
        weight = np.ones_like(target) if alpha is None else alpha * target + (1.0 - alpha) * (1.0 - target)
        return sign, log_pt, one_minus_pt, weight

    def forward(self, logits: np.ndarray, target: np.ndarray):
        """logits: raw scores, any shape, e.g. (N,) or (N, classes). target: same shape, 0 or 1.
        Returns a float, or the per-element array for "none"."""
        logits, target = _pair(logits, target)
        _, log_pt, one_minus_pt, weight = self._terms(logits, target)
        return _reduce(-weight * one_minus_pt**self.config.gamma * log_pt, self.config.reduction)

    def backward(self, logits: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Gradient of the reduced loss with respect to the logits, same shape as the logits.

        With u = 1 - p_t the per-element derivative is s * w * (gamma * u^gamma * p_t * log(p_t) - u^(gamma + 1)).
        For "none" it is returned unscaled (the gradient of the sum).
        """
        logits, target = _pair(logits, target)
        gamma = self.config.gamma
        sign, log_pt, u, weight = self._terms(logits, target)
        local = sign * weight * (gamma * u**gamma * (1.0 - u) * log_pt - u ** (gamma + 1.0))
        return local * _grad_scale(logits.size, self.config.reduction)

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build FocalLoss(FocalLossConfig(gamma=2.0, alpha=None, reduction="none")) and evaluate forward on logits from -6 to 6 with target 1. Repeat with gamma=0.0 and plot the ratio of the two. Then check backward against a finite difference at a logit of 0.5.

Check on learning

  1. A dataset has 1000 easy negatives at pt=0.99p_t = 0.99 and 10 hard positives at pt=0.2p_t = 0.2. Which group contributes more total loss under cross-entropy, and under focal loss with γ=2\gamma = 2?
    A way to think about it

    Multiply the count by the per-example loss for each group, once with −ln⁡pt-\ln p_t and once with the extra factor (1−pt)2(1 - p_t)^{2}.

  2. Why can a class weight alone not solve the problem that focal loss addresses?
    A way to think about it

    A class weight treats every negative alike. The issue is that among the negatives, the easy ones outnumber the hard ones. Ask what would distinguish them.

  3. Ten percent of your labels are wrong. Predict how focal loss behaves compared with cross-entropy.
    A way to think about it

    A wrong label gives a confident model a very low ptp_t. See which loss gives such an example more relative weight, and what the model is then pushed to do.

  4. The paper's default alpha of 0.25 down-weights the rare positive class. Why might that be the right choice when γ\gamma is 2?
    A way to think about it

    The focusing term already removes most of the negatives' weight. Think about the balance that remains after it, and which side then needs trimming.

  5. Raising γ\gamma from 2 to 5 makes training focus on an ever smaller set of examples. What risk does that carry?
    A way to think about it

    Consider the effective number of examples that still contribute gradient, and what kind of examples remain when all but the hardest are silenced.