Problems
Loading...
1 / 1

Implement Huber Loss

Loss Functions
Easy

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)={12e2,if eδ,δ(e12δ),if e>δ.L_{\delta}(e) = \begin{cases} \frac{1}{2} e^{2}, & \text{if } |e| \le \delta, \\ \delta\left(|e| - \frac{1}{2}\delta\right), & \text{if } |e| > \delta. \end{cases}

Function Arguments

  • y_true: array-like - True target values
  • y_pred: array-like - Predicted values
  • delta: float = 1.0 - Threshold parameter (δ)
Loading visualization...

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.5e20.5 \cdot e^2

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: δ(e0.5δ)\delta \cdot (|e| - 0.5 \cdot \delta)

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