Regression Metrics
For regression the question is not "right or wrong?" but "how far off?" Every regression metric summarises the residuals — the differences between the true values and the predictions — in a different way. Choosing the right one depends on what kind of error hurts in your application.
The common metrics
| Metric | Formula (in words) | Unit | Notes |
|---|---|---|---|
| MAE | mean of absolute errors | same as target | easy to explain; robust to outliers |
| MSE | mean of squared errors | target² | punishes large errors heavily |
| RMSE | square root of MSE | same as target | like MSE but readable |
| R² | 1 − MSE / variance of y | none | share of variance explained; 1 is perfect, 0 = predicting the mean |
| MAPE | mean of absolute errors / true values | % | relative error; breaks when true values are near 0 |
Let's compute them by hand and with scikit-learn for a delivery-time model:
import numpy as np
from sklearn.metrics import (mean_absolute_error, mean_squared_error, root_mean_squared_error,
r2_score, mean_absolute_percentage_error)
true_min = np.array([32, 45, 28, 51, 38, 60, 25, 41])
pred_min = np.array([30, 49, 30, 45, 40, 52, 27, 43])
err = true_min - pred_min
print("residuals:", err)
print(f"MAE by hand: {np.abs(err).mean():.3f} sklearn: {mean_absolute_error(true_min, pred_min):.3f}")
print(f"MSE by hand: {(err ** 2).mean():.3f} sklearn: {mean_squared_error(true_min, pred_min):.3f}")
print(f"RMSE by hand: {np.sqrt((err ** 2).mean()):.3f} sklearn: {root_mean_squared_error(true_min, pred_min):.3f}")
r2_hand = 1 - (err ** 2).sum() / ((true_min - true_min.mean()) ** 2).sum()
print(f"R^2 by hand: {r2_hand:.3f} sklearn: {r2_score(true_min, pred_min):.3f}")
print(f"MAPE: {mean_absolute_percentage_error(true_min, pred_min) * 100:.1f} %")residuals: [ 2 -4 -2 6 -2 8 -2 -2]
MAE by hand: 3.500 sklearn: 3.500
MSE by hand: 17.000 sklearn: 17.000
RMSE by hand: 4.123 sklearn: 4.123
R^2 by hand: 0.862 sklearn: 0.862
MAPE: 8.2 %
"On average our delivery estimates are off by 3.5 minutes" (MAE) is a sentence anyone understands.
MAE vs RMSE: how outliers count
Two models with the same total absolute error can look very different under RMSE. Model A makes many small errors; model B is usually perfect but has one big miss:
import numpy as np
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
truth = np.full(10, 100.0)
model_a = truth + np.array([3, -3, 3, -3, 3, -3, 3, -3, 3, -3]) # many small errors
model_b = truth + np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 30]) # one big error
for name, pred in [("A (small errors)", model_a), ("B (one big miss)", model_b)]:
print(f"{name}: MAE={mean_absolute_error(truth, pred):.2f} RMSE={root_mean_squared_error(truth, pred):.2f}")A (small errors): MAE=3.00 RMSE=3.00
B (one big miss): MAE=3.00 RMSE=9.49
Same MAE, but RMSE is more than three times larger for model B. If occasional big misses are costly (a bridge load estimate, a medicine dose), prefer RMSE. If every unit of error costs the same (minutes of waiting), MAE is the honest choice.
R² can be negative
R² compares your model with the dumbest possible one: always predicting the mean. A model that's worse than that gets a negative R²:
import numpy as np
from sklearn.metrics import r2_score
y = np.array([10, 20, 30, 40, 50])
print("perfect: ", r2_score(y, y))
print("always the mean:", r2_score(y, np.full(5, y.mean())))
print("reversed: ", r2_score(y, y[::-1]))perfect: 1.0
always the mean: 0.0
reversed: -3.0
Looking at residuals
A single number hides patterns. Plotting residuals against predictions shows whether errors are random (good) or systematic (the model is missing something):
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(3)
x = rng.uniform(0, 10, 150).reshape(-1, 1)
y = 0.5 * x.ravel() ** 2 + rng.normal(0, 2, 150) # curved truth
model = LinearRegression().fit(x, y) # a straight line can't capture it
pred = model.predict(x)
residuals = y - pred
plt.scatter(pred, residuals, s=10)
plt.axhline(0, color="red")
plt.xlabel("Predicted value")
plt.ylabel("Residual (true - predicted)")
plt.show()
low = residuals[pred < 10].mean()
mid = residuals[(pred > 15) & (pred < 30)].mean()
print(f"mean residual for small predictions: {low:.2f}, for middle predictions: {mid:.2f}")mean residual for small predictions: 1.10, for middle predictions: -1.80
The residuals form a U-shape instead of a random band around zero: the straight line overestimates in the middle and underestimates at both ends. That's a clear signal to add a polynomial feature or try a non-linear model.
Metrics in cross validation
Pass the metric name to scoring. Error metrics are negated so that "higher is better" holds for every scorer:
from sklearn.datasets import load_diabetes
from sklearn.model_selection import cross_validate
from sklearn.linear_model import Ridge
X, y = load_diabetes(return_X_y=True)
scores = cross_validate(Ridge(alpha=0.1), X, y, cv=5,
scoring=["neg_mean_absolute_error", "neg_root_mean_squared_error", "r2"])
print(f"MAE {-scores['test_neg_mean_absolute_error'].mean():.1f}")
print(f"RMSE {-scores['test_neg_root_mean_squared_error'].mean():.1f}")
print(f"R^2 {scores['test_r2'].mean():.3f}")MAE 44.6
RMSE 54.8
R^2 0.480
Test yourself
Which metric is in the same unit as the target and treats every unit of error equally?
- MSE
- MAE
- R²
- Log loss
Two models have the same MAE, but model B has a much higher RMSE. What does that tell you?
- Model B is always better
- Model B makes some large errors
- Model B has a higher R²
- The metrics were computed wrongly
What does a negative R² mean?
- The model is perfect
- The model is worse than always predicting the mean
- The target has negative values
- There are missing values