Implement Huber Loss, a robust regression loss that is less sensitive to outliers than Mean Squared Error. It behaves like L2 loss near zero and L1 loss when the error is large.
Huber Loss Formula:
For prediction error e = y_true - y_pred:
Lδ(e)={21e2,δ(∣e∣−21δ),if ∣e∣≤δ,if ∣e∣>δ.y_true: array-like - True target valuesy_pred: array-like - Predicted valuesdelta: float = 1.0 - Threshold parameter (δ)Input: y_true=[1, 2, 3], y_pred=[1.5, 1.7, 2.5], delta=1.0
Output: 0.0983
Errors [0.5, 0.3, 0.5] are all within delta, so the quadratic (L2) formula applies: mean of 0.5⋅e2
Input: y_true=[0, 5], y_pred=[2, 8], delta=1.0
Output: 2.0
Errors [2, 3] both exceed delta, so the linear (L1) formula applies: δ⋅(∣e∣−0.5⋅δ)
Input: y_true=[1, 2], y_pred=[1, 2], delta=1.0
Output: 0.0
Perfect predictions result in zero loss
Use np.where() to apply the piecewise formula based on |e| ≤ δ.
Compute absolute error with np.abs().
Return the mean: np.mean() to get a scalar result.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Implement Huber Loss, a robust regression loss that is less sensitive to outliers than Mean Squared Error. It behaves like L2 loss near zero and L1 loss when the error is large.
Huber Loss Formula:
For prediction error e = y_true - y_pred:
Lδ(e)={21e2,δ(∣e∣−21δ),if ∣e∣≤δ,if ∣e∣>δ.y_true: array-like - True target valuesy_pred: array-like - Predicted valuesdelta: float = 1.0 - Threshold parameter (δ)Input: y_true=[1, 2, 3], y_pred=[1.5, 1.7, 2.5], delta=1.0
Output: 0.0983
Errors [0.5, 0.3, 0.5] are all within delta, so the quadratic (L2) formula applies: mean of 0.5⋅e2
Input: y_true=[0, 5], y_pred=[2, 8], delta=1.0
Output: 2.0
Errors [2, 3] both exceed delta, so the linear (L1) formula applies: δ⋅(∣e∣−0.5⋅δ)
Input: y_true=[1, 2], y_pred=[1, 2], delta=1.0
Output: 0.0
Perfect predictions result in zero loss
Use np.where() to apply the piecewise formula based on |e| ≤ δ.
Compute absolute error with np.abs().
Return the mean: np.mean() to get a scalar result.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number