Sub topic 13
Scoring the final model on the test set
This chapter covers the last step of the modeling workflow: scoring the tuned model once on the held-out test set and reading the result. You should already be comfortable with the earlier chapters: the train/test split, the baseline, cross-validation with cross_val_score, and GridSearchCV. The code below is a complete script, so you can run it from top to bottom without the earlier sessions.
Why the test set is used once
Everything before this chapter used the training data only. Cross-validation split that training data into folds. The grid search scored each parameter combination on those folds. Each choice you made, such as Ridge versus gradient boosting or max_leaf_nodes=31 versus 63, was picked because it scored well on data the model was allowed to influence.
The test set has not influenced any of those choices. If you score on it once, the result is an honest estimate of how the model behaves on new houses. If you score on it, change something, and score again, the test set becomes a second validation set. After a few rounds the number is optimistic, and you have no clean data left to check it.
The rule is simple:
- Make all modeling decisions with training data and cross-validation.
- Score on the test set once.
- Report that number, even if it is worse than you hoped.
The complete script
The script below rebuilds the pipeline from the previous chapters and ends with the final evaluation. It sets random_state=42 everywhere, so you get the same split and the same model on each run.
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import GridSearchCV, train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
param_grid = {
"learning_rate": [0.05, 0.1],
"max_leaf_nodes": [15, 31, 63],
}
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=42),
param_grid,
cv=3,
scoring="neg_mean_absolute_error",
)
search.fit(X_train, y_train)
best_model = search.best_estimator_
print("Best params:", search.best_params_)
print("Best CV MAE:", -search.best_score_)
# Final evaluation: the only time the test set is used for scoring.
pred = best_model.predict(X_test)
base_pred = baseline.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
r2 = r2_score(y_test, pred)
print(f"Baseline test MAE: {mean_absolute_error(y_test, base_pred):.3f}")
print(f"Model test MAE: {mae:.3f}")
print(f"Model test RMSE: {rmse:.3f}")
print(f"Model test R2: {r2:.3f}")Two details in this script are easy to miss.
best_estimator_is already fitted.GridSearchCVhasrefit=Trueby default. After choosing the best parameters, it retrains that model on the whole training set. You do not callfitagain, and you never callfitonX_test.- The baseline is scored on the test set too. A model number means little alone. Scoring the baseline on the same rows gives you the comparison that shows whether the model adds value.
Reading the numbers
The target MedHouseVal is in units of $100,000. A test MAE of 0.32 means the model's predictions are off by about $32,000 on average. Your exact values depend on your scikit-learn version, but gradient boosting on this dataset typically lands near an MAE of 0.3 and an R² of 0.8 or higher. The mean-only baseline typically has an MAE near 0.9 and an R² near 0.
| Metric | What it tells you | Units |
|---|---|---|
| MAE | Average size of the error, all errors weighted equally | $100,000 |
| RMSE | Like MAE, but large errors count more because errors are squared first | $100,000 |
| R² | Share of the target's variance the model explains compared with always predicting the mean | None |
Some points to check in the output:
- RMSE is at least as large as MAE. If RMSE is much larger, a few predictions are far off. Look for them before you trust the average.
- R² near 0 means no better than the baseline. R² can also be negative on a test set. That means the model is worse than predicting the training mean.
- MAE and RMSE answer a business question. "Typically $32,000 off" is something a stakeholder can judge. R² is better for comparing models than for explaining one.
Comparing the test score with the CV score
The cross-validation score (-search.best_score_) and the test MAE should be close. A small gap is normal and has three sources:
- The model for the test run was refit on all of the training data, not on two thirds of it as in a 3-fold search.
- Each score comes from a different sample of houses, so each carries noise.
- The grid search picked the parameters with the best CV score. The best of several noisy scores is slightly optimistic. This is a mild form of selection bias.
If the test MAE is only slightly worse than the CV MAE, the process worked. If it is much worse, suspect leakage in your preprocessing. A test MAE far better than the CV MAE is also suspicious. Check that the split really happened before any other step.
Putting a range around the score
A single test MAE hides how uncertain it is. The test set has about 4,100 houses, and a different sample of houses would give a slightly different number. A bootstrap shows how much. You resample the per-house errors with replacement and recompute the mean many times. This needs no refitting, so it is cheap.
errors = np.abs(y_test.to_numpy() - pred)
rng = np.random.default_rng(42)
boot_means = [
rng.choice(errors, size=len(errors), replace=True).mean()
for _ in range(1000)
]
low, high = np.percentile(boot_means, [2.5, 97.5])
print(f"Test MAE {errors.mean():.3f} (95% interval {low:.3f} to {high:.3f})")This interval covers sampling noise in the test set only. It does not cover the variation from retraining with a different seed or split. Even so, it is enough to stop you from reading meaning into a difference in the third decimal place.
Looking for where the model fails
An average hides structure. Two quick checks cost almost nothing and often reveal real problems.
residuals = y_test - pred
print("Mean residual (bias):", round(residuals.mean(), 3))
capped = y_test >= 5.0
print("Rows at the price cap:", int(capped.sum()))
print("MAE on capped rows: ", round(errors[capped.to_numpy()].mean(), 3))
print("MAE on other rows: ", round(errors[~capped.to_numpy()].mean(), 3))- Mean residual. This should be close to 0. A large positive or negative value means the model systematically under- or over-predicts.
- The price cap. In this dataset, median house values above $500,000 are recorded as 5.0. The model can never see the true value of those houses, so it tends to under-predict them. The MAE on capped rows is usually clearly higher than elsewhere. This is a property of the data, not a bug in your model. A real project would note it in the report, and might filter these rows or treat them separately.
Common errors at this stage
- Fitting on the test set. Calling
best_model.fit(X_test, y_test)or fitting a scaler onX_testleaks the test data into the model. Only callpredictandtransformon test data. - Scoring with the wrong sign. Scorers such as
neg_mean_absolute_errorreturn negative numbers so that "higher is better" holds for every scorer. The metric functions (mean_absolute_error) return positive values. Do not mix them: negate scorer output when you report it, as shown above. - Argument order.
mean_absolute_error(y_true, y_pred)is symmetric, butr2_score(y_true, y_pred)is not. Passing the arguments in the wrong order gives a wrong R². - Reporting only R². A high R² can coexist with errors too large to be useful. Always report an error in the target's units.
- Comparing to nothing. Without the baseline, "MAE 0.32" has no reference point.
What to report
A short, honest report from this project would contain:
- The metric you chose and why (MAE, in dollars).
- The baseline's test score.
- The final model's test score, with an interval.
- The CV score, to show the two agree.
- Known weak spots, such as the price cap.
Exercise
Your tuned model has a cross-validation MAE of 0.33 and a test MAE of 0.32 (units of $100,000). A colleague suggests trying max_leaf_nodes=127 and re-scoring on the test set, because the test result "might improve". Why is this a problem, and what should you do instead?
Show answer
Each look at the test set that leads to a change makes the test set part of model selection, so the final score becomes optimistic and no longer measures performance on new data. Add 127 to the grid and rerun the grid search with cross-validation on the training set only. Choose by CV score. If you need a clean final number after that, use data that has never influenced any choice, such as newly collected houses. The agreement between the CV MAE (0.33) and test MAE (0.32) already shows the process worked, so there is no evidence of a problem to fix.
Exercise
A model has a test MAE of 0.32 and a test RMSE of 0.65. What does the large gap between them suggest, and what could you compute to investigate?
Show answer
RMSE squares errors before averaging, so a few very large errors raise it much more than MAE. A gap this wide suggests the model makes some large mistakes on a small group of houses. Investigate by sorting errors in descending order and inspecting the worst rows, or by comparing MAE on subsets such as the capped rows (y_test >= 5.0) against the rest.