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" (). Picking the wrong one can make a useless model look fine.
Residuals first
Every regression metric is built from the residuals , the true value minus the prediction, for the 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
| Metric | Unit | Range | Reads as |
|---|---|---|---|
| MAE | same as | the typical size of an error; every unit of error counts the same | |
| MSE | squared | the average squared error; what least squares minimises, convenient for maths, hard to read | |
| RMSE | same as | like MAE but large errors weigh more; always | |
| none | the share of the variance of the model explains; 0 = as good as predicting the mean , below 0 = worse than that |
The denominator of is the squared error of the constant model that always predicts the mean of the evaluation targets. So 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:
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 : 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.
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 would not change.
Negative R-squared
is not a square of anything that must be positive. On new data a bad model can do worse than the mean, and then . Here polynomials of degree 1, 3 and 5 are fitted to 15 noisy points from the diabetes data and evaluated on held-out patients:
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 (). The degree-5 polynomial fits its training points better () and is a disaster on new data: test , 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 (), because it uses the training mean, not the test mean. A test 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 ; compare models on the same evaluation set only, or use .
- Reading a high as "accurate". If varies a lot, can still mean errors that are too large for the job. Always report an error in the units of next to it.
- Training . It only grows with model complexity. Report it on a validation or test set.
- Errors that scale with . Being off by 10 on a value of 20 is worse than on a value of 2000. Then use a relative error (MAPE, , undefined at ) or model and report errors on that scale.
Practice
- Residuals are . Compute MAE, MSE and RMSE.
Answer
MAE , MSE , RMSE .
- A model always predicts the mean of the test targets. What is its 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 . 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.
- 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, is the variance of , 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?
- MSE
- MAE
- RMSE
A model has on the test set. What does that mean?
- It explains 40 % of the variance
- Its squared error is larger than that of always predicting the test mean
- The metric was computed wrongly; cannot be negative
- 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?
- B has a few very large errors
- B is biased upwards
- B was evaluated in a different unit
- B has smaller errors on average
You convert the target from minutes to seconds. Which metric does not change?
- MAE
- RMSE
- MSE