Sub topic 13
Scoring the final model on the test set
This chapter assumes you have followed the earlier chapters. You should know the train/test split, the baseline, cross-validation, and the grid search over HistGradientBoostingRegressor. Here you spend the test set for the first time.
Why the test set is used once
Cross-validation and the grid search only touched the training data. The test set has stayed hidden so far. Its score is an honest estimate of performance on new houses only if no modeling decision was based on it.
Every time you look at the test score and then change something, the test set leaks into your choices. The score then becomes optimistic. So the order is fixed: choose features, model, and hyperparameters first, then score the test set once.
Running the final evaluation
The script below is self-contained. It repeats the split and the search so you can run it from a fresh session. GridSearchCV refits the best parameters on the full training set, so best_estimator_ is ready to predict.
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
df = fetch_california_housing(as_frame=True).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
)
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=42),
{"learning_rate": [0.05, 0.1], "max_leaf_nodes": [15, 31, 63]},
cv=3,
scoring="neg_mean_absolute_error",
)
search.fit(X_train, y_train)
best_model = search.best_estimator_
print("Best CV MAE:", -search.best_score_)
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
for name, model in [("Baseline", baseline), ("Tuned model", best_model)]:
pred = model.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = mean_squared_error(y_test, pred) ** 0.5
r2 = r2_score(y_test, pred)
print(f"{name}: MAE={mae:.3f} RMSE={rmse:.3f} R2={r2:.3f}")Scoring the baseline on the test set is fine. It is a reference point and involves no tuning.
Reading the numbers
The target is in units of $100,000. An MAE of 0.30 means predictions are off by about $30,000 on average.
| Metric | What it tells you | What to compare |
|---|---|---|
| MAE | Average size of the error, in target units | The baseline MAE |
| RMSE | Like MAE, but large errors count more | MAE. A much larger RMSE means a few big misses |
| R² | Share of variance explained. The baseline scores about 0 | 1.0 is perfect. Negative is worse than the mean |
Check three things:
- The tuned model beats the baseline on every metric.
- The test MAE is close to the cross-validation MAE. A small gap is normal. A large gap points to leakage or an unlucky split.
- The error is small enough for the use you have in mind. A $30,000 average miss may be too large for some decisions.
Common errors
- Tuning against the test score. If the result disappoints, resist adjusting the model and rescoring. Go back to cross-validation, and accept that the test number will be slightly less independent if you repeat the process.
- Fitting on the test set. Call
predictonX_test, neverfit. - Comparing across different metrics. Cross-validation scored with
neg_mean_absolute_errorreturns negative values, so negate them before comparing with the test MAE. - Treating one number as exact. The test set is a finite sample, so the score has noise around it.
Exercise
Cross-validation gives a MAE of 0.32 for your tuned model, but the test MAE is 0.55. Name two likely causes and what you would check first.
Show answer
One cause is leakage in preprocessing or tuning, where the cross-validation score was too optimistic because information from the validation folds reached training. The other is a test set that differs from the training data, for example because of an unlucky split or a data shift. Check first that all preprocessing sits inside the pipeline and was fit on training data only. Then re-split with a different random_state and see whether the gap persists.