AI Logic

Loss Functions

Huber Loss

Updated:

Graph of the Huber loss. The horizontal axis is the error (prediction − target) and the vertical axis is the loss of one example, overlaying the Huber loss with δ = 1 (solid), half the squared error ½e² (dashed), and the absolute error |e| (dotted). It switches from quadratic to linear at e = ±1, and at e = 3 the Huber loss is 2.5 versus 4.5 for ½e². Legend on the right

Background and Overview

The Huber loss is a loss function that behaves like the squared error where the error is small and like the absolute error where it is large. It is used in regression, where a model predicts values, as a loss that keeps training stable even when the data contain outliers.

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

Here e=y^−ye = \hat{y} - y is the difference between the prediction and the target (the error), and δ>0\delta > 0 is the threshold at which the loss switches from the squared error to the absolute error.

Mean squared error (MSE) squares the error, so a single example that is far off can dominate both the loss and the gradient. The absolute error ∣e∣|e|, on the other hand, is robust to outliers, but it has a kink at zero error and its gradient keeps the same magnitude even near the target, which makes fine adjustment difficult. The Huber loss combines, in a single formula, the smoothness of the squared error near the target and the robustness of the absolute error far from it.

The statistician P. J. Huber proposed this loss in a 1964 paper as a way to estimate a location (a central value such as the mean) from data in which a normal distribution is contaminated by a small fraction of another distribution (outliers). That data model, "a normal distribution with part of it replaced by another distribution," and its estimators are still studied in robust statistics, the field of statistical methods that resist outliers (Donoho and Montanari, 2015).

The figure at the top plots the Huber loss with δ=1\delta = 1 (solid) alongside half the squared error 12e2\frac{1}{2}e^2 (dashed) and the absolute error ∣e∣|e| (dotted). For ∣e∣≤1|e| \le 1 it coincides with the dashed curve, and for ∣e∣>1|e| > 1 it becomes a straight line parallel to the dotted one. At an error of 3, 12e2=4.5\frac{1}{2}e^2 = 4.5, while the Huber loss stays at 2.52.5.

Definition and Computation

The Huber loss is computed as follows. As an example, take the same data as in the MSE article: predictions y^=(2.5, 0.0, 2.0, 8.0)\hat{y} = (2.5,\ 0.0,\ 2.0,\ 8.0) and targets y=(3.0, −0.5, 2.0, −2.0)y = (3.0,\ -0.5,\ 2.0,\ -2.0) for four examples. The fourth target is a recording error and is far off. Let δ=1\delta = 1.

  1. Compute the error ei=y^i−yie_i = \hat{y}_i - y_i for each example. Here e=(−0.5, 0.5, 0, 10)e = (-0.5,\ 0.5,\ 0,\ 10).
  2. Compare the magnitude ∣ei∣|e_i| with δ\delta: if it is at most δ\delta, compute 12ei2\frac{1}{2}e_i^2; if it exceeds δ\delta, compute δ(∣ei∣−12δ)\delta(|e_i| - \frac{1}{2}\delta). Here this gives (0.125, 0.125, 0, 9.5)(0.125,\ 0.125,\ 0,\ 9.5).
  3. Average by dividing by the number of examples. Here (0.125+0.125+0+9.5)/4=2.4375(0.125 + 0.125 + 0 + 9.5) / 4 = 2.4375.

On the same example, MSE is 25.12525.125 and the mean absolute error is 2.752.75. Because the outlier's influence is not inflated by squaring, the Huber loss is much smaller than MSE.

The two pieces join at ∣e∣=δ|e| = \delta. Both have the value 12δ2\frac{1}{2}\delta^2 and the slope δ\delta there, so the loss curve has no kink and the gradient changes continuously.

The linear piece is written as δ(∣e∣−12δ)\delta(|e| - \frac{1}{2}\delta), shifted down by 12δ\frac{1}{2}\delta, so that its value matches the quadratic piece at ∣e∣=δ|e| = \delta. With plain δ∣e∣\delta |e|, the loss would jump by 12δ2\frac{1}{2}\delta^2 at the switching point.

Why It Is Robust to Outliers

The reason is that the magnitude of the gradient a single example contributes to the loss is bounded. Differentiating the Huber loss with respect to the error ee gives the following.

∂Lδ∂e={e(∣e∣≤δ)δ⋅sign⁡(e)(∣e∣>δ)\frac{\partial L_\delta}{\partial e} = \begin{cases} e & (|e| \le \delta) \\ \delta \cdot \operatorname{sign}(e) & (|e| > \delta) \end{cases}

The gradient is proportional to the error while the error is small, and saturates at ±δ\pm\delta once it exceeds δ\delta. It helps to think of the gradient as simply the error clipped to the range [−δ, δ][-\delta,\ \delta].

Comparing the gradients with respect to the predictions y^i\hat{y}_i in the example above (a factor of 1/41/4 appears because of the averaging) makes the difference clear.

ExampleError eeMSE gradient 2e/42e/4Huber loss (δ=1\delta = 1) gradient
1st−0.5-0.5−0.25-0.25−0.125-0.125
2nd0.50.50.250.250.1250.125
3rd000000
4th (outlier)1010550.250.25

With MSE, the outlier's gradient is 20 times that of the other examples, and the parameter update is spent almost entirely on fixing the outlier. With the Huber loss it is only twice as large, so learning from the other examples is not drowned out.

As an analogy, picture a teacher trying to even out a class's average score who, even when one student has an extreme score, only listens to that student's case "up to a strength of δ\delta at most."

Because of this property, predictions optimized with the Huber loss sit between the mean of the targets (the optimal prediction under MSE) and their median (the optimal prediction under the absolute error). A larger δ\delta moves it toward the mean, and a smaller δ\delta toward the median.

Where It Is Used

The Huber loss (and its variants) is used in regression where outliers or label errors are likely.

  • Location regression in object detection: Fast R-CNN used the Smooth L1 loss, which has the same formula as the Huber loss with δ=1\delta = 1, to regress the position of the box enclosing an object (the bounding box). The paper explains that it is less sensitive to outliers than the squared error used by R-CNN and others, and that it prevents the exploding gradients that the squared error tends to cause when the targets are unbounded, without careful tuning of the learning rate.
  • Regression with outliers: It replaces MSE on data such as sensor readings or prices, where values that are far off occasionally appear.
  • Regression where the gradient magnitude should be limited: Since the gradient magnitude never exceeds δ\delta, it keeps large errors early in training from making updates erratic.

Caveats in Practice

Choose δ\delta to match the scale (units) of the targets. Since δ\delta is the boundary for "what counts as an outlier," using the same δ\delta for targets in 0–1 and targets in 0–1000 makes the former almost MSE and the latter almost the absolute error. It is easier to standardize the targets (mean 0, variance 1) first, start around δ=1\delta = 1, and adjust while looking at the distribution of errors.

Keep the following points in mind as well.

  • PyTorch has both nn.HuberLoss and nn.SmoothL1Loss: HuberLoss(delta=δ) follows the formula above, and the slope of its linear piece is δ\delta. SmoothL1Loss(beta=β) is the Huber loss divided by β\beta, and the slope of its linear piece is always 1. The two give the same value only when δ=β=1\delta = \beta = 1; otherwise the loss and gradient magnitudes differ by a factor of δ\delta, which also changes how the learning rate behaves.
  • The second derivative is not continuous: The gradient is continuous, but at ∣e∣=δ|e| = \delta the second derivative (the curvature) jumps from 1 to 0. This is not a problem for ordinary gradient methods, but when a loss that is smooth up to the second derivative is needed, an approximation of the form δ2(1+(e/δ)2−1)\delta^2\left(\sqrt{1 + (e/\delta)^2} - 1\right) (the Pseudo-Huber loss) is used.
  • Large errors shrink more slowly than with MSE: Even examples with large errors that are not outliers have their gradient capped at ±δ\pm\delta, so they are not pulled back as strongly as with the squared error. On data with almost no outliers, MSE can converge faster.
  • The default reduction="mean" divides by the total number of elements: As with nn.MSELoss, it averages over the total number of elements in the tensor, not over the batch size.

Comparison with Other Loss Functions

The table lines up the Huber loss with loss functions commonly used in regression from the same viewpoints.

Loss functionLoss of one exampleGradient magnitudeRobustness to outliersOptimal prediction
MSEe2e^2Proportional to the error (unbounded)WeakMean of the targets
Mean absolute error (MAE)∣e∣\lvert e \rvertAlways 1 (discontinuous at zero error)StrongMedian of the targets
Huber loss12e2\frac{1}{2}e^2 for ∣e∣≤δ\lvert e \rvert \le \delta, otherwise δ(∣e∣−12δ)\delta(\lvert e \rvert - \frac{1}{2}\delta)Proportional to the error up to δ\delta, then δ\deltaModerate (tuned by δ\delta)Between the mean and the median
Smooth L1 lossHuber loss / β/\ \betae/βe/\beta up to β\beta, then 1Moderate (tuned by β\beta)Same as the Huber loss

Rough guidelines for choosing are as follows.

  • If there are almost no outliers, use MSE: It is the most standard choice and has theoretical support under the assumption of normally distributed noise.
  • If outliers are mixed in and MSE makes training unstable, switch to the Huber loss: It keeps the smoothness near the target while limiting the influence of outliers through δ\delta.
  • If outliers are very common and the goal is to predict the median, use the mean absolute error: However, its gradient does not shrink near zero error, so measures such as lowering the learning rate are needed.
  • To match an existing detector implementation, use the Smooth L1 loss: With β=1\beta = 1 it is the same as the Huber loss (δ=1\delta = 1).

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Example from the text: the 4th target is an outlier (error 10)
y_pred = torch.tensor([2.5, 0.0, 2.0, 8.0], requires_grad=True)
y_true = torch.tensor([3.0, -0.5, 2.0, -2.0])

criterion = nn.HuberLoss(delta=1.0)   # reduction="mean": divides by the total number of elements
loss = criterion(y_pred, y_true)
print(loss.item())                    # 2.4375

loss.backward()
print(y_pred.grad)                    # (−0.125, 0.125, 0.0, 0.25): the outlier's gradient is capped at δ/4

# Computation following the definition
def huber(pred, target, delta=1.0):
    e = pred - target
    quad = 0.5 * e ** 2                          # part where |e| <= δ
    lin = delta * (e.abs() - 0.5 * delta)        # part where |e| > δ
    return torch.where(e.abs() <= delta, quad, lin).mean()

print(huber(y_pred.detach(), y_true).item())     # 2.4375

# Comparison: MSE and mean absolute error
print(nn.MSELoss()(y_pred.detach(), y_true).item())   # 25.125
print(nn.L1Loss()(y_pred.detach(), y_true).item())    # 2.75

# SmoothL1Loss is HuberLoss divided by beta (same value when delta = beta = 1)
beta = 2.0
print(nn.SmoothL1Loss(beta=beta)(y_pred.detach(), y_true).item())
print(nn.HuberLoss(delta=beta)(y_pred.detach(), y_true).item() / beta)   # same value as above

FAQ

Q. What value should δ be?
A.

There is no fixed value. Since δ is the boundary for "what counts as an outlier," choose it to match the scale of the targets. A good rule of thumb is to standardize the targets, start around δ = 1, and adjust it while watching the error distribution during training so that the errors of ordinary examples mostly fall within δ.

Q. Are the Huber loss and the Smooth L1 loss the same thing?
A.

They give the same value when δ = β = 1. In general, the Smooth L1 loss is the Huber loss divided by β; the slope of the linear piece is δ for the Huber loss and always 1 for the Smooth L1 loss. In PyTorch they are nn.HuberLoss and nn.SmoothL1Loss, respectively.

Q. If the outliers are removed, isn't MSE enough?
A.

If outliers can be clearly identified and removed, MSE may be enough. But drawing the line for what counts as an outlier is hard, and checking large amounts of data by hand is laborious. The advantage of the Huber loss is that it keeps all the data and only limits the influence of outliers to δ.

References

  1. P. J. Huber, "Robust Estimation of a Location Parameter," The Annals of Mathematical Statistics, 35(1), pp. 73–101, 1964.
  2. R. Girshick, "Fast R-CNN," ICCV, 2015.
  3. PyTorch Documentation, "torch.nn.HuberLoss."
  4. PyTorch Documentation, "torch.nn.SmoothL1Loss."
  5. D. L. Donoho and A. Montanari, "Variance Breakdown of Huber (M)-estimators: n/p → m ∈ (1, ∞)," arXiv:1503.02106, 2015.
  6. K. P. Murphy, "Probabilistic Machine Learning: An Introduction," MIT Press, 2022, Section 5.1.5.3 Huber loss, 11.6.3 Huber loss.
  7. J. T. Barron, "A General and Adaptive Robust Loss Function," CVPR, 2019 (a general form that includes the Charbonnier/Pseudo-Huber loss).