Focal loss

On this page 7

Focal loss is a modification of cross-entropy loss that multiplies each example’s loss by a modulating factor of (1 − p_t)^γ, where p_t is the predicted probability of the correct class and γ is the focusing parameter. In the training of models in artificial intelligence, it reduces the contribution of easy, well-classified examples and lets the gradient concentrate on hard, misclassified examples.

The loss was introduced for dense object detection, where a one-stage detector evaluates tens of thousands of candidate boxes per image and the vast majority are easy background. That extreme foreground-background imbalance caused ordinary cross-entropy to be dominated by many small losses from easy negatives. Focal loss became a standard tool for imbalanced classification in detection, segmentation, medical imaging and other domains with rare positive classes.

How focal loss reshapes cross-entropy

For binary classification, define p_t as p when the true label is positive and 1 − p otherwise. Standard cross-entropy is −log(p_t). Focal loss is FL(p_t) = −α_t (1 − p_t)^γ log(p_t), where α_t is an optional class weight and γ ≥ 0 controls how strongly easy examples are suppressed. With γ = 0 and no α, the formula reduces exactly to cross-entropy.

The modulating factor approaches zero as p_t approaches one, so a confidently correct prediction contributes almost nothing. When an example is misclassified, p_t is small, the factor stays close to one and the loss is nearly unchanged. The effect is a dynamic, per-example reweighting that requires no manual mining of hard examples. The table shows how much the factor shrinks the loss at γ = 2.

Probability of correct classCross-entropy lossModulating factorRelative reduction
0.1 (hard)2.300.81About 1.2 times
0.5 (uncertain)0.690.254 times
0.9 (easy)0.1050.01100 times
0.99 (very easy)0.0100.000110,000 times
Effect of the modulating factor at gamma equal to 2

This asymmetric scaling explains the method: thousands of easy negatives with p_t near 0.99 lose four orders of magnitude of influence, while the few hard examples keep almost all of theirs.

The focusing parameter and the alpha weight

Two hyperparameters control focal loss. The focusing parameter γ decides how aggressively easy examples are down-weighted, and the balancing weight α rescales positives relative to negatives. In the original detection setting, the best combination was γ = 2 with α = 0.25 for the positive class. The low α for positives seems counterintuitive, but it compensates for the fact that γ already suppresses the many easy negatives.

Gamma valueBehaviorTypical use
0Identical to cross-entropyBalanced datasets, baseline runs
0.5 to 1Mild focusingModerate imbalance, noisy labels
2Strong focusingDefault for dense detection
3 to 5Very strong focusingExtreme imbalance, used with caution
Typical values of the focusing parameter

Both values interact with the learning rate and with output initialization. The original work also initialized the final classification bias so that the model starts by predicting a prior probability of about 0.01 for the rare class. Without this prior initialization, the first iterations produce very large losses from the abundant background and training can diverge.

Focal loss compared with other imbalance remedies

Focal loss is one of several ways to handle class imbalance, and its distinguishing property is that it weights examples by difficulty, not only by class. Class-weighted cross-entropy applies a fixed weight to every example of a class, while sampling methods change which examples the model sees. The comparison below positions focal loss among common alternatives.

MethodWhat it reweightsStrengthWeakness
Focal lossEach example by its confidenceAutomatic hard-example focusTwo extra hyperparameters
Weighted cross-entropyEach class by a fixed weightSimple and interpretableIgnores example difficulty
Hard negative miningSelected hard negatives onlyEffective in two-stage detectorsDiscards most data, adds heuristics
Oversampling or undersamplingFrequency of classes in batchesModel-agnosticOverfitting or information loss
Label smoothingTarget distributionImproves calibrationDoes not address imbalance directly
Comparison of methods for class imbalance

Several variants build on the same idea. Generalized focal loss and quality focal loss extend it to continuous quality targets in detection, polyfocal formulations expand the loss as a polynomial series, and asymmetric loss applies different focusing to positives and negatives in multi-label classification.

Where focal loss is used in practice

Focal loss is the standard choice in one-stage object detectors, where it allowed simple dense detectors to match the accuracy of two-stage pipelines. It is also common in semantic segmentation of small structures, often combined with Dice loss, and in medical image classification where lesions are rare. Tabular problems such as fraud detection use it as well, though gains there are less consistent.

  • Use it when positives are rare and easy negatives dominate the loss.
  • Start with γ = 2 and tune α on a validation set instead of copying defaults.
  • Initialize the output bias toward the rare-class prior to keep early training stable.
  • Track recall and precision per class, not only the average loss value.

Limitations and common mistakes

Focal loss is not a universal improvement. On balanced datasets it often matches or slightly underperforms plain cross-entropy, and with noisy labels a high γ can amplify errors because mislabeled examples look permanently hard. The loss also changes probability calibration: models trained with it tend to be less overconfident, which can help or hurt depending on the downstream threshold.

SymptomLikely causeFix
Loss explodes earlyNo prior bias initializationSet rare-class bias to the prior
Recall drops on rare classAlpha set too low for the dataRetune alpha on validation data
Unstable trainingGamma too high for label noiseLower gamma or clean labels
Numerical overflowProbabilities computed before logUse log-space or logit-based formulas
Frequent problems and how to address them

A practical implementation detail is numerical stability: robust code computes the loss from logits with log-sigmoid or log-softmax functions rather than from clipped probabilities.

A non-technical view

Imagine a teacher grading a long practice test. Most questions are easy, and the student gets them right every time. A few questions are hard, and the student keeps failing them.

Normal training treats every question about the same. The many easy questions then take up most of the attention. Focal loss tells the model to pay little attention to what it already knows. It spends its effort on the hard questions it still gets wrong. That is useful when the important cases are rare.

A concrete example

A team builds a detector that finds small cracks in photos of concrete bridges. Each image yields about 50,000 candidate regions, and fewer than 20 contain a crack. With standard cross-entropy, the model quickly learns to label everything as background and reaches high accuracy while missing most cracks.

The engineers switch to focal loss with γ = 2 and α = 0.25 and initialize the classifier bias to a crack prior of 0.01. Easy background regions now contribute almost nothing to the gradient. On the validation set, recall for cracks rises substantially while precision stays acceptable, and the inspection team receives far fewer missed defects in its weekly review.