TExcelTAD

Focal Loss

An object detector scores tens of thousands of candidate boxes per image, and almost all of them are plain background that the model classifies correctly after a few epochs. Each of those easy negatives has a small cross-entropy, but there are so many that together they dominate the total loss and its gradient, and the few hard, informative examples get drowned out. Focal loss (Lin et al., 2017, introduced with the RetinaNet detector) fixes this by multiplying cross-entropy by a factor that fades out examples the model already gets right. This lesson implements it with its gradient, shows how strongly it down-weights easy examples, and then tests it honestly on an imbalanced tabular problem, where it is not a free win.

The formula

Write ptp_t for the probability the model gives to the true class: pt=pp_t = p if y=1y = 1 and pt=1−pp_t = 1 - p if y=0y = 0. Binary cross-entropy is −log⁡pt-\log p_t. Focal loss is

FL(pt)=−αt (1−pt)γlog⁡pt\text{FL}(p_t) = -\alpha_t \, (1 - p_t)^{\gamma} \log p_t
  • The focusing parameter γ≥0\gamma \ge 0 controls the modulating factor (1−pt)γ(1 - p_t)^\gamma. For a well-classified example (ptp_t near 1) the factor is near 0; for a badly classified one (ptp_t small) it is near 1, so hard examples keep almost their full cross-entropy. γ=0\gamma = 0 gives back cross-entropy; the paper found γ=2\gamma = 2 best.
  • The balancing weight αt\alpha_t is α\alpha for positives and 1−α1 - \alpha for negatives, the usual class weighting. Surprisingly, the paper's best value was α=0.25\alpha = 0.25, which gives the rare positives less weight: once γ\gamma has silenced the easy negatives, the positives no longer need a boost.

The gradient with respect to the logit zz, writing s=+1s = +1 for positives and −1-1 for negatives (so pt=σ(sz)p_t = \sigma(sz)), is

∂ FL∂z=s αt(1−pt)γ(γ ptlog⁡pt−(1−pt)).\frac{\partial \, \text{FL}}{\partial z} = s \, \alpha_t (1 - p_t)^{\gamma} \big( \gamma \, p_t \log p_t - (1 - p_t) \big) .

With γ=0\gamma = 0 and αt=1\alpha_t = 1 it reduces to −s(1−pt)=p−y-s(1 - p_t) = p - y, the cross-entropy gradient.

How much weight is left?

The first column below is the cross-entropy of an example whose true-class probability is ptp_t. The other columns are the modulating factor (1−pt)γ(1 - p_t)^\gamma, the fraction of that cross-entropy focal loss keeps (with α\alpha switched off).

python · try it yourself
import numpy as np

def focal(y, z, gamma=2.0, alpha=0.25):
    s = 2 * y - 1                                   # +1 for positives, -1 for negatives
    log_pt = -np.logaddexp(0, -s * z)               # log p_t, computed stably
    pt = np.exp(log_pt)
    a = np.where(y == 1, alpha, 1 - alpha)
    return np.mean(-a * (1 - pt) ** gamma * log_pt)

def focal_grad(y, z, gamma=2.0, alpha=0.25):        # d loss / d z
    s = 2 * y - 1
    pt = 1 / (1 + np.exp(-s * z))
    a = np.where(y == 1, alpha, 1 - alpha)
    return s * a * (1 - pt) ** gamma * (gamma * pt * np.log(pt) - (1 - pt)) / len(y)

# how much of the cross-entropy is left for easy and hard examples
print("  p_t    CE     gamma=1  gamma=2  gamma=5   (focal / CE, alpha off)")
for pt in [0.95, 0.6, 0.3, 0.1]:
    ce = -np.log(pt)
    print(f"{pt:5.2f}  {ce:6.3f}  " + "  ".join(f"{(1 - pt) ** g:7.4f}" for g in [1, 2, 5]))

y = np.array([1.0, 1.0, 0.0, 0.0, 1.0])
z = np.array([3.0, -0.5, -2.0, 1.5, 0.2])
h = 1e-6
num = np.array([(focal(y, z + h * e) - focal(y, z - h * e)) / (2 * h) for e in np.eye(5)])
print("gradient matches numeric:", np.allclose(focal_grad(y, z), num, atol=1e-8))
print("gamma=0, alpha=0.5 is half the BCE:", np.isclose(focal(y, z, 0.0, 0.5), 0.5 * np.mean(np.logaddexp(0, z) - y * z)))
  p_t    CE     gamma=1  gamma=2  gamma=5   (focal / CE, alpha off)
 0.95   0.051   0.0500   0.0025   0.0000
 0.60   0.511   0.4000   0.1600   0.0102
 0.30   1.204   0.7000   0.4900   0.1681
 0.10   2.303   0.9000   0.8100   0.5905
gradient matches numeric: True
gamma=0, alpha=0.5 is half the BCE: True

With γ=2\gamma = 2, an easy example at pt=0.95p_t = 0.95 keeps 0.25 % of its cross-entropy (a factor of 400 less), while a hard one at pt=0.1p_t = 0.1 keeps 81 %. In a batch of 10,000 easy negatives and 10 hard positives, that changes which examples steer the gradient. The gradient formula passes the numerical check, and γ=0,α=0.5\gamma = 0, \alpha = 0.5 is exactly half of binary cross-entropy (the αt\alpha_t of 0.5 on both classes).

Does it help on an imbalanced table?

Train the same logistic regression by gradient descent with three losses on data with about 5 % positives, then compare on a held-out half. Average precision (AP) measures how well the scores rank positives above negatives, independently of any threshold (ROC and PR curves); recall and precision are read at the default threshold 0.5; "mean p" is the average predicted probability, which a calibrated model keeps near the true positive rate.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import average_precision_score, recall_score, precision_score

X, y = make_classification(n_samples=4000, n_features=10, n_informative=4, weights=[0.95],
                           class_sep=0.8, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)
print("positives in training:", int(y_tr.sum()), "of", len(y_tr))

def grad_bce(y, z):
    return (1 / (1 + np.exp(-z)) - y) / len(y)

def grad_focal(y, z, gamma=2.0, alpha=0.25):
    s = 2 * y - 1
    pt = 1 / (1 + np.exp(-s * z))
    a = np.where(y == 1, alpha, 1 - alpha)
    return s * a * (1 - pt) ** gamma * (gamma * pt * np.log(pt) - (1 - pt)) / len(y)

def train(grad_fn, lr=0.5, steps=2000, **kw):
    w, b = np.zeros(X_tr.shape[1]), 0.0
    for _ in range(steps):
        g = grad_fn(y_tr, X_tr @ w + b, **kw)        # d loss / d z for every example
        w -= lr * X_tr.T @ g
        b -= lr * g.sum()
    return w, b

for name, fn, kw in [("BCE", grad_bce, {}), ("focal g=2 a=0.25", grad_focal, {}),
                     ("focal g=2 a=0.75", grad_focal, {"alpha": 0.75})]:
    w, b = train(fn, **kw)
    p = 1 / (1 + np.exp(-(X_te @ w + b)))
    pred = (p >= 0.5).astype(int)
    print(f"{name:17s} AP {average_precision_score(y_te, p):.3f}  recall@0.5 {recall_score(y_te, pred):.3f}"
          f"  precision@0.5 {precision_score(y_te, pred, zero_division=0):.3f}  mean p {p.mean():.3f}")
print("true positive rate in test:", round(y_te.mean(), 3))
positives in training: 112 of 2000
BCE               AP 0.390  recall@0.5 0.180  precision@0.5 0.952  mean p 0.057
focal g=2 a=0.25  AP 0.385  recall@0.5 0.063  precision@0.5 1.000  mean p 0.177
focal g=2 a=0.75  AP 0.306  recall@0.5 0.180  precision@0.5 0.769  mean p 0.327
true positive rate in test: 0.056

The result is worth reading slowly:

  • Ranking did not improve. AP is 0.390 with cross-entropy, 0.385 with focal loss at α=0.25\alpha = 0.25 and 0.306 at α=0.75\alpha = 0.75. A linear model has only 11 parameters and no army of easy negatives to ignore, so there is little for focal loss to fix.
  • The probabilities moved. Cross-entropy's mean prediction (0.057) matches the true positive rate in the test set (0.056); focal loss raises it to 0.177 and 0.327. Down-weighting confident examples pulls every probability towards 0.5, so focal-loss models are not calibrated. If you need probabilities, recalibrate on a validation set.
  • Recall at 0.5 is the wrong comparison. The three models put the 0.5 threshold at different places on their score scale. Comparing at a threshold chosen for the business goal (Log Loss and Choosing a Threshold) is fairer than at 0.5.

Focal loss earns its place in dense prediction: one-stage object detectors and segmentation models, where each image produces a huge number of easy background examples. For tabular imbalance, first try class weights, resampling and threshold tuning (Class Weights, Focal Loss and Balanced Batches in Data Preparation compares them), and evaluate with AP or recall at a fixed precision rather than accuracy.

In the libraries

torchvision.ops.sigmoid_focal_loss(inputs, targets, alpha=0.25, gamma=2, reduction="mean") takes raw logits, like our function. A multiclass version multiplies softmax cross-entropy by (1−py)γ(1 - p_y)^\gamma. Gradient-boosting libraries accept it as a custom objective through its gradient and second derivative.

Pitfalls

  • Expecting better calibration. The opposite happens; recalibrate or use the scores only for ranking.
  • Setting α\alpha by intuition. "Positives are rare, so give them α=0.75\alpha = 0.75" is the natural guess and was worse here and in the paper. Tune α\alpha and γ\gamma together on a validation set.
  • Computing log⁡pt\log p_t from a clipped sigmoid. Use log⁡pt=−log⁡(1+e−sz)\log p_t = -\log(1 + e^{-sz}) (-np.logaddexp(0, -s * z)) as in the code; it is exact for any logit.

Practice

  1. Compute the focal loss with γ=2\gamma = 2 and αt=1\alpha_t = 1 for pt=0.5p_t = 0.5, and compare it with cross-entropy.
Answer

Cross-entropy −log⁡0.5≈0.693-\log 0.5 \approx 0.693. Focal: (1−0.5)2⋅0.693=0.25⋅0.693≈0.173(1 - 0.5)^2 \cdot 0.693 = 0.25 \cdot 0.693 \approx 0.173, a quarter.

  1. With γ=2\gamma = 2, at what ptp_t does focal loss keep exactly 1 % of the cross-entropy?
Answer

(1−pt)2=0.01(1 - p_t)^2 = 0.01 gives 1−pt=0.11 - p_t = 0.1, so pt=0.9p_t = 0.9.

  1. Show that for γ=0\gamma = 0 the gradient formula gives p−yp - y (with αt=1\alpha_t = 1).
Answer

With γ=0\gamma = 0: s⋅(0−(1−pt))=−s(1−pt)s \cdot (0 - (1 - p_t)) = -s(1 - p_t). For y=1y = 1: s=1s = 1, pt=pp_t = p, giving p−1p - 1. For y=0y = 0: s=−1s = -1, pt=1−pp_t = 1 - p, giving p−0p - 0. Both equal p−yp - y.

Test yourself

What does the factor (1−pt)γ(1 - p_t)^{\gamma} in focal loss do?

  1. Gives more weight to the rare class
  2. Down-weights examples the model already classifies confidently and correctly
  3. Clips the gradient
  4. Smooths the labels

Which focal-loss setting is exactly (scaled) binary cross-entropy?

  1. γ=0\gamma = 0
  2. γ=2\gamma = 2
  3. α=0.25\alpha = 0.25
  4. γ=1,α=1\gamma = 1, \alpha = 1

In the lesson's tabular example, what happened to the mean predicted probability when training with focal loss?

  1. It stayed at the true positive rate
  2. It rose well above the true positive rate (0.177 and 0.327 against 0.056)
  3. It dropped to zero
  4. It became exactly 0.5

Where does focal loss give its biggest benefit?

  1. Linear regression
  2. Dense prediction such as one-stage object detection, with huge numbers of easy background examples
  3. Balanced classification with few features
  4. Clustering