Use this free focal loss calculator to see how it down-weights easy examples compared with cross-entropy. Set the probability, true label, gamma and alpha, or average over a whole batch.
Per-example loss vs cross-entropy
| # | p | y | pt | cross-entropy | focal loss |
|---|
What is focal loss?
Focal loss is a version of cross-entropy that turns down the loss on examples the model already gets right, so training concentrates on the hard ones. It was introduced by Lin et al. in 2017 for the RetinaNet object detector, where the network sees thousands of easy background boxes for every real object. With plain binary cross-entropy, those easy negatives each add a little loss, and together they swamp the few examples that matter.
The fix is one extra factor. Write \( p_t \) for the probability the model gives to the true class (so \( p_t = p \) when \( y = 1 \) and \( p_t = 1 – p \) when \( y = 0 \)). Then:
\[ \mathrm{FL}(p_t) = -\alpha_t\,(1 – p_t)^{\gamma}\,\ln(p_t) \]
Cross-entropy is the special case \( \gamma = 0 \), \( \alpha_t = 1 \). The modulating factor \( (1 – p_t)^\gamma \) is close to 0 when \( p_t \) is high (an easy, confident, correct prediction) and close to 1 when \( p_t \) is low (a hard or wrong one).
How gamma and alpha change focal loss
Gamma (\( \gamma \)) is the focusing parameter. The larger it is, the faster the loss falls away for well-classified examples. In the paper, \( \gamma = 2 \) worked best. Try it in the calculator above:
- Easy example, \( p_t = 0.9 \): cross-entropy is 0.1054, but with \( \gamma = 2 \) the loss is 0.00105, which is 100 times smaller, because \( (1 – 0.9)^2 = 0.01 \).
- Hard example, \( p_t = 0.1 \): cross-entropy is 2.3026, and the focal version is 1.8651. The factor \( (0.9)^2 = 0.81 \) keeps most of the loss.
So the easy example’s share of the total loss drops sharply, while the hard example’s loss barely changes. During training, the gradient comes mostly from the mistakes.
Alpha (\( \alpha \)) is a class-balance weight. \( \alpha_t = \alpha \) for positives and \( 1 – \alpha \) for negatives, the same idea as class weights for imbalanced datasets. A surprise from the paper: the best setting was \( \alpha = 0.25 \), which down-weights the rare positive class. That works because \( \gamma \) already removes most of the easy negatives’ loss, so the positives need less help. Leave the alpha box blank in the calculator to switch it off.
Focal loss vs cross-entropy
| Cross-entropy | Focal loss | |
|---|---|---|
| Formula | \( -\ln(p_t) \) | \( -\alpha_t (1-p_t)^\gamma \ln(p_t) \) |
| Easy examples (\( p_t \) near 1) | Small but non-zero loss each | Almost no loss |
| Hard examples (\( p_t \) near 0) | Large loss | Still large |
| Extra settings | None | \( \gamma \) and \( \alpha \) |
| Best for | Balanced classification | Heavy imbalance, many easy negatives |
If your classes are roughly balanced, it usually brings little benefit over standard cross-entropy loss. It earns its keep when one class is rare and most examples are easy, as in object detection, fraud detection or medical screening. Read more about choosing among loss functions.
Gradient and training tips
Differentiating it with the chain rule shows the same pattern: the gradient for confident correct predictions shrinks towards zero, so they stop pushing the weights. Practical points:
- Start with \( \gamma = 2 \), \( \alpha = 0.25 \), then tune with cross-validation like any other hyperparameter.
- Initialise the output bias so the model starts by predicting the rare class with low probability (RetinaNet used about 0.01). Otherwise the loss can be unstable at the start.
- Judge the model on the right metric. Accuracy hides problems with rare classes; look at precision and recall, the F1 score or ROC AUC.
- Clip probabilities away from exactly 0 and 1 before taking logs. The calculator does this at \( 10^{-12} \).
Focal loss in PyTorch
A minimal binary version, written from the formula above:
import torch
import torch.nn.functional as F
def focal_loss(logits, targets, gamma=2.0, alpha=0.25):
ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")
p = torch.sigmoid(logits)
p_t = p * targets + (1 - p) * (1 - targets)
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
return (alpha_t * (1 - p_t) ** gamma * ce).mean()
Using binary_cross_entropy_with_logits keeps the log numerically stable, because it works from the raw logits before the sigmoid. torchvision also ships a ready-made version, torchvision.ops.sigmoid_focal_loss. The original paper is Focal Loss for Dense Object Detection (arXiv).
Frequently asked questions
What does gamma do in focal loss? It sets how strongly easy examples are down-weighted. \( \gamma = 0 \) gives ordinary cross-entropy; \( \gamma = 2 \) cuts the loss on a 90%-confident correct prediction by a factor of 100.
Is focal loss only for object detection? No. It works for any classification task with heavy class imbalance or many easy examples.
Why is alpha 0.25 and not 0.75? Gamma already removes most of the loss from the many easy negatives, so the rare positives end up slightly over-weighted; \( \alpha = 0.25 \) rebalances that. It is a tuned value, not a rule.
Can focal loss be used for multi-class problems? Yes. Apply the same factor to the softmax probability of the true class: \( -\alpha_t (1-p_t)^\gamma \ln p_t \).