Implement the Huber Loss function (also called Smooth L1 Loss). It behaves like MSE for small errors and like MAE for large errors, controlled by a threshold parameter delta.
import numpy as np
def huber_loss(y_true: np.ndarray, y_pred: np.ndarray,
delta: float = 1.0) -> float:
y_true = np.array(y_true, dtype=float)
y_pred = np.array(y_pred, dtype=float)
residual = np.abs(y_true - y_pred)
loss = np.where(
residual <= delta,
0.5 * residual ** 2,
delta * residual - 0.5 * delta ** 2
)
return float(np.mean(loss))|y_true - y_pred| for each element.0.5 * residual^2 (like MSE).delta * |residual| - 0.5 * delta^2 (like MAE, shifted to be continuous).