MediumLoss Functions

Binary Focal Loss

Loss Functions

Medium

Problem

Binary focal loss addresses the class imbalance problem in binary classification by down-weighting the loss contribution from easy (well-classified) examples. This allows the model to focus training on hard, misclassified examples. It was introduced in the RetinaNet paper for object detection.

Given predicted probabilities, binary targets, a balancing factor alpha, and a focusing parameter gamma, compute the mean binary focal loss.

Algorithm

For each sample, let p be the predicted probability and y be the target (0 or 1):

  1. Compute the probability assigned to the true class:

p_t = p \quad \text{if } y = 1

p_t = 1 - p \quad \text{if } y = 0

  1. Compute the focal loss for this sample:

FL = -\alpha \cdot (1 - p_t)^{\gamma} \cdot \ln(p_t)

  1. Return the mean focal loss across all samples.

Return the mean focal loss as a float.

Theory

In many binary classification tasks, one class is much more common than the other:

Standard binary cross-entropy treats all samples equally. This causes problems:

During training:

The loss breakdown:


What Focal Loss Does

Focal loss adds a modulating factor that down-weights easy examples:

\text{FL}(p_t) = -\alpha_t (1 - p_t)^\gamma \log(p_t)

Where:

The modulating factor (1 - p_t)^\gamma is small when p_t is high (easy examples) and large when p_t is low (hard examples).


Breaking Down the Formula

For binary classification:

p_t = \begin{cases} p & \text{if } y = 1 \\ 1 - p & \text{if } y = 0 \end{cases}

Where p is the model's predicted probability for class 1.

Expanded formula:

\text{FL} = \begin{cases} -\alpha (1 - p)^\gamma \log(p) & \text{if } y = 1 \\ -(1 - \alpha) \cdot p^\gamma \log(1 - p) & \text{if } y = 0 \end{cases}

Two components work together:


How the Focusing Factor Works

Let us compute the modulating factor (1 - p_t)^\gamma for \gamma = 2:

Confidence 0.9 (very confident): factor = 0.01, giving 100x reduction Confidence 0.8: factor = 0.04, giving 25x reduction Confidence 0.6: factor = 0.16, giving 6x reduction Confidence 0.5 (uncertain): factor = 0.25, giving 4x reduction Confidence 0.3: factor = 0.49, giving 2x reduction Confidence 0.1 (wrong): factor = 0.81, minimal reduction

Key insight:


The Effect of Gamma

\gamma controls how aggressively easy examples are down-weighted:

gamma = 0:

gamma = 1:

gamma = 2 (most common):

gamma = 5:


The Alpha Parameter

Alpha is a class balancing weight:

Common settings:

Example with 99% negatives, 1% positives:


Comparing Losses on Easy vs. Hard Examples

Example: positive sample (y = 1)

Prediction 0.9: BCE = 0.105, Focal = 0.001, ratio = 105x smaller Prediction 0.7: BCE = 0.357, Focal = 0.032, ratio = 11x smaller Prediction 0.5: BCE = 0.693, Focal = 0.173, ratio = 4x smaller Prediction 0.3: BCE = 1.204, Focal = 0.590, ratio = 2x smaller Prediction 0.1: BCE = 2.303, Focal = 1.866, ratio = 1.2x smaller

Observation:


The Gradient

The gradient of focal loss is more complex than cross-entropy:

\frac{\partial \text{FL}}{\partial p} = -\alpha_t \left[ \gamma (1 - p_t)^{\gamma - 1} \log(p_t) + (1 - p_t)^\gamma \cdot \frac{1}{p_t} \right] \cdot \frac{\partial p_t}{\partial p}

Key properties:


Where Focal Loss Is Used

Object detection:

Medical imaging:

Fraud detection:

Any highly imbalanced binary classification task


Practical Tips

Examples

Example 1

Input
predictions = [0.9], targets = [1], alpha = 1, gamma = 2
Output
0.001054
Explanation
The factor (1 - 0.9)² strongly reduces the loss of this confident correct prediction.

Example 2

Input
predictions = [0.1], targets = [1], alpha = 1, gamma = 2
Output
1.865094

Hints

  1. Select p when the target is 1 and one minus p when the target is 0.
  2. Accumulate the focal term with math.log, then divide by the sample count.

Requirements

Constraints

Starter Code

import math

def binary_focal_loss(predictions: list, targets: list, alpha: float, gamma: float) -> float:
    """
    Returns the mean binary focal loss as a float.
    """
    # Write code here
    pass

Test Cases

CaseMatches
Confident correct predictionpublic
Wrong predictionpublic