Regression Losses: MSE, MAE and Huber
A loss function turns "how wrong is this prediction?" into one number the optimizer can push down. For regression the error of one example is the residual , and the three standard losses differ only in how they punish a residual as it grows. That choice decides what your model predicts (a mean or a median), how much a single bad label can drag it around, and what the gradient looks like during training. The training loop needs both the loss and its gradient, so this lesson gives both, checks every gradient numerically, and then fits the same line under each loss.
Three ways to punish a residual
For examples with predictions :
What matters for training is the derivative with respect to each prediction:
| Loss | A residual of 10 pulls with | |
|---|---|---|
| MSE | force 20: grows with the error | |
| MAE | force 1: every error pulls equally | |
| Huber | force : quadratic near 0, capped beyond |
So MSE listens hardest to the worst examples, MAE treats all errors alike, and Huber is MSE for small residuals and MAE for large ones. Its two pieces meet with the same value and the same slope at , so the loss is smooth enough for gradient methods. MAE has a kink at , where we use the subgradient .
The minimisers also differ. For a constant prediction , MSE is minimised by the mean of the targets and MAE by the median. Huber lands in between, which is why it is called a robust loss. The Loss Functions lesson of Mathematics for Deep Learning derives these from likelihoods: MSE is the negative log-likelihood of Gaussian noise, MAE of Laplace noise, which has heavier tails.
From scratch, with a gradient check
Each loss is a pair of functions: the value and its gradient with respect to the predictions. A numerical gradient check compares the analytic gradient with the central difference ; it is the cheapest way to catch a wrong formula before it silently ruins training (Gradient Checking explains the method).
import numpy as np
def mse(y, yhat):
return np.mean((yhat - y) ** 2)
def mse_grad(y, yhat): # d loss / d yhat
return 2 * (yhat - y) / len(y)
def mae(y, yhat):
return np.mean(np.abs(yhat - y))
def mae_grad(y, yhat):
return np.sign(yhat - y) / len(y)
def huber(y, yhat, delta=1.0):
r = yhat - y
quad = 0.5 * r ** 2
lin = delta * (np.abs(r) - 0.5 * delta)
return np.mean(np.where(np.abs(r) <= delta, quad, lin))
def huber_grad(y, yhat, delta=1.0):
r = yhat - y
return np.clip(r, -delta, delta) / len(y)
def numeric_grad(loss, y, yhat, h=1e-6):
g = np.zeros_like(yhat)
for i in range(len(yhat)):
e = np.zeros_like(yhat); e[i] = h
g[i] = (loss(y, yhat + e) - loss(y, yhat - e)) / (2 * h)
return g
y = np.array([3.0, -0.5, 2.0, 7.0])
yhat = np.array([2.5, 0.0, 2.0, 1.0]) # the last prediction is off by 6
for name, f, g in [("MSE", mse, mse_grad), ("MAE", mae, mae_grad), ("Huber", huber, huber_grad)]:
print(f"{name:5s} loss {f(y, yhat):.4f} gradient {np.round(g(y, yhat), 4)}"
f" matches numeric: {np.allclose(g(y, yhat), numeric_grad(f, y, yhat), atol=1e-6)}")MSE loss 9.1250 gradient [-0.25 0.25 0. -3. ] matches numeric: True
MAE loss 1.7500 gradient [-0.25 0.25 0. -0.25] matches numeric: True
Huber loss 1.4375 gradient [-0.125 0.125 0. -0.25 ] matches numeric: True
Read the last column of the gradients: the prediction that is 6 too low gets a gradient of from MSE, twelve times that of the residual of 0.5, but only from MAE (the same as every other error) and from Huber with , where it is capped. MSE's loss value (9.125) is dominated by that one example: of it.
One outlier, three lines
Fit by gradient descent under each loss. The data is 50 points around , and five labels have been corrupted by adding 40 (think of a unit error in the logs). The only thing that changes between the three fits is the function that turns residuals into gradients.
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 50)
y = 2 * x + 1 + rng.normal(0, 1, 50) # true line: slope 2, intercept 1
y[:5] += 40 # five corrupted labels
def grad_of(kind, r, delta=1.0): # d loss / d residual, averaged later
if kind == "MSE": return 2 * r
if kind == "MAE": return np.sign(r)
if kind == "Huber": return np.clip(r, -delta, delta)
def fit_line(kind, steps=20000, lr=0.01):
w, b = 0.0, 0.0
for t in range(steps):
r = (w * x + b) - y # residuals
g = grad_of(kind, r)
w -= lr * np.mean(g * x) # chain rule: d r / d w = x
b -= lr * np.mean(g) # d r / d b = 1
return w, b
for kind in ["MSE", "MAE", "Huber"]:
w, b = fit_line(kind)
print(f"{kind:5s} slope {w:.3f} intercept {b:.3f}")
from sklearn.linear_model import LinearRegression, HuberRegressor
X = x.reshape(-1, 1)
ols = LinearRegression().fit(X, y)
hub = HuberRegressor(epsilon=1.35, alpha=0.0).fit(X, y)
print(f"sklearn LinearRegression slope {ols.coef_[0]:.3f} intercept {ols.intercept_:.3f}")
print(f"sklearn HuberRegressor slope {hub.coef_[0]:.3f} intercept {hub.intercept_:.3f}")MSE slope 1.246 intercept 9.008
MAE slope 2.040 intercept 1.041
Huber slope 2.033 intercept 1.030
sklearn LinearRegression slope 1.246 intercept 9.008
sklearn HuberRegressor slope 2.033 intercept 1.053
Five bad labels out of 50 bend the MSE line badly: slope 1.246 and intercept 9.008 instead of about 2 and 1. MAE and Huber both recover the true line (slopes 2.040 and 2.033). Our gradient-descent MSE fit equals scikit-learn's closed-form LinearRegression to three decimals, a useful check that the loop is right. HuberRegressor gives almost the same slope as our Huber fit. Its intercept differs slightly because it also estimates the noise scale and applies (its epsilon), while we fixed .
MAE needed many steps here: its gradient never shrinks near the minimum, so with a constant learning rate the parameters keep jumping by a fixed amount. This is the usual trade-off: MAE is robust but optimises slowly and needs a decaying learning rate; Huber is robust and smooth.
Which loss to use
| Situation | Loss | Why |
|---|---|---|
| Errors roughly Gaussian, large errors really are worse | MSE | the mean is what you want; smooth, fast to optimise |
| Labels with outliers or heavy tails, or the business cares about the median | MAE | an outlier pulls no harder than any other point |
| Mostly clean data with occasional gross errors (sensor glitches, typos) | Huber | MSE's smoothness near 0, MAE's robustness beyond |
| You need a different quantile (e.g. the 90th percentile of delivery time) | pinball (quantile) loss | MAE is the special case for the median |
Choose on the scale of a "normal" residual: errors smaller than are treated as noise, larger ones as suspicious. With standardised targets, is a common start. In PyTorch the three are nn.MSELoss, nn.L1Loss and nn.HuberLoss(delta=...) (nn.SmoothL1Loss is Huber divided by ).
The loss you train with does not have to be the metric you report. You may train with Huber for robustness and still report RMSE and MAE on the test set (Regression Metrics).
Pitfalls
- Robust loss as a cover-up. Huber stops five bad labels from bending the line, but the labels are still wrong. Find and fix them when you can (data cleaning).
- Unscaled targets with Huber. on prices in dollars means every residual is "large", and Huber behaves exactly like MAE. Scale the target or choose in its units.
- Sum versus mean.
reduction="sum"multiplies the gradient by , so the learning rate that worked with the mean is now times too large. - Comparing loss values across losses. An MSE of 9 and an MAE of 1.75 are in different units (squared versus plain); compare models with one metric.
Practice
- Predictions , targets . Compute MSE, MAE and Huber with .
Answer
Residuals . MSE . MAE . Huber: (at the boundary both pieces give 0.5), , , so the mean is .
- For a constant prediction , show that MSE is minimised by the mean of the targets.
Answer
gives . The second derivative is 2, so it is a minimum. For MAE the derivative is , zero when as many targets lie above as below: the median.
- Change
y[:5] += 40toy[:5] += 400in the outlier example. Which of the three slopes do you expect to change a lot, and why?
Answer
Only MSE's. Its gradient grows with the residual, so ten times larger outliers pull ten times harder. MAE's and Huber's gradients for those five points are already capped (at 1 and at ), so a larger corruption does not change their pull and the fitted lines stay near slope 2.
Test yourself
Which loss gives every non-zero residual a gradient of the same size, whatever its magnitude?
- MSE
- MAE
- Huber with a large
- None of them
For a constant prediction, which statistic of the targets minimises the MAE?
- the mean
- the median
- the mode
- the midrange
In the example, five corrupted labels moved the MSE slope from about 2 to 1.246. Why did Huber stay near 2?
- Huber ignores the five points completely
- Huber's gradient for a residual larger than is capped at , so the outliers cannot pull harder than that
- Huber uses a smaller learning rate
- Huber removes outliers before training
With Huber loss and on targets measured in dollars (typical errors of hundreds), the loss behaves almost like…
- MSE
- MAE (scaled by )
- cross-entropy
- zero loss