Focal Loss for Imbalanced Data

medium
Unit 17 · Normalisation0/3 to milestone

When 99% of examples are easy negatives (background in object detection, legitimate transactions in fraud), their small losses still add up and swamp the rare positives. Focal loss down-weights easy examples:

FL(pt)=−αt(1−pt)γlog⁡(pt)\text{FL}(p_t) = -\alpha_t (1 - p_t)^\gamma \log(p_t)

where for a binary label yy and predicted probability pp: pt=pp_t = p if y=1y = 1, else 1−p1 - p; and αt=α\alpha_t = \alpha if y=1y = 1, else 1−α1 - \alpha.

Implement focal_loss(logits, y, alpha=0.25, gamma=2.0) returning the mean loss. Compute log⁡pt\log p_t stably from the logits: log⁡p=−softplus(−z)\log p = -\text{softplus}(-z) and log⁡(1−p)=−softplus(z)\log(1-p) = -\text{softplus}(z), using np.logaddexp(0, ·). With gamma=0 and alpha=0.5 it equals half the binary cross-entropy.

#loss-functions#imbalanced-data#detection2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Focal Loss for Imbalanced Data · TechGradify