Skip to content

← Loss Functions step 6 of 8

Medium Research

Focal Loss

Focal loss reduces the contribution of easy classification examples. It starts with cross-entropy and multiplies it by a factor that is small when the model already assigns high probability to the correct label.

For a binary target, let p be the predicted probability of label 1. The probability of the correct label, pt, is p for target 1 and 1 - p for target 0. The class weight, at, is alpha for target 1 and 1 - alpha for target 0.

The focal term is (1 - pt) ** gamma. With gamma = 2, a correct-label probability of 0.9 gives a multiplier of 0.01, while 0.5 gives 0.25. Thus easy examples contribute less, relative to hard examples. alpha separately controls the relative weighting of the two labels.

Your task

Implement focal_loss(probs, targets, alpha, gamma) for nonempty 1D tensors of matching shape. probs contains probabilities in [0, 1]; targets contains binary labels 0 or 1. alpha is a float in [0, 1], and gamma is a nonnegative float.

Compute the mean of

-at * (1 - pt) ** gamma * log(pt + 1e-8)

using natural logarithms. The added 1e-8 is this exercise's explicit finite-log convention. Add it only inside the logarithm; do not change the focal multiplier or substitute probability clamping.

For probs = [0.9], targets = [1], alpha = 1, and gamma = 2, the result is approximately 0.0010536. When gamma = 0, the focal multiplier is 1, leaving class-weighted cross-entropy with the stated epsilon. This is not unweighted BCE: for example, alpha = 1 ignores all target-0 examples.

Return a Python float. Rounding to seven decimal places is optional. For training, keep the result as a tensor instead so gradients remain available. The original focal-loss paper explains its use for dense object detection.

For comparison, the plot below shows ordinary binary cross-entropy. It does not include focal loss's class weight or focusing factor, and uses the chart's own probability-clamping rule.

Loading visualization…