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 for the probability the model gives to the true class: if and if . Binary cross-entropy is . Focal loss is
- The focusing parameter controls the modulating factor . For a well-classified example ( near 1) the factor is near 0; for a badly classified one ( small) it is near 1, so hard examples keep almost their full cross-entropy. gives back cross-entropy; the paper found best.
- The balancing weight is for positives and for negatives, the usual class weighting. Surprisingly, the paper's best value was , which gives the rare positives less weight: once has silenced the easy negatives, the positives no longer need a boost.
The gradient with respect to the logit , writing for positives and for negatives (so ), is
With and it reduces to , 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 . The other columns are the modulating factor , the fraction of that cross-entropy focal loss keeps (with switched off).
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 , an easy example at keeps 0.25 % of its cross-entropy (a factor of 400 less), while a hard one at 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 is exactly half of binary cross-entropy (the 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.
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 and 0.306 at . 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 . 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 by intuition. "Positives are rare, so give them " is the natural guess and was worse here and in the paper. Tune and together on a validation set.
- Computing from a clipped sigmoid. Use (
-np.logaddexp(0, -s * z)) as in the code; it is exact for any logit.
Practice
- Compute the focal loss with and for , and compare it with cross-entropy.
Answer
Cross-entropy . Focal: , a quarter.
- With , at what does focal loss keep exactly 1 % of the cross-entropy?
Answer
gives , so .
- Show that for the gradient formula gives (with ).
Answer
With : . For : , , giving . For : , , giving . Both equal .
Test yourself
What does the factor in focal loss do?
- Gives more weight to the rare class
- Down-weights examples the model already classifies confidently and correctly
- Clips the gradient
- Smooths the labels
Which focal-loss setting is exactly (scaled) binary cross-entropy?
In the lesson's tabular example, what happened to the mean predicted probability when training with focal loss?
- It stayed at the true positive rate
- It rose well above the true positive rate (0.177 and 0.327 against 0.056)
- It dropped to zero
- It became exactly 0.5
Where does focal loss give its biggest benefit?
- Linear regression
- Dense prediction such as one-stage object detection, with huge numbers of easy background examples
- Balanced classification with few features
- Clustering