Down-weight easy examples with focal loss
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.
def 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.