Sub topic 6
Measuring error: MSE, RMSE, MAE and R-squared
This chapter assumes you can fit a LinearRegression, call predict, and split data with train_test_split. You should also be comfortable with NumPy arrays and with the idea of a mean and a variance. Here you will learn what each common regression metric measures, how to compute it in scikit-learn, and which mistakes make a score misleading.
Why one number is not enough
A fitted model produces predictions. To judge them, you compare each prediction with the true value and summarize the differences. The summary you pick changes what you see.
The basic ingredient is the residual, the actual value minus the predicted value:
e_i = y_i - ŷ_i
All four metrics in this chapter are built from residuals. They differ in how they combine them.
The four metrics
Mean squared error (MSE)
MSE is the average of the squared residuals:
MSE = (1/n) * Σ (y_i - ŷ_i)²
Squaring does two things. It makes every term non-negative, so positive and negative errors cannot cancel. It also punishes large errors much more than small ones. A residual of 10 contributes 100, while ten residuals of 1 contribute only 10 together.
MSE is also the quantity ordinary least squares minimizes on the training data, so it connects directly to how the model was fitted. Its drawback is units. If y is in dollars, MSE is in dollars squared, which is hard to read.
Root mean squared error (RMSE)
RMSE is the square root of MSE:
RMSE = sqrt(MSE)
It returns the error to the units of y. An RMSE of 12 000 on house prices in dollars means a typical error on the order of 12 000 dollars, weighted toward the larger misses. RMSE is the usual headline number for regression.
Mean absolute error (MAE)
MAE is the average of the absolute residuals:
MAE = (1/n) * Σ |y_i - ŷ_i|
It is also in the units of y, and every error counts in proportion to its size. A single outlier moves MAE far less than it moves RMSE. MAE is often easier to explain to a non-technical audience: it is the average distance between prediction and truth.
R-squared (R²)
R² compares your model with a trivial baseline that always predicts the mean of y:
R² = 1 - SS_res / SS_tot
Here SS_res is the sum of squared residuals of your model, and SS_tot is the sum of squared differences between each y_i and the mean of y. The ratio is unitless.
- R² = 1 means perfect predictions.
- R² = 0 means the model does no better than predicting the mean.
- R² < 0 means the model is worse than predicting the mean. This is possible on test data.
A common reading is "the fraction of variance explained". That is accurate for training data with an intercept in OLS. On held-out data it is better to think of it as "improvement over the mean baseline".
Comparing the metrics
| Metric | Units | Sensitive to outliers | Lower or higher is better | Typical use |
|---|---|---|---|---|
| MSE | squared units of `y` | Very high | Lower | Optimization and model comparison |
| RMSE | units of `y` | High | Lower | Reporting a typical error size |
| MAE | units of `y` | Moderate | Lower | Robust, easy-to-explain error |
| R² | none | High | Higher | Comparing against a mean baseline |
RMSE is never smaller than MAE on the same predictions. If the two are close, errors are fairly uniform. If RMSE is much larger than MAE, a few large errors dominate.
Computing the metrics in scikit-learn
The functions live in sklearn.metrics. Each takes the true values first and the predictions second. The order matters for R², which is not symmetric.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("coef:", model.coef_, "intercept:", model.intercept_)
print("RMSE:", np.sqrt(mean_squared_error(y_test, pred)))
print("MAE:", mean_absolute_error(y_test, pred))
print("R2:", r2_score(y_test, pred))The data are generated with slope 3, intercept 2 and noise of standard deviation 1. Because the noise is the only source of error, RMSE should land near 1, MAE near 0.8, and R² close to 1. You can check this: for normally distributed noise, MAE is about 0.8 times the standard deviation.
Two practical notes:
- Older tutorials use
mean_squared_error(..., squared=False)to get RMSE. That argument was deprecated and later removed. Takingnp.sqrtyourself works in every version. Recent releases also provideroot_mean_squared_error. model.score(X_test, y_test)returns R² for regressors. It is a shortcut forr2_score(y_test, model.predict(X_test)).
Evaluate on held-out data
Training error always looks better than test error, because the model was fitted to the training rows. Reporting metrics on the training set tells you how well the model memorized, not how well it will predict new data. Compute your reported numbers on the test set, or on validation folds during cross-validation.
Comparing the two is useful as a diagnostic:
- Train and test scores both poor: the model underfits.
- Train score good, test score much worse: the model overfits.
- Both good and close: the model generalizes.
Choosing a metric
No metric is correct in every situation. Ask what a mistake costs.
- If large errors are disproportionately costly, such as underestimating the load on a server, prefer RMSE or MSE.
- If every unit of error costs the same, or the data contain outliers you do not want to dominate, prefer MAE.
- If you need a scale-free number to compare across targets or against a baseline, use R².
Report more than one metric when you can. RMSE and MAE together show whether outliers drive the error. R² alone hides the size of the error in real units.
Pitfalls
R² depends on the spread of the target
The same absolute error gives a high R² when y varies widely and a low R² when y varies little. You cannot compare R² across datasets with different target variance. RMSE in real units is comparable if the target is in the same units.
R² does not show a good fit
A high R² does not prove the model is right. A straight line fitted to a curved relationship can still score well. Residual plots, covered in the next chapter on residuals, reveal the curvature that the score hides.
Adding features inflates training R²
For OLS with an intercept, adding any feature, even pure noise, never lowers training R². That is why you should judge by test or cross-validated R², not by training R². Adjusted R² penalizes extra features, but scikit-learn does not provide it, and held-out scores serve the same purpose.
Scale and transformed targets
If you fit a model to log(y), the metrics describe errors in log units. An RMSE of 0.2 on a log scale means roughly a 20 percent multiplicative error, not 0.2 dollars. Convert predictions back before computing metrics if you want errors in original units. Be aware that back-transforming introduces its own bias.
One small test set is noisy
A single split on a few dozen rows gives a metric that changes noticeably with random_state. Cross-validation, covered in a later chapter, averages over several splits for a steadier estimate.
Constant targets
If every y_test value is identical, SS_tot is zero and R² is undefined. scikit-learn returns a fixed value with a warning, not a meaningful score.
How the metrics relate to each other
For a model with an intercept, fitted by OLS and evaluated on its own training data, R² can be written using MSE:
R² = 1 - MSE / Var(y)
So on the training set, R² is just MSE rescaled by the variance of the target. This explains why R² and RMSE usually rank models the same way when the data are the same. They can disagree only when you compare across different targets or datasets.
Summary
- Residuals are the building block. MSE squares them, RMSE returns to original units, MAE uses absolute values, and R² compares against a mean baseline.
- RMSE weights large errors more than MAE does. A big gap between them points to outliers.
- Always report metrics on held-out data and pass the true values first.
- Pair a numeric score with a baseline and, in the next chapters, with residual plots.
Exercise
A model predicts house prices in dollars. On the test set, MAE is 8 000 and RMSE is 20 000. What does the gap tell you, and which metric would you report if a few very expensive houses should not dominate the summary?
Show answer
RMSE is much larger than MAE because squaring gives large residuals extra weight, so a few predictions are far off while most are close. This suggests outliers, probably the expensive houses. To keep them from dominating the summary, report MAE (and mention RMSE as well), since MAE counts each error in proportion to its size.
Exercise
A model has a training R² of 0.95 and a test R² of 0.40. Name the likely problem and one way to confirm it without collecting new data.
Show answer
The model is likely overfitting: it fits the training rows well but generalizes poorly. You can confirm it with cross-validation. If the cross-validated R² is also much lower than the training R², the gap is real and not an accident of one split. Comparing against a DummyRegressor baseline also shows how much the model actually gains on unseen data.