Sub topic 4
Choosing how to measure error
This chapter assumes you can run Python with NumPy and scikit-learn installed, and that you know what a feature and a target are. Every later chapter reports a number from one of the metrics below, so we settle here what those numbers mean. We use a toy example only. The train/test split comes in the next chapter.
Why the metric comes before the model
A regression model outputs a number, and "how good is it?" has no single answer. A model can be off by a little on most houses and wildly wrong on a few. Different metrics weigh those two kinds of mistake differently. Choose the metric first, because it decides which model counts as "best" later, in cross-validation and in grid search.
All three metrics here start from the residual for each row: the prediction minus the true value. They differ in how they combine the residuals into one number.
Mean absolute error (MAE)
MAE averages the absolute size of the residuals:
MAE = mean(|ytrue − ypred|)
Its main virtue is that it is in the same units as the target. In this project the target MedHouseVal is the median house value in units of $100,000. An MAE of 0.4 therefore means the typical prediction is off by about $40,000. You can explain that sentence to anyone.
MAE treats every dollar of error equally. A $100,000 miss counts exactly twice as much as a $50,000 miss.
Mean squared error and RMSE
Mean squared error (MSE) squares each residual before averaging:
MSE = mean((ytrue − ypred)²)
Squaring makes large errors count much more. A miss of 1.0 contributes 1.0, but a miss of 3.0 contributes 9.0. The units are squared too (here, squared $100,000), which is hard to read. Taking the square root fixes that and gives the root mean squared error (RMSE):
RMSE = sqrt(MSE)
RMSE is back in target units, so it is comparable to MAE. It is always greater than or equal to MAE, and the gap tells you something. If RMSE is close to MAE, the errors are fairly even in size. If RMSE is much larger, a few large errors dominate.
R², the coefficient of determination
R² compares your model with the simplest possible predictor, one that always answers with the mean of the target:
R² = 1 − (sum of squared residuals of your model) / (sum of squared residuals of the mean predictor)
- R² = 1 means perfect predictions.
- R² = 0 means no better than always predicting the mean.
- R² < 0 means worse than predicting the mean. This can happen, especially on data the model has not seen.
R² has no units, so it is useful for a rough "how much of the variation did we capture" reading. It does not tell you the typical error in dollars.
All three on a toy example
Here are five houses. The numbers are small enough to check by hand.
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])
y_pred = np.array([2.2, 2.6, 1.9, 3.0, 2.5])
mae = mean_absolute_error(y_true, y_pred)
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
r2 = r2_score(y_true, y_pred)
print(f"MAE: {mae:.3f}")
print(f"RMSE: {rmse:.3f}")
print(f"R2: {r2:.3f}")The output is:
MAE: 0.400
RMSE: 0.522
R2: 0.632The residuals are 0.2, −0.4, 0.4, −1.0 and 0.0. Their absolute values sum to 2.0, so MAE is 2.0 / 5 = 0.4. Their squares sum to 1.36, so MSE is 0.272 and RMSE is about 0.522. The true values have mean 2.6 and a total squared deviation of 3.70, so R² is 1 − 1.36 / 3.70 ≈ 0.632.
The arguments go in the order (y_true, y_pred). For MAE and MSE, swapping them changes nothing. For r2_score, swapping them gives a different and wrong answer, so keep the order.
How one big miss changes the picture
Now change a single prediction. The fourth house is truly 4.0, and the model now predicts 1.0 instead of 3.0.
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
y_true = np.array([2.0, 3.0, 1.5, 4.0, 2.5])
y_pred_bad = np.array([2.2, 2.6, 1.9, 1.0, 2.5])
print(f"MAE: {mean_absolute_error(y_true, y_pred_bad):.3f}")
print(f"RMSE: {np.sqrt(mean_squared_error(y_true, y_pred_bad)):.3f}")This prints:
MAE: 0.800
RMSE: 1.368MAE doubled, from 0.4 to 0.8. RMSE rose from 0.522 to 1.368, which is 2.6 times higher. The ratio RMSE / MAE went from about 1.3 to about 1.7. That jump is the signature of one large error among mostly small ones.
Which one should you use?
The choice depends on what an error costs.
| Metric | Units | Sensitivity to large errors | Best used for |
|---|---|---|---|
| MAE | Target units | Low, each error counts in proportion to its size | Reporting a typical error to a non-technical reader |
| RMSE | Target units | High, big misses are punished | Cases where a large miss is much worse than several small ones |
| R² | None | Same as squared error | Quick comparison of models on one dataset |
In this project, MAE is the main metric. The reasons are:
- A price prediction that is off by $40,000 is easy to interpret.
- The target has some extreme values, and we do not want a handful of them to decide which model wins.
- A single headline number lets us compare the baseline, Ridge and gradient boosting directly.
We still report R² beside it, and we check RMSE when MAE looks fine but the results feel off.
Using the metrics inside scikit-learn tools
Functions such as cross_val_score and GridSearchCV take a scoring string. The names for our three metrics are:
"neg_mean_absolute_error""neg_root_mean_squared_error""r2"
The "neg" prefix exists because scikit-learn always treats a higher score as better. Errors are better when lower, so the library negates them. A score of −0.42 means an MAE of 0.42. When you print a cross-validation result, flip the sign yourself, as the Ridge example in a later chapter does with -scores.mean(). R² is already "higher is better" and is not negated.
A reference point: the mean predictor
An error number means little alone. Is an MAE of 0.8 good? That depends on how hard the problem is. The simplest answer is to measure a predictor that ignores all features and always returns the mean target value. Any real model should beat it. This is the idea behind the baseline in the next chapters. We can compute it now on the full dataset, purely to illustrate the metrics, not to evaluate anything.
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
y = fetch_california_housing(as_frame=True).frame["MedHouseVal"]
constant = np.full(len(y), y.mean())
print("MAE: ", round(mean_absolute_error(y, constant), 3))
print("RMSE:", round(float(np.sqrt(mean_squared_error(y, constant))), 3))
print("R2 is zero:", np.isclose(r2_score(y, constant), 0.0))Two things stand out. The RMSE of a constant predictor equals the standard deviation of the target, because both measure spread around the mean. And R² is exactly 0 here, because R² is defined relative to this very predictor. Later, on held-out data, the mean of the training set differs slightly from the mean of the test set, so the baseline's test R² lands near zero but not exactly on it.
Pitfalls specific to this dataset
- Units. MAE and RMSE are in units of $100,000. Convert before you quote them. Saying "the error is 0.4" to a stakeholder invites confusion.
- A capped target. The California housing target tops out at 5.0, which is $500,000. Many districts sit at this cap, so the data hides how expensive those homes really are. Errors there may look small only because the values were clipped.
- Errors that scale with price. A $40,000 miss matters more on a $100,000 house than on a $450,000 one. MAE and RMSE do not capture this. Relative error metrics exist, but we stay with the three above to keep the project focused.
- One number hides the shape. Two models with the same MAE can fail in different places. Check RMSE beside MAE, and look at the largest residuals when it matters.
- R² on its own. A high R² does not mean the typical error is small in dollars. Always report an error metric in target units next to it.
Exercise
A model predicts [3.0, 2.0, 4.0] for houses whose true values are [3.0, 3.0, 2.0]. Compute MAE and RMSE by hand. Which is larger, and what does the gap say about the errors?
Show answer
The residuals are 0, −1 and 2. MAE = (0 + 1 + 2) / 3 = 1.0. The squares are 0, 1 and 4, so MSE = 5 / 3 ≈ 1.667 and RMSE = sqrt(1.667) ≈ 1.291. RMSE is larger. The gap shows that one error (the 2.0 miss) is bigger than the others and is pulled up by squaring.
Exercise
You run crossvalscore with scoring="negmeanabsolute_error" and get a mean of −0.52 for model A and −0.47 for model B. Which model is better, and what is each model's MAE in dollars?
Show answer
Model B is better, because −0.47 is greater than −0.52 and a higher score is better. Removing the sign gives MAE 0.47 for B and 0.52 for A. Since the target is in units of $100,000, B is off by about $47,000 and A by about $52,000.