Overview
Squared error is smooth and precise near the target but lets one wild data point dominate, because its penalty grows with the square of the error. Absolute error treats outliers gently but has a corner at zero and a constant-size gradient that makes fine convergence awkward. Huber loss joins the two. Within a threshold of the target it behaves like squared error. Beyond the threshold it continues as a straight line with the slope it had at the threshold. The gradient is therefore the error itself, clipped to a fixed range.
A short history
Peter Huber introduced this loss in the 1964 paper 'Robust Estimation of a Location Parameter', a founding work of robust statistics. Squared error lets a few outliers dominate, and absolute error is not smooth at zero. Huber's loss is quadratic near zero and linear beyond a threshold. Deep learning adopted it as smooth L1 in Fast R-CNN in 2015 for box regression, and deep Q-learning uses the same idea to limit the size of updates.
How it works
- Compute the error as prediction minus target for each element.
- If , the loss is .
- If , the loss is , a line that meets the parabola at with matching slope.
- If
smooth_l1is on, divide by . - Reduce over all elements with
reduction. - In
backward, the gradient is clipped to , divided by for smooth-L1 and by the element count for the mean.
Watch out for
- The threshold is in the units of the target. If targets are rescaled and is not, the loss quietly becomes all quadratic or all linear.
- With too large it is just squared error and outliers dominate again. With too small it is absolute error with a tiny rounded tip.
- Huber and smooth-L1 differ by the factor and coincide only at . Mixing up the two conventions rescales the gradient.
- The second derivative jumps at . That is rarely a problem for gradient descent but can matter for second-order methods.
Use cases
When to use it
Regression with occasional outliers or heavy-tailed noise, such as bounding-box regression in detection and value targets in reinforcement learning.
In industry
- Object detection
- Detectors in the Fast R-CNN family regress bounding box coordinates with smooth L1 so that badly matched boxes do not dominate the gradient.
- Reinforcement learning
- Deep Q-network implementations commonly use Huber loss on the temporal difference error to keep updates bounded.
- Demand and price forecasting
- Forecasters use Huber loss when most errors are small but occasional spikes, such as promotions or outages, would distort a squared error fit.
Choosing it: what must hold
- A regression target with mostly moderate errors and some outliers you do not want to drive the fit.
- A threshold delta set on the scale of the errors you consider normal.
- Targets in consistent units, or normalised, so that one threshold makes sense for all outputs.
When to choose something else
| If | Use instead |
|---|---|
| Errors are well behaved with no heavy outliers | Mean squared error |
| Outliers are frequent and you want the median prediction | Mean absolute error |
| You need a full predictive distribution, not a single value | Mixture density loss |
Math foundations
The loss
A parabola in the middle and straight lines outside. The constant in the linear branch makes the two pieces meet at .
Its gradient
The squared-error gradient with its size capped at . No single example can pull harder than that, which is where the robustness comes from.
Smooth-L1
The same shape, rescaled so the linear part has slope 1 like absolute error. This is the form used in object detection.
The two limits
A very large threshold gives half the squared error. A very small one, after rescaling, gives the absolute error. Huber interpolates between them.
Symbols
- the error, prediction minus target
- the threshold between the two regimes,
deltain the config, default 1 - the Huber loss for one element
- +1 for positive e, -1 for negative e
- e limited to the range from minus delta to delta
Worked by hand
Threshold . Compute the loss and gradient for a small error and an outlier .
The outlier costs 2.5 instead of 4.5, and its pull on the model is 1 instead of 3. The small error is treated exactly as squared error would.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import HuberLoss
from config import HuberLossConfig
loss = HuberLoss(HuberLossConfig(delta=1.0))
pred, target = np.array([0.5, 3.0, -2.0]), np.zeros(3)
print(loss.forward(pred, target)) # (0.125 + 2.5 + 1.5) / 3 = 1.375
print(loss.backward(pred, target)) # [0.1667, 0.3333, -0.3333]: the error, clipped to +-delta, over 3Read the implementation (65 lines)
"""Huber loss: 0.5 * e^2 for |e| <= delta, delta * (|e| - 0.5 * delta) beyond, with e = pred - target.
NumPy only. `forward` returns the loss, `backward` its gradient with respect to the prediction.
"""
from __future__ import annotations
import numpy as np
try:
from .config import HuberLossConfig
except ImportError: # run from the template's own folder
from config import HuberLossConfig
def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
"""Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
if pred.shape != target.shape:
raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
return pred, target
def _reduce(values: np.ndarray, reduction: str):
"""Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
if reduction == "mean":
return float(values.mean())
if reduction == "sum":
return float(values.sum())
return values
def _grad_scale(count: int, reduction: str) -> float:
"""Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
return 1.0 / count if reduction == "mean" else 1.0
class HuberLoss:
"""Quadratic near zero error, linear for large errors. Optionally scaled into smooth-L1."""
def __init__(self, config: HuberLossConfig | None = None) -> None:
self.config = config or HuberLossConfig()
def forward(self, pred: np.ndarray, target: np.ndarray):
"""pred, target: same shape, any number of axes. Returns a float, or the per-element array for "none"."""
pred, target = _pair(pred, target)
delta = self.config.delta
abs_err = np.abs(pred - target)
values = np.where(abs_err <= delta, 0.5 * abs_err**2, delta * (abs_err - 0.5 * delta))
if self.config.smooth_l1:
values = values / delta
return _reduce(values, self.config.reduction)
def backward(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Gradient of the reduced loss with respect to pred, same shape as pred.
The per-element derivative is the error clipped to [-delta, delta] (divided by delta for smooth-L1).
For "none" it is returned unscaled (the gradient of the sum).
"""
pred, target = _pair(pred, target)
delta = self.config.delta
local = np.clip(pred - target, -delta, delta)
if self.config.smooth_l1:
local = local / delta
return local * _grad_scale(pred.size, self.config.reduction)
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build HuberLoss(HuberLossConfig(delta=1.0, reduction="none")) and evaluate forward and backward on errors from -4 to 4 against a zero target. Add a single target that is off by 100 to a batch of ten and compare the mean gradient with that of delta=1000.0.
Check on learning
- How would you choose for a dataset whose residuals are mostly within 2 units but occasionally reach 50?
A way to think about it
The threshold should sit where ordinary errors end and outliers begin. Look at a histogram of residuals from a first rough fit.
- A model trained with squared error predicts the mean of the targets, and one trained with absolute error predicts the median. What does a Huber-trained model predict?
A way to think about it
Near the bulk of the data it averages, far from it each point counts only by its sign. The result lies between mean and median, closer to one or the other as changes.
- In reinforcement learning the targets themselves are noisy estimates that can be far off early on. Why is a clipped gradient helpful there?
A way to think about it
A wildly wrong target under squared error produces a huge update that can destabilise the network. Compare the largest possible update under each loss.
- Your targets were in metres and are now in millimetres, with left at 1. What changed in the behaviour of the loss?
A way to think about it
Every error is now 1000 times larger in number. Decide which branch almost all of them now fall in.