Implement Huber Loss
Implement Huber Loss
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∣>δ.Function Arguments
y_true: array-like- True target valuesy_pred: array-like- Predicted valuesdelta: float = 1.0- Threshold parameter (δ)
Examples
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
Hint 1
Use np.where() to apply the piecewise formula based on |e| ≤ δ.
Hint 2
Compute absolute error with np.abs().
Hint 3
Return the mean: np.mean() to get a scalar result.
Requirements
- Return scalar mean loss across all samples
- Compute per-sample error, apply piecewise formula
- Must be vectorized (no Python loops)
- Handle arrays of any reasonable size
Constraints
- Length ≤ 10,000 samples
- delta > 0
- NumPy only; time limit: 200ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Implement Huber Loss
Implement Huber Loss
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∣>δ.Function Arguments
y_true: array-like- True target valuesy_pred: array-like- Predicted valuesdelta: float = 1.0- Threshold parameter (δ)
Examples
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
Hint 1
Use np.where() to apply the piecewise formula based on |e| ≤ δ.
Hint 2
Compute absolute error with np.abs().
Hint 3
Return the mean: np.mean() to get a scalar result.
Requirements
- Return scalar mean loss across all samples
- Compute per-sample error, apply piecewise formula
- Must be vectorized (no Python loops)
- Handle arrays of any reasonable size
Constraints
- Length ≤ 10,000 samples
- delta > 0
- NumPy only; time limit: 200ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number