Skip to content

8.2. Regression

Regression predicts a number, so the error is also a number — and that is the whole difficulty. In classification an error is a fact: right or wrong. Here every prediction is a little bit wrong, and a metric is a decision about how to add up all that wrongness. Different ways of adding it up reward completely different models, so the metric is not a report at the end; it is a specification at the start.

Everything below is built on the residual:

\[ e_i = y_i - \hat{y}_i \]

and differs only in what it does with the sign, the magnitude and the outliers.

The choice that decides everything: absolute or squared

\[ \text{MAE} = \frac{1}{N}\sum_{i=1}^{N} |e_i| \qquad\qquad \text{MSE} = \frac{1}{N}\sum_{i=1}^{N} e_i^2 \]

They look like two flavours of the same idea. They are not, and the difference has a precise statement: they are minimized by different predictions.

  • Minimizing MSE gives you the mean of the target distribution1.
  • Minimizing MAE gives you the median.

Which is why the choice is not a matter of taste. If you train a delivery-time model on MSE, it predicts the average delivery time, and averages are dragged upward by the rare disaster. Train it on MAE and it predicts the time that half the deliveries beat — usually what the customer was asking about. Same data, same architecture, different question answered.

Below: a set of delivery times with a long right tail. The curves are MSE and MAE as functions of a single constant prediction \(c\); drag \(c\) and watch where each one bottoms out.

Why squaring produces the mean, in one line

Minimize \(\sum (y_i - c)^2\) by setting the derivative to zero: \(-2\sum(y_i - c) = 0 \Rightarrow c = \frac{1}{N}\sum y_i\). The mean, exactly.

Do the same for \(\sum |y_i - c|\): the derivative of \(|y_i - c|\) is \(-1\) for points above \(c\) and \(+1\) for points below, so the total is zero when as many points sit above as below — the median, and it does not matter how far above they are. That indifference to distance is robustness, stated precisely.

RMSE: the units come back

MSE is in squared units — squared minutes, squared reais — which nobody can interpret. Taking the root fixes that:

\[ \text{RMSE} = \sqrt{\frac{1}{N}\sum_{i=1}^{N} e_i^2} \]

RMSE keeps MSE's preference for the mean and its sensitivity to large errors, while reading in the same units as the target. That makes it the default for reporting, and it comes with a free diagnostic:

\[ \text{RMSE} \;\ge\; \text{MAE} \qquad\text{always} \]

with equality only when every error has exactly the same magnitude. So the ratio RMSE/MAE is a measure of how uneven your errors are. Plain Gaussian noise gives \(\sqrt{\pi/2} \approx 1.25\); noticeably above that means a few predictions are much worse than the rest, and you should go and look at those cases individually instead of tuning anything.

What one outlier does

Drag the red point. Nothing else changes: same data, same model family, same code.

or drag it directly on the chart

Two things happen at once when you drag it, and only one of them is the metric's fault.

The metrics move: RMSE grows faster than MAE, and MedAE — the median of the absolute errors — barely notices, because a median does not care how far away the far point is. That is robustness measured rather than asserted.

The model moves too. The orange line is fitted by least squares, so it chases the outlier: its slope falls from 0.961 to 0.423 as you drag the point down. The green line, fitted to minimize absolute error, stays at 0.989 the whole time. The metric you optimize is the model you get — the same lesson as the mean and the median, now visible in the fit itself.

What to do about it

  • Look at the residuals before choosing. One glance at a residual histogram beats any rule.
  • If the tail is real (delivery times, incomes, insurance claims), that is the data, not an error — report MedAE or a quantile, and consider training on MAE or Huber.
  • If the tail is bad data (a sensor stuck at zero, a typo in a price), fix the data. No metric compensates for corrupted labels.
  • Huber loss is the compromise, quadratic near zero and linear beyond \(\delta\):
\[ L_\delta(e) = \begin{cases} \tfrac{1}{2}e^2 & |e| \le \delta \\ \delta\left(|e| - \tfrac{1}{2}\delta\right) & |e| > \delta \end{cases} \]

It is differentiable everywhere (unlike MAE at zero) and bounded in influence (unlike MSE), which is why torch.nn.SmoothL1Loss is the default in object detectors2.

R²: a comparison, not a percentage

\[ R^2 = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2} \]

Look at what is in the denominator: the error of predicting the mean of \(y\) for everyone. So \(R^2\) does not measure quality in the abstract — it measures how much better than the dumbest reasonable baseline you are. That framing settles most of the confusion around it:

  • \(R^2 = 1\) — perfect predictions.
  • \(R^2 = 0\) — you did exactly as well as always guessing the mean. Your model added nothing.
  • \(R^2 < 0\)possible, and common on test data. You did worse than the constant mean. If you have never seen a negative \(R^2\), you have probably only ever computed it on the training set.

Three things \(R^2\) is not

It is not "the percentage of variance explained" in general. That reading is only valid for linear models fitted by least squares on the same data. For a neural network on held-out data it is just the comparison above.

It is not comparable across datasets. \(R^2\) depends on the variance of \(y\) in your sample. A model predicting house prices in one city can score 0.9 and the same model in a more homogeneous city 0.3 — while making the same errors in reais. Compare RMSE across datasets, not \(R^2\).

It never decreases when you add features, however useless they are, which is what adjusted \(R^2\) exists to fix:

\[ R^2_{\text{adj}} = 1 - (1 - R^2)\frac{N - 1}{N - k - 1} \]

with \(k\) predictors. Use it to compare models of different sizes on the same data.

Percentage errors, and how they bite

\[ \text{MAPE} = \frac{100}{N}\sum_{i=1}^{N}\left|\frac{y_i - \hat{y}_i}{y_i}\right| \]

MAPE is popular because "we're off by 8%" travels well in a meeting. It also has three sharp edges, and the first one alone disqualifies it from many problems:

  1. It is undefined at \(y_i = 0\) and enormous near it. Demand forecasting has zeros. Any count-like target has zeros.
  2. It is asymmetric. Predicting 50 when the truth is 100 gives 50%. Predicting 150 when the truth is 100 gives 50% too, but predicting 200 gives 100% — while the smallest possible error for under-prediction is capped at 100%. Optimizing MAPE therefore biases a model to predict low.
  3. It weights small targets enormously. Being off by 1 unit on a true value of 2 costs 50%; the same absolute miss on a true value of 1000 costs 0.1%.
Instead Definition Why it is better
sMAPE \(\dfrac{100}{N}\sum \dfrac{\lvert e_i\rvert}{(\lvert y_i\rvert + \lvert\hat{y}_i\rvert)/2}\) Symmetric-ish and bounded, though still awkward near zero
MASE3 \(\dfrac{\text{MAE of your model}}{\text{MAE of the naive forecast}}\) Scale-free, defined at zero, and reads directly: below 1 you beat the naive baseline
WAPE \(\dfrac{\sum \lvert e_i\rvert}{\sum \lvert y_i \rvert}\) Aggregate percentage error; robust to individual small targets

Always compute the baseline

Every regression report should carry the score of the trivial model next to the model's: predicting the mean, the median, or — for anything with time in it — the last observed value. Beating the last value is genuinely hard in forecasting, and a model that does not is not a model. This is the regression version of the always-predict-the-majority check from the classification page.

Predicting a range instead of a number

Sometimes a single number is the wrong output. Quantile loss (also called pinball loss) trains a model to predict the \(\tau\)-th quantile instead of the mean:

\[ L_\tau(e) = \begin{cases} \tau \, e & e \ge 0 \\ (\tau - 1)\, e & e < 0 \end{cases} \]

Read it as an asymmetric MAE: with \(\tau = 0.9\), under-predicting is penalized nine times more than over-predicting, so the model learns a value it will exceed only 10% of the time. Train three models at \(\tau = 0.1, 0.5, 0.9\) and you have a prediction interval rather than a point — often far more useful to whoever has to act on it. Note that \(\tau = 0.5\) is MAE, up to a factor of two4.

Which metric, and why

Your situation Use Because
Errors roughly symmetric, no wild outliers RMSE Same units, standard, penalizes big misses
The tail is real and you must not chase it MAE or MedAE Both target the middle of the distribution, not its mean
Outliers are corrupted data Fix the data, then RMSE No metric repairs bad labels
Comparing to a "do nothing" baseline , MASE Both are ratios against a trivial predictor
Comparing across datasets with different scales MASE, WAPE, or R² with care RMSE is not comparable across different \(y\) variances
The stakeholder thinks in percentages WAPE or MAPE if no zeros Percentages travel, but check for zeros and the low bias
You need a range, not a point Quantile loss Gives you the interval directly
Training a network on heavy-tailed targets Huber / SmoothL1 Differentiable and bounded influence

In code

import numpy as np
from sklearn.metrics import (mean_absolute_error, root_mean_squared_error,
                             median_absolute_error, r2_score)

mae  = mean_absolute_error(y_test, pred)
rmse = root_mean_squared_error(y_test, pred)          # sklearn >= 1.4
medae = median_absolute_error(y_test, pred)
r2   = r2_score(y_test, pred)

# the baselines — report these next to the model, always
mean_rmse   = root_mean_squared_error(y_test, np.full_like(y_test, y_train.mean()))
median_mae  = mean_absolute_error(y_test, np.full_like(y_test, np.median(y_train)))

print(f"RMSE {rmse:.3f} vs {mean_rmse:.3f} for predicting the mean")
print(f"MAE  {mae:.3f} vs {median_mae:.3f} for predicting the median")
print(f"RMSE/MAE {rmse/mae:.2f}  (≈1.25 for gaussian errors; higher means heavy tails)")
print(f"R² {r2:.3f}   ({'worse than the mean!' if r2 < 0 else 'better than the mean'})")

Key takeaways

  1. The metric is not a report, it is a specification: minimizing MSE asks for the conditional mean, minimizing MAE asks for the median. Decide which one your user wants.
  2. RMSE is the sane default for reporting — same units as the target — and RMSE/MAE tells you for free how uneven the errors are.
  3. MedAE is the robust reading; use it when the tail is genuine and you refuse to chase it.
  4. compares you to predicting the mean. It can be negative, and it is not comparable across datasets.
  5. MAPE is undefined at zero, asymmetric, and biases models to predict low. Prefer MASE or WAPE.
  6. Always report a baseline — mean, median, or last observation. A model that does not beat it is not a model.
  7. If a decision needs a range, train quantiles and hand over the interval.

Additional Resources

  1. Evaluating forecast accuracy — Hyndman, R. J., & Athanasopoulos, G., Forecasting: Principles and Practice (3rd ed.). The clearest treatment of scale-dependent versus scale-free errors, written by the people who proposed MASE. Free online, and the surrounding chapters are the reference on baselines.

  2. Regression metrics — scikit-learn User Guide. Exact definitions5, including the sign conventions of the neg_* scorers that trip everyone up the first time they use cross_val_score.

  3. Root mean square error (RMSE) or mean absolute error (MAE)? — Chai, T., & Draxler, R. R. (2014)6. A short, readable argument in a genuine disagreement between researchers — worth reading against Willmott & Matsuura's opposite case1 to see that the choice really is a modelling decision and not a settled fact.

References

The works cited through the text, in order of appearance:


  1. Willmott, C. J., & Matsuura, K. (2005). Advantages of the mean absolute error (MAE) over the root mean square error (RMSE) in assessing average model performanceClimate Research 30, 79–82. The case for MAE, and the paper that started the argument continued below. 

  2. Huber, P. J. (1964). Robust Estimation of a Location ParameterAnnals of Mathematical Statistics 35(1), 73–101. Where the quadratic-then-linear loss comes from, and the origin of modern robust statistics. 

  3. Hyndman, R. J., & Koehler, A. B. (2006). Another look at measures of forecast accuracyInternational Journal of Forecasting 22(4), 679–688. Catalogues how percentage errors fail, and proposes MASE. 

  4. Koenker, R., & Bassett, G. (1978). Regression QuantilesEconometrica 46(1), 33–50. Quantile regression, and the asymmetric loss that produces it. 

  5. Regression metrics — scikit-learn User Guide. 

  6. Chai, T., & Draxler, R. R. (2014). Root mean square error (RMSE) or mean absolute error (MAE)? – Arguments against avoiding RMSE in the literatureGeoscientific Model Development 7, 1247–1250. The reply to Willmott & Matsuura, arguing RMSE is the right summary when the errors are gaussian.