Huber & Hinge losses
Background
Two robust margin/regression losses. Huber loss blends squared error (for small residuals) with absolute error (for large ones), so a few outliers don't dominate the gradient — the standard robust regression loss. Hinge loss is the SVM loss: it penalises predictions that are correct but not confident, enforcing a margin.
Problem statement
Implement two functions.
huber_loss(pred, target, delta=1.0) — the mean over elements of, with :
hinge_loss(pred, target) — the mean of with labels :
Input
pred—np.ndarray: predictions (raw scores for hinge).target—np.ndarray: targets (real values for Huber; labels for hinge).delta—float(Huber only): the transition point between the quadratic and linear regimes.
Output
Each function returns a float: the mean loss.
Examples
Example 1 — Huber
Input: huber_loss([1, 2, 3], [1.5, 4, 3], delta=1.0)
Output: 0.5417
Explanation: residuals . The small one is quadratic ; the large one is linear ; the zero contributes 0. Mean .
Example 2 — Hinge
Input: hinge_loss([0.8, -0.5, 2], [1, -1, 1])
Output: 0.2333
Explanation: margins , so losses and the mean is .
Constraints
- Huber is quadratic when and linear () beyond — the two pieces meet smoothly at .
- Hinge labels are ; points correctly classified beyond the margin () contribute 0.
- Both functions return the mean over elements.
Notes
- As Huber becomes MSE; as it becomes (scaled) MAE — it interpolates between the two.
- Hinge is non-smooth at the margin; its sub-gradient is when and otherwise, exactly what the SVM/Pegasos update uses.
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Huber reference: 0.5417
- •Huber equals MSE/2 for small residuals
- •Hinge reference: 0.2333
- •Hinge is 0 when all points are beyond the margin