Focal Loss: Turning Down the Easy Examples

Loss FunctionsMedium+10 XP+10

Focal Loss: Turning Down the Easy Examples

Cross-entropy weighs every example the same. In a dataset dominated by easy negatives, that means the loss is mostly spent on examples the model already gets right, drowning out the few hard ones. Focal loss down-weights the easy, well-classified examples so training focuses on what's still wrong.

Let p_t be the model's predicted probability for the true class:

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

Task: write focal_loss(y_true, y_pred, alpha, gamma) for binary labels, returning the mean loss, rounded to 4 decimal places.

  • p_t is y_pred when the true label is 1, and 1 - y_pred when it's 0.
  • gamma = 0 collapses focal loss back to plain weighted cross-entropy — there's no down-weighting left.

Examples

y_true = [1, 0, 1]
y_pred = [0.9, 0.1, 0.6]
alpha = 0.25
gamma = 2.0
returns 0.007
y_true = [1, 1, 0, 0]
y_pred = [0.5, 0.5, 0.5, 0.5]
alpha = 1.0
gamma = 0.0
returns 0.6931

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run