KatInterview

Numerically Stable Focal Loss from Raw Scores

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationnumerical-stabilitysigmoidloss-function

Last updated

Implement a class-weighted, focus-modulated binary cross-entropy directly from logits in pure Python, with stable math, input validation and sum/mean/none reductions.

Stable Focal Loss

When positives are very rare, a plain binary cross-entropy is dominated by the huge number of easy negatives. Focal loss counters this by scaling each example's cross-entropy by two factors: a class weight and a "difficulty" factor that shrinks toward zero for examples the model already gets right.

Write a function that computes this loss from raw scores (logits) using plain Python lists. Do not build the loss by computing a probability and then taking its logarithm, because that breaks for extreme scores such as -1000 or 1000.

Definition

For a score z and a label y in {0, 1}:

  • p = 1 / (1 + exp(-z))
  • p_t = p if y == 1, otherwise 1 - p
  • Class weight w_t:
    • if alpha == -1, then w_t = 1 for every example (weighting disabled);
    • otherwise w_t = alpha when y == 1 and w_t = 1 - alpha when y == 0.
  • Per-example loss: w_t * (1 - p_t)^gamma * (-log(p_t))

When gamma == 0, the difficulty factor is exactly 1, and the loss is just weighted cross-entropy.

Task

Implement the function with the signature given in the starter code. Parameters:

  • scores: list of raw logits (floats or ints).
  • labels: list of the same length containing 0/1 (ints or floats).
  • alpha: positive-class weight, or the sentinel -1 to disable class weighting.
  • gamma: non-negative focusing exponent.
  • reduction: one of "none", "sum", "mean".

Output

  • "none": a list of per-example losses, in input order.
  • "sum": a single float, the sum of the per-example losses.
  • "mean": a single float, the sum divided by the number of examples. For empty input, return 0.0.

Validation

Raise ValueError if:

  • scores and labels have different lengths;
  • reduction is not one of the three allowed strings;
  • gamma < 0;
  • any label is not 0 or 1.

Numerical requirements

  • Results must be finite for any finite score, including magnitudes in the hundreds or thousands. Never exponentiate a large positive number.
  • Use an accurately rounded summation (for example math.fsum) when adding up losses.

Constraints

  • 0 <= len(scores) <= 10^6
  • scores[i] is a finite real number of any magnitude (e.g. |z| up to 10^4)
  • labels[i] is 0, 1, 0.0 or 1.0
  • gamma >= 0
  • alpha is either -1 or a real number (typically in [0, 1])

Examples

Example 1

Input: stable_focal_loss([0, 2, -2], [1, 1, 0], 0.25, 2, 'mean')

Output: 0.01504175387341232

Example 2

Input: stable_focal_loss([-1000, 1000], [0, 1], 0.5, 2, 'none')

Output: [0, 0]

Example 3

Input: stable_focal_loss([0], [1], 0.25, 0, 'mean')

Output: 0.17328679513998632

Example 4

Input: stable_focal_loss([0, 2, -2], [1, 1, 0], -1, 0, 'mean')

Output: 0.31566773421529676

Hints

Hint 1

The negative log of p_t equals the cross-entropy, which can be written as max(z, 0) - z*y + log1p(exp(-|z|)). The exponent is never positive, so it cannot overflow.

Hint 2

Since 1 - sigmoid(z) = sigmoid(-z), the difficulty base 1 - p_t is sigmoid(-z) for positive labels and sigmoid(z) for negative labels. Evaluate sigmoid with two branches so that exp only ever sees a non-positive argument.

Hint 3

Handle the special cases explicitly: alpha == -1 gives weight 1, gamma == 0 gives factor 1, and an empty list under 'mean' returns 0.0. Validate inputs before computing.