TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Regression Losses: MSE, MAE and Huber

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 r=y^−yr = \hat{y} - y, 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 nn examples with predictions y^i\hat{y}_i:

MSE=1n∑i=1n(y^i−yi)2MAE=1n∑i=1n∣y^i−yi∣Huberδ=1n∑i=1nhδ(y^i−yi),hδ(r)={12r2∣r∣≤δδ(∣r∣−12δ)∣r∣>δ\begin{aligned} \text{MSE} &= \frac{1}{n} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2 \\ \text{MAE} &= \frac{1}{n} \sum_{i=1}^{n} \lvert \hat{y}_i - y_i \rvert \\ \text{Huber}_\delta &= \frac{1}{n} \sum_{i=1}^{n} h_\delta(\hat{y}_i - y_i), \qquad h_\delta(r) = \begin{cases} \frac{1}{2} r^2 & \lvert r \rvert \le \delta \\ \delta \left( \lvert r \rvert - \frac{1}{2}\delta \right) & \lvert r \rvert > \delta \end{cases} \end{aligned}

What matters for training is the derivative with respect to each prediction:

Loss ∂L/∂y^i\partial L / \partial \hat{y}_i A residual of 10 pulls with
MSE 2nri\frac{2}{n} r_i force 20: grows with the error
MAE 1nsign⁡(ri)\frac{1}{n} \operatorname{sign}(r_i) force 1: every error pulls equally
Huber 1nclip⁡(ri,−δ,δ)\frac{1}{n} \operatorname{clip}(r_i, -\delta, \delta) force δ\delta: quadratic near 0, capped beyond δ\delta

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 ∣r∣=δ\lvert r \rvert = \delta, so the loss is smooth enough for gradient methods. MAE has a kink at r=0r = 0, where we use the subgradient sign⁡(0)=0\operatorname{sign}(0) = 0.

The minimisers also differ. For a constant prediction cc, 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 L(y^+hei)−L(y^−hei)2h\frac{L(\hat{y} + h e_i) - L(\hat{y} - h e_i)}{2h}; it is the cheapest way to catch a wrong formula before it silently ruins training (Gradient Checking explains the method).

python · try it yourself
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 −3-3 from MSE, twelve times that of the residual of 0.5, but only −0.25-0.25 from MAE (the same as every other error) and −0.25-0.25 from Huber with δ=1\delta = 1, where it is capped. MSE's loss value (9.125) is dominated by that one example: 62/4=96^2 / 4 = 9 of it.

One outlier, three lines

Fit y^=wx+b\hat{y} = wx + b by gradient descent under each loss. The data is 50 points around y=2x+1y = 2x + 1, 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.

python · try it yourself
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 σ\sigma and applies δ=1.35σ\delta = 1.35\sigma (its epsilon), while we fixed δ=1\delta = 1.

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 δ\delta
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 δ\delta on the scale of a "normal" residual: errors smaller than δ\delta are treated as noise, larger ones as suspicious. With standardised targets, δ=1\delta = 1 is a common start. In PyTorch the three are nn.MSELoss, nn.L1Loss and nn.HuberLoss(delta=...) (nn.SmoothL1Loss is Huber divided by δ\delta).

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. δ=1\delta = 1 on prices in dollars means every residual is "large", and Huber behaves exactly like MAE. Scale the target or choose δ\delta in its units.
  • Sum versus mean. reduction="sum" multiplies the gradient by nn, so the learning rate that worked with the mean is now nn 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

  1. Predictions y^=(1,1,1)\hat{y} = (1, 1, 1), targets y=(0,1,5)y = (0, 1, 5). Compute MSE, MAE and Huber with δ=1\delta = 1.
Answer

Residuals r=(1,0,−4)r = (1, 0, -4). MSE =(1+0+16)/3=17/3≈5.667= (1 + 0 + 16)/3 = 17/3 \approx 5.667. MAE =(1+0+4)/3≈1.667= (1 + 0 + 4)/3 \approx 1.667. Huber: h(1)=0.5h(1) = 0.5 (at the boundary both pieces give 0.5), h(0)=0h(0) = 0, h(−4)=1⋅(4−0.5)=3.5h(-4) = 1 \cdot (4 - 0.5) = 3.5, so the mean is 4/3≈1.3334/3 \approx 1.333.

  1. For a constant prediction cc, show that MSE is minimised by the mean of the targets.
Answer

ddc1n∑(c−yi)2=2n∑(c−yi)=0\frac{d}{dc} \frac{1}{n} \sum (c - y_i)^2 = \frac{2}{n} \sum (c - y_i) = 0 gives c=1n∑yic = \frac{1}{n} \sum y_i. The second derivative is 2, so it is a minimum. For MAE the derivative is 1n∑sign⁡(c−yi)\frac{1}{n} \sum \operatorname{sign}(c - y_i), zero when as many targets lie above cc as below: the median.

  1. Change y[:5] += 40 to y[:5] += 400 in 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 δ\delta), 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?

  1. MSE
  2. MAE
  3. Huber with a large δ\delta
  4. None of them

For a constant prediction, which statistic of the targets minimises the MAE?

  1. the mean
  2. the median
  3. the mode
  4. the midrange

In the example, five corrupted labels moved the MSE slope from about 2 to 1.246. Why did Huber stay near 2?

  1. Huber ignores the five points completely
  2. Huber's gradient for a residual larger than δ\delta is capped at δ\delta, so the outliers cannot pull harder than that
  3. Huber uses a smaller learning rate
  4. Huber removes outliers before training

With Huber loss and δ=1\delta = 1 on targets measured in dollars (typical errors of hundreds), the loss behaves almost like…

  1. MSE
  2. MAE (scaled by δ\delta)
  3. cross-entropy
  4. zero loss