Down-weight easy examples with focal loss

MediumLosses

In object detection almost every box is easy background. Focal loss multiplies cross-entropy by (1 - p_t) ** gamma so easy examples, where p_t is near 1, barely count.

For binary targets: p = sigmoid(z), p_t = p if y == 1 else 1 - p, alpha_t = alpha if y == 1 else 1 - alpha.
loss = -alpha_t (1 - p_t) ** gamma log(p_t)

Write focal_loss(z, y, alpha=0.25, gamma=2.0) returning the mean as a float. Compute log(p_t) stably from the logits.

Signaturedef focal_loss(z, y, alpha=0.25, gamma=2.0)

Understand the idea

Focal loss is cross-entropy with a volume knob that turns down easy examples. p_t is the probability the model gives to the true class. The factor (1 - p_t)^gamma is almost 0 when the model is already confident and right, and near 1 when it is wrong, so training focuses on hard cases. Like a teacher spending time on the questions students got wrong. alpha_t adds class weighting. Worked example, alpha = 0.25, gamma = 2, y = 1. For z = 2: p_t = 0.881, (1 - 0.881)^2 = 0.0142, -log(0.881) = 0.127, loss = 0.25 x 0.0142 x 0.127 = 0.00045. For z = -2: p_t = 0.119, (0.881)^2 = 0.776, -log(0.119) = 2.127, loss = 0.25 x 0.776 x 2.127 = 0.413, about 900 times larger. Rule: loss = -alpha_t (1 - p_t)^gamma log(p_t), mean over elements, with log(p_t) computed stably as a log-sigmoid of z or -z. Object detectors like RetinaNet use focal loss.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: mixedfocal_loss([2.0, -1.0, 0.5, -3.0], [1, 0, 0, 1])
  • Sample 2: gamma 0 is weighted BCEfocal_loss([1.0, -2.0], [1, 0], alpha=0.5, gamma=0.0)
  • Test 3: extreme logits finitefocal_loss([200.0, -200.0], [0, 0])