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
- Take a logit and a 0 or 1 target for each element.
- Compute , the probability the model gives to the true label: for a positive, for a negative.
- Compute the ordinary cross-entropy .
- Multiply by the modulating factor , which is small for confident correct predictions.
- Multiply by the class weight: for positives and for negatives, when
alphais set. - 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
alphaof 0.25 gives positives less weight than negatives. That suits a 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
| If | Use instead |
|---|---|
| Classes are roughly balanced | Softmax cross-entropy or binary cross-entropy |
| Imbalance is mild and you need calibrated probabilities | Binary cross-entropy with a positive class weight |
| Many of the hard examples are mislabelled | Label-smoothed cross-entropy, after cleaning the labels |
Math foundations
Probability of the true label
One number that says how right the model is, whichever the label. Cross-entropy is .
The focal loss
Cross-entropy times a modulating factor. With and no class weight it is plain binary cross-entropy.
The class weight
A fixed weight per class, separate from the focusing. When
alphais null the weight is 1 for both.How strongly easy examples are reduced
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.
Gradient with respect to the logit
With this reduces to , the cross-entropy gradient. The extra factors shrink it for confident correct predictions.
Symbols
- the logit for one element
- the target, 0 or 1
- the probability the model gives to the true label
- focusing strength,
gammain the config, default 2 - weight on positives,
alphain the config, default 0.25 - the class weight that applies to this element
- the sign: +1 for a positive target, -1 for a negative one
- the logistic sigmoid
Worked by hand
Two positive examples with and . The easy one has logit 2, so . The hard one has logit , so .
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 logitsRead 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
- A dataset has 1000 easy negatives at and 10 hard positives at . Which group contributes more total loss under cross-entropy, and under focal loss with ?
A way to think about it
Multiply the count by the per-example loss for each group, once with and once with the extra factor .
- 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.
- 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 . See which loss gives such an example more relative weight, and what the model is then pushed to do.
- The paper's default
alphaof 0.25 down-weights the rare positive class. Why might that be the right choice when 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.
- Raising 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.