Huber Loss: Gentle on Outliers

Loss FunctionsEasy+10 XP+10

Huber Loss: Gentle on Outliers

MSE punishes large errors quadratically, so a single wild outlier can dominate the whole loss. MAE treats every error the same regardless of size, but its gradient never shrinks even for tiny errors near zero. Huber loss is a compromise: quadratic for small errors, linear for large ones.

Let a = y_true - y_pred be the residual for one sample:

Lδ(a)={12a2∣a∣≤δδ(∣a∣−12δ)otherwiseL_\delta(a) = \begin{cases} \frac{1}{2}a^2 & |a| \le \delta \\ \delta\left(|a| - \frac{1}{2}\delta\right) & \text{otherwise} \end{cases}Lδ​(a)={21​a2δ(∣a∣−21​δ)​∣a∣≤δotherwise​

Task: write huber_loss(y_true, y_pred, delta) returning the mean loss over all samples, rounded to 4 decimal places.

  • delta is the threshold where the loss switches from quadratic to linear.
  • The two pieces meet smoothly at |a| = delta — both give 0.5 * delta**2 there.

Examples

y_true = [3.0, -1.0, 5.0]
y_pred = [2.5, -1.0, 8.0]
delta = 1.0
returns 0.875
y_true = [0.0, 0.0]
y_pred = [0.5, -0.5]
delta = 1.0
returns 0.125

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run