TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Regression Metrics: MAE, MSE, RMSE and R-squared

Regression Metrics: MAE, MSE, RMSE and R-squared

A model predicts delivery times, house prices or energy use. Before you can say whether it is good, you need one number that summarises how far its predictions are from the truth, and you need to know what that number hides. The four standard regression metrics answer slightly different questions: "how far off am I on a typical day" (MAE), "how bad are my worst misses" (MSE, RMSE), and "how much better am I than just guessing the average" (R2R^2). Picking the wrong one can make a useless model look fine.

Residuals first

Every regression metric is built from the residuals ei=yi−y^ie_i = y_i - \hat{y}_i, the true value minus the prediction, for the nn examples of an evaluation set. Look at them before you summarise them: a histogram of residuals shows bias (centred away from 0), heavy tails (a few huge misses) and slices where the model fails, which a single number cannot.

The four metrics

MAE=1n∑i=1n∣yi−y^i∣MSE=1n∑i=1n(yi−y^i)2RMSE=MSER2=1−∑i(yi−y^i)2∑i(yi−yˉ)2\begin{aligned} \text{MAE} &= \frac{1}{n} \sum_{i=1}^{n} \lvert y_i - \hat{y}_i \rvert \\ \text{MSE} &= \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 \\ \text{RMSE} &= \sqrt{\text{MSE}} \\ R^2 &= 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2} \end{aligned}
Metric Unit Range Reads as
MAE same as yy [0,∞)[0, \infty) the typical size of an error; every unit of error counts the same
MSE yy squared [0,∞)[0, \infty) the average squared error; what least squares minimises, convenient for maths, hard to read
RMSE same as yy [0,∞)[0, \infty) like MAE but large errors weigh more; always RMSE≥MAE\text{RMSE} \ge \text{MAE}
R2R^2 none (−∞,1](-\infty, 1] the share of the variance of yy the model explains; 0 = as good as predicting the mean yˉ\bar{y}, below 0 = worse than that

The denominator of R2R^2 is the squared error of the constant model that always predicts the mean of the evaluation targets. So R2R^2 is a comparison with a baseline, and it is unitless: it lets you compare across problems, while MAE and RMSE tell a stakeholder "we are off by about 4 minutes". Report one of each kind.

From scratch, checked against scikit-learn

Ten delivery times in minutes and a model's predictions:

python · try it yourself
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

y_true = np.array([22, 35, 18, 41, 27, 30, 25, 38, 20, 33], dtype=float)
y_pred = np.array([25, 31, 20, 36, 29, 30, 22, 41, 24, 30], dtype=float)

def mae(y, p):  return np.mean(np.abs(y - p))
def mse(y, p):  return np.mean((y - p) ** 2)
def rmse(y, p): return np.sqrt(mse(y, p))
def r2(y, p):   return 1 - np.sum((y - p) ** 2) / np.sum((y - y.mean()) ** 2)

print("residuals:", (y_true - y_pred).astype(int).tolist())
print(f"MAE  ours {mae(y_true, y_pred):.3f}  sklearn {mean_absolute_error(y_true, y_pred):.3f}")
print(f"MSE  ours {mse(y_true, y_pred):.3f}  sklearn {mean_squared_error(y_true, y_pred):.3f}")
print(f"RMSE ours {rmse(y_true, y_pred):.3f}  sklearn {np.sqrt(mean_squared_error(y_true, y_pred)):.3f}")
print(f"R2   ours {r2(y_true, y_pred):.3f}  sklearn {r2_score(y_true, y_pred):.3f}")
print(f"baseline (always predict the mean {y_true.mean():.1f}): MAE {mae(y_true, np.full(10, y_true.mean())):.3f}")
residuals: [-3, 4, -2, 5, -2, 0, 3, -3, -4, 3]
MAE  ours 2.900  sklearn 2.900
MSE  ours 10.100  sklearn 10.100
RMSE ours 3.178  sklearn 3.178
R2   ours 0.816  sklearn 0.816
baseline (always predict the mean 28.9): MAE 6.500

The model is off by 2.9 minutes on a typical order (MAE), RMSE is a little larger (3.18) because the biggest misses (5 and 4 minutes) count more, and R2=0.816R^2 = 0.816: the model removes about 82 % of the squared error of always predicting the mean of 28.9 minutes, whose MAE would be 6.5. The from-scratch functions and sklearn.metrics agree to the last digit.

Outliers: MAE and RMSE disagree

Squaring makes one big miss count like many small ones. Below, model A is off by 2 minutes on every order; model B is perfect on nine orders and off by 20 on one. Their MAE is the same; RMSE says B is more than three times as bad.

python · try it yourself
import numpy as np

y = np.array([30.0] * 10)
pred_a = y + np.array([2, -2, 2, -2, 2, -2, 2, -2, 2, -2])   # small errors everywhere
pred_b = y.copy(); pred_b[3] += 20                             # one large miss

for name, p in [("A (2 min everywhere)", pred_a), ("B (one 20-min miss)", pred_b)]:
    e = y - p
    print(f"{name:21s} MAE {np.mean(np.abs(e)):.2f}  RMSE {np.sqrt(np.mean(e ** 2)):.2f}")

# units: the same predictions in seconds
print("in seconds: MAE", np.mean(np.abs(y * 60 - pred_b * 60)), " RMSE", round(float(np.sqrt(np.mean((y * 60 - pred_b * 60) ** 2))), 2))
A (2 min everywhere)  MAE 2.00  RMSE 2.00
B (one 20-min miss)   MAE 2.00  RMSE 6.32
in seconds: MAE 120.0  RMSE 379.47

Which is right depends on the business. If a 20-minute delay loses the customer and a 2-minute one is never noticed, RMSE matches the cost better. If every minute costs the same, MAE does. MAE is also the loss minimised by the median, RMSE by the mean, which is why MAE is called robust (see Regression Losses). Both scale with the unit: switching to seconds multiplies them by 60, while R2R^2 would not change.

Negative R-squared

R2R^2 is not a square of anything that must be positive. On new data a bad model can do worse than the mean, and then R2<0R^2 < 0. Here polynomials of degree 1, 3 and 5 are fitted to 15 noisy points from the diabetes data and evaluated on held-out patients:

python · try it yourself
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_absolute_error

X, y = load_diabetes(return_X_y=True)
X = X[:, [2]]                                   # one feature: body-mass index
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
small = np.arange(15)                           # train on only 15 patients
for deg in [1, 3, 5]:
    m = make_pipeline(PolynomialFeatures(deg), StandardScaler(), LinearRegression())
    m.fit(X_tr[small], y_tr[small])
    print(f"degree {deg:2d}  train R2 {r2_score(y_tr[small], m.predict(X_tr[small])):6.3f}"
          f"  test R2 {r2_score(y_te, m.predict(X_te)):7.3f}  test MAE {mean_absolute_error(y_te, m.predict(X_te)):6.1f}")
print("test set:", len(y_te), "patients; predicting the training mean gives test R2",
      round(r2_score(y_te, np.full(len(y_te), y_tr[small].mean())), 3))
degree  1  train R2  0.428  test R2   0.042  test MAE   56.9
degree  3  train R2  0.431  test R2   0.032  test MAE   56.6
degree  5  train R2  0.587  test R2 -36.895  test MAE  125.1
test set: 133 patients; predicting the training mean gives test R2 -0.025

Trained on only 15 patients, the straight line barely beats the mean on the 133 test patients (R2=0.042R^2 = 0.042). The degree-5 polynomial fits its training points better (R2=0.587R^2 = 0.587) and is a disaster on new data: test R2=−36.9R^2 = -36.9, because the curve shoots off between and beyond the training points and its squared errors dwarf those of a flat line. Note the last line too: even the constant prediction scores slightly below 0 (−0.025-0.025), because it uses the training mean, not the test mean. A test R2R^2 near 0 means "no better than a constant", and a negative one is a loud alarm for overfitting or a broken pipeline (Underfitting and Overfitting).

Pitfalls

  • Comparing MSE across data sets. MSE depends on the unit and the spread of yy; compare models on the same evaluation set only, or use R2R^2.
  • Reading a high R2R^2 as "accurate". If yy varies a lot, R2=0.9R^2 = 0.9 can still mean errors that are too large for the job. Always report an error in the units of yy next to it.
  • Training R2R^2. It only grows with model complexity. Report it on a validation or test set.
  • Errors that scale with yy. Being off by 10 on a value of 20 is worse than on a value of 2000. Then use a relative error (MAPE, 1n∑∣ei∣/∣yi∣\frac{1}{n}\sum \lvert e_i \rvert / \lvert y_i \rvert, undefined at yi=0y_i = 0) or model log⁡y\log y and report errors on that scale.

Practice

  1. Residuals are 3,−1,0,−23, -1, 0, -2. Compute MAE, MSE and RMSE.
Answer

MAE =(3+1+0+2)/4=1.5= (3 + 1 + 0 + 2)/4 = 1.5, MSE =(9+1+0+4)/4=3.5= (9 + 1 + 0 + 4)/4 = 3.5, RMSE =3.5≈1.87= \sqrt{3.5} \approx 1.87.

  1. A model always predicts the mean of the test targets. What is its R2R^2 on that test set, and what would it be if it predicted the training mean instead?
Answer

Exactly 0, because its squared error equals the denominator of R2R^2. Predicting the training mean gives a slightly negative value whenever the training mean differs from the test mean, because the test mean is the constant with the smallest squared error on the test set.

  1. Why is RMSE never smaller than MAE?
Answer

RMSE is the quadratic mean of the absolute errors and MAE their arithmetic mean; the quadratic mean is always at least the arithmetic mean (equivalently, MSE−MAE2\text{MSE} - \text{MAE}^2 is the variance of ∣ei∣\lvert e_i \rvert, which is not negative). They are equal only when every absolute error is the same.

Test yourself

Which metric is in the same unit as the target and treats every unit of error equally?

  1. MSE
  2. MAE
  3. R2R^2
  4. RMSE

A model has R2=−0.4R^2 = -0.4 on the test set. What does that mean?

  1. It explains 40 % of the variance
  2. Its squared error is larger than that of always predicting the test mean
  3. The metric was computed wrongly; R2R^2 cannot be negative
  4. It is overfitting the test set

Two models have the same MAE, but model B has a much larger RMSE. What is the most likely reason?

  1. B has a few very large errors
  2. B is biased upwards
  3. B was evaluated in a different unit
  4. B has smaller errors on average

You convert the target from minutes to seconds. Which metric does not change?

  1. MAE
  2. RMSE
  3. MSE
  4. R2R^2