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)=−(1−p)γylog(p)−pγ(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)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
Use np.clip() to prevent log(0) by clipping probabilities to a small range like [1e-15, 1-1e-15].
Compute both terms separately: (1-p)**gamma * y * np.log() and p**gamma * (1-y) * np.log().
The final loss is negative sum of both terms: -(term1 + term2), then take the mean.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
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)=−(1−p)γylog(p)−pγ(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)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
Use np.clip() to prevent log(0) by clipping probabilities to a small range like [1e-15, 1-1e-15].
Compute both terms separately: (1-p)**gamma * y * np.log() and p**gamma * (1-y) * np.log().
The final loss is negative sum of both terms: -(term1 + term2), then take the mean.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number