All problems
MediumLoss & Trainingv2026-06-29

Loss & Training ยท Medium

Focal Loss

Implement Focal Loss with production-minded edge case handling.

Task

Implement binary_focal_loss(logits: list[float], targets: list[int], gamma: float, alpha: float) -> float. Compute mean binary focal loss directly from logits using a numerically stable binary cross-entropy calculation.

Requirements

  • logits and targets have the same shape, and every target is either 0 or 1.
  • gamma is non-negative, and alpha is in [0, 1].
  • Compute binary cross-entropy directly from each logit; do not first form probabilities and take their logarithms.
  • For a positive target use p_t = sigmoid(logit) and alpha_t = alpha; for a negative target use p_t = 1 - sigmoid(logit) and alpha_t = 1 - alpha.
  • Compute each loss as alpha_t * (1 - p_t) ** gamma * BCE-with-logits.
  • Return the arithmetic mean of the per-example losses, or 0.0 when the inputs are empty.
  • Do not modify the inputs.

Example

logits = [0.0, 0.0]
targets = [1, 0]

binary_focal_loss(logits, targets, gamma=2.0, alpha=0.25)
# 0.0866433976
solution.pySign in to save
Public tests run locally in your browser.
Run your code to see public test results.