Focal Loss for Segmentation
Focal loss multiplies cross-entropy by a factor that fades easy background pixels to near zero, leaving rare edge and lesion pixels in charge.
Why Does This Exist?
In dense masks percent or more of pixels are easy background the model masters in epoch one, yet plain cross-entropy keeps summing their small losses until they drown the few lesion and boundary pixels. Dice fixes this with overlap scoring; focal loss (Lin et al., 2017, adapted from detection to masks) fixes it by reweighting: multiply each pixel's cross-entropy by with , where is the predicted probability of the true class. Easy pixels fade; hard ones rule.
For the glossary entry see the focal loss definition. This page is the segmentation variant with per-pixel behaviour and numbers.
Think of It Like This
A coach who stops drilling mastered scales
A piano coach hears forty easy scales played right and two hard passages fumbled. Equal attention wastes the hour on scales. Focal loss hands the coach a volume knob wired to mastery: confident passages fade to a whisper, fumbled bars play loudly. Practice time flows to the failures.
Where it stops: the knob needs tuning. Too high a gamma mutes useful reinforcement and the easy passages drift back out of tune.
How It Actually Works
Per pixel with true-class probability and balance factor :
With : a background pixel at contributes of its cross-entropy, while an edge pixel at keeps . The easy pixel is downweighted roughly relative to the hard one before balancing. for foreground is the standard starting point from RetinaNet practice.
Worked example
Two pixels, , no . Easy: , cross-entropy , focal . Hard: , cross-entropy , focal . Ratio hard-to-easy rises from about to about . That is why boundaries finally move.
Code
import math
def focal(pt: float, gamma: float = 2.0) -> float: return -((1 - pt) ** gamma) * math.log(pt)
print(round(focal(0.9), 4), round(focal(0.3), 4))# -> (0.0011, 0.59)Watch Out For
Gamma so high the model forgets easy regions
mutes background so hard that late-training drift reintroduces holes inside confident areas. Symptom: speckled interiors while edges look great. Fix: start at , and combine with Dice if interiors destabilize.
Applying detection alpha blindly to masks
RetinaNet's assumes box imbalance, not your organ ratio. Symptom: foreground recall stuck low despite focal loss. Fix: set from your pixel frequencies and validate per-class recall, not just mean loss.
The Quick Version
- Focal loss multiplies cross-entropy by per pixel.
- Confident background pixels fade by or more; hard pixels dominate.
- Standard start: , foreground , then tune to your frequencies.
- Complements Dice: focal mines hard pixels, Dice guards global overlap.
- Too much gamma destabilizes confident interiors.