Sign in

Huber

Huber loss (smooth L1)

A regression loss that is quadratic for small errors and linear for large ones, so it is smooth near zero and resistant to outliers.

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 δ\delta 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

  1. Compute the error ee as prediction minus target for each element.
  2. If ∣e∣≤δ|e| \le \delta, the loss is 12e2\tfrac{1}{2} e^{2}.
  3. If ∣e∣>δ|e| > \delta, the loss is δ (∣e∣−12δ)\delta\,(|e| - \tfrac{1}{2}\delta), a line that meets the parabola at δ\delta with matching slope.
  4. If smooth_l1 is on, divide by δ\delta.
  5. Reduce over all elements with reduction.
  6. In backward, the gradient is ee clipped to [−δ,δ][-\delta, \delta], divided by δ\delta for smooth-L1 and by the element count for the mean.

Watch out for

  • The threshold δ\delta is in the units of the target. If targets are rescaled and δ\delta is not, the loss quietly becomes all quadratic or all linear.
  • With δ\delta too large it is just squared error and outliers dominate again. With δ\delta too small it is absolute error with a tiny rounded tip.
  • Huber and smooth-L1 differ by the factor 1/δ1/\delta and coincide only at δ=1\delta = 1. Mixing up the two conventions rescales the gradient.
  • The second derivative jumps at ∣e∣=δ|e| = \delta. 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

IfUse instead
Errors are well behaved with no heavy outliersMean squared error
Outliers are frequent and you want the median predictionMean absolute error
You need a full predictive distribution, not a single valueMixture density loss

Math foundations

  1. The loss

    Lδ(e)={12 e2,∣e∣≤δδ (∣e∣−12δ),∣e∣>δL_\delta(e) = \begin{cases} \tfrac{1}{2}\,e^{2}, & |e| \le \delta \\ \delta\,\big(|e| - \tfrac{1}{2}\delta\big), & |e| > \delta \end{cases}

    A parabola in the middle and straight lines outside. The constant −12δ2-\tfrac{1}{2}\delta^{2} in the linear branch makes the two pieces meet at ∣e∣=δ|e| = \delta.

  2. Its gradient

    dLδde={e,∣e∣≤δδ sign⁡(e),∣e∣>δ  =  clip⁡(e,−δ,δ)\frac{dL_\delta}{de} = \begin{cases} e, & |e| \le \delta \\ \delta\,\operatorname{sign}(e), & |e| > \delta \end{cases} \;=\; \operatorname{clip}(e, -\delta, \delta)

    The squared-error gradient with its size capped at δ\delta. No single example can pull harder than that, which is where the robustness comes from.

  3. Smooth-L1

    SmoothL1⁡δ(e)=Lδ(e)δ={e22δ,∣e∣≤δ∣e∣−12δ,∣e∣>δ\operatorname{SmoothL1}_\delta(e) = \frac{L_\delta(e)}{\delta} = \begin{cases} \dfrac{e^{2}}{2\delta}, & |e| \le \delta \\[4pt] |e| - \tfrac{1}{2}\delta, & |e| > \delta \end{cases}

    The same shape, rescaled so the linear part has slope 1 like absolute error. This is the form used in object detection.

  4. The two limits

    lim⁡δ→∞Lδ(e)=12 e2,lim⁡δ→0Lδ(e)δ=∣e∣\lim_{\delta \to \infty} L_\delta(e) = \tfrac{1}{2}\,e^{2}, \qquad \lim_{\delta \to 0} \frac{L_\delta(e)}{\delta} = |e|

    A very large threshold gives half the squared error. A very small one, after rescaling, gives the absolute error. Huber interpolates between them.

Symbols

ee
the error, prediction minus target
δ\delta
the threshold between the two regimes, delta in the config, default 1
LδL_\delta
the Huber loss for one element
sign⁡(e)\operatorname{sign}(e)
+1 for positive e, -1 for negative e
clip⁡(e,−δ,δ)\operatorname{clip}(e, -\delta, \delta)
e limited to the range from minus delta to delta

Worked by hand

Threshold δ=1\delta = 1. Compute the loss and gradient for a small error e=0.5e = 0.5 and an outlier e=3e = 3.

L1(0.5)=12×0.25=0.125,gradient=0.5L_1(0.5) = \tfrac{1}{2} \times 0.25 = 0.125, \qquad \text{gradient} = 0.5
L1(3)=1×(3−0.5)=2.5,gradient=1L_1(3) = 1 \times (3 - 0.5) = 2.5, \qquad \text{gradient} = 1
half squared error at e=3:12×9=4.5,gradient=3\text{half squared error at } e = 3: \quad \tfrac{1}{2} \times 9 = 4.5, \qquad \text{gradient} = 3

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 3
Read 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

  1. How would you choose δ\delta 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.

  2. 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 δ\delta changes.

  3. 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.

  4. Your targets were in metres and are now in millimetres, with δ\delta 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.