Problems
Loading...
1 / 1

Implement Focal Loss

Loss Functions
Medium

Implement Focal Loss for binary classification. This loss function addresses class imbalance by down-weighting easy examples and focusing training on harder ones.

Focal Loss Formula:

FL(p,y)=(1p)γylog(p)    pγ(1y)log(1p)FL(p, y) = -(1 - p)^{\gamma} \, y \log(p)\; -\; p^{\gamma} (1 - y)\log(1 - p)

where y ∈ {0,1} is true label, p is predicted probability, γ ≥ 0 controls focusing

Function Arguments

  • p: np.ndarray - Predicted probabilities, shape (N,)
  • y: np.ndarray - Binary labels {0,1}, shape (N,)
  • gamma: float = 2.0 - Focusing parameter (γ ≥ 0)
Loading visualization...

Examples

Input: p=[0.9, 0.2, 0.7, 0.1], y=[1, 0, 1, 0], gamma=2.0

Output: 0.011

Input: p=[0.5, 0.5, 0.5, 0.5], y=[1, 0, 1, 0], gamma=2.0

Output: 0.173

Input: p=[0.9, 0.2, 0.7, 0.1], y=[1, 0, 1, 0], gamma=0.0

Output: 0.198

Hint 1

Use np.clip() to prevent log(0) by clipping probabilities to a small range like [1e-15, 1-1e-15].

Hint 2

Compute both terms separately: (1-p)**gamma * y * np.log() and p**gamma * (1-y) * np.log().

Hint 3

The final loss is negative sum of both terms: -(term1 + term2), then take the mean.

Requirements

  • Input p must already be probabilities (no sigmoid inside function)
  • Compute elementwise loss using the formula above
  • Return scalar mean loss across all samples
  • Must be vectorized (no Python loops)

Constraints

  • 0 < p < 1 (probabilities)
  • 0 ≤ γ ≤ 5
  • N ≤ 1e6 samples
  • NumPy only; time limit: 300ms
Try Similar Problems