Sub topic 4
Choosing how to measure error
This chapter assumes you can run scikit-learn code, know what features and a target are, and have loaded the California housing data in the previous chapters. Here you pick the numbers that will judge every model in the project.
Why the metric comes first
A regression model predicts a number. To compare models you need one number that says how wrong the predictions are. The target here, MedHouseVal, is in units of $100,000. An error of 0.5 means about $50,000.
Choose the metric before you train anything. If you choose it after seeing results, you may pick whichever one flatters your model.
The three metrics
Let y be the true values, ŷ the predictions, and n the number of rows.
- MAE (mean absolute error) is the average of
|y - ŷ|. It is in the target's units and easy to explain. Every miss counts in proportion to its size. - RMSE (root mean squared error) is the square root of the average of
(y - ŷ)². It is also in the target's units. Squaring makes large misses count much more than small ones. - R² (coefficient of determination) is
1 - (sum of squared errors of the model) / (sum of squared errors of always predicting the mean). It has no units. A score of 1 is perfect, 0 matches the mean predictor, and negative values are worse than the mean predictor.
| Metric | Units | Sensitive to large errors | Best value |
|---|---|---|---|
| MAE | Same as target | Low | 0 |
| RMSE | Same as target | High | 0 |
| R² | None | High | 1 |
A small worked example
Two models make errors on five houses. Both have the same total absolute error, but model B has one big miss.
import numpy as np
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score,
)
y_true = np.array([2.0, 3.0, 1.5, 4.0, 2.5])
pred_a = np.array([2.4, 2.6, 1.9, 3.6, 2.9]) # five misses of 0.4
pred_b = np.array([2.0, 3.0, 1.5, 4.0, 4.5]) # one miss of 2.0
for name, pred in [("A", pred_a), ("B", pred_b)]:
mae = mean_absolute_error(y_true, pred)
rmse = np.sqrt(mean_squared_error(y_true, pred))
r2 = r2_score(y_true, pred)
print(f"{name}: MAE={mae:.2f} RMSE={rmse:.2f} R2={r2:.2f}")Both models have an MAE of 0.40. Model B has an RMSE of about 0.89 against 0.40 for model A, because squaring punishes the single large miss. MAE alone cannot tell the two apart.
Which one to use in this project
This project uses MAE as the main metric and R² as a second view.
- MAE answers the question a buyer would ask: "How many dollars off is a typical prediction?"
- R² shows how much better the model is than the mean predictor, on a scale that does not depend on units.
- RMSE is worth reporting if large misses are costly. Here, a prediction that is $200,000 off is bad, but it is not four times worse than one that is $50,000 off in practical terms.
Scikit-learn's scoring functions assume that higher is better. For error metrics, it negates them. That is why later chapters pass scoring="neg_mean_absolute_error" and then flip the sign with -scores.mean().
Common errors
- Reading MAE as a percentage. It is in units of $100,000, so 0.53 means about $53,000.
- Passing arguments in the wrong order. Use
metric(y_true, y_pred). For MAE and RMSE the order does not change the result, but for R² it does. - Forgetting the sign flip on
neg_scorers and reporting a negative error. - Calling
mean_squared_error(..., squared=False)in new code. That argument is deprecated in recent versions. Takenp.sqrtof the result, or useroot_mean_squared_errorif your version has it.
Exercise
A model has an MAE of 0.40 and an RMSE of 0.89 on the same test set. What does the gap between the two numbers suggest, and which units are both numbers in?
Show answer
The gap suggests that a few predictions are far off, because RMSE squares errors and so weights large misses heavily, while MAE treats all misses equally. Both numbers are in the target's units, here $100,000, so the typical miss is about $40,000 and the error that punishes outliers is about $89,000.
Exercise
Why does cross_val_score return negative numbers when you use scoring="neg_mean_absolute_error", and how do you report the real MAE?
Show answer
Scikit-learn treats every score as "higher is better", so it negates error metrics. Report the real MAE by negating the result again, for example -scores.mean().