Sub topic 8
Measuring on held-out data, not training data
This chapter assumes you can compute MAE, RMSE, and R squared, and that you know what a train/test split is. It explains why the data you score on matters as much as the metric you choose.
Why training scores mislead
A model is fitted to its training data, so it has already seen those targets. Its errors on that data are usually smaller than its errors on new data. A training score therefore measures how well the model memorized, not how well it will predict.
Held-out data is a portion of the dataset that you set aside before fitting and never use for fitting. Scoring on it answers the question you care about: how large are the errors on rows the model has not seen?
The set-aside portion is usually called the test set. The rest is the training set.
Seeing the gap in code
The script below fits two models on the same split and scores each one on both the training and test data. A linear model is simple and has little room to memorize. A decision tree with no depth limit can grow until every training row has its own leaf.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
X, y = make_regression(n_samples=200, n_features=3, noise=10.0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
models = {
"linear": LinearRegression(),
"deep tree": DecisionTreeRegressor(random_state=0),
}
for name, model in models.items():
model.fit(X_train, y_train)
for label, X_part, y_part in (
("train", X_train, y_train),
("test", X_test, y_test),
):
pred = model.predict(X_part)
rmse = np.sqrt(mean_squared_error(y_part, pred))
r2 = r2_score(y_part, pred)
print(f"{name:10s} {label:5s} RMSE={rmse:7.2f} R2={r2:.3f}")Run it and compare the two models:
- The deep tree scores RMSE 0.00 and R squared 1.000 on the training rows. It reproduces each training target exactly, because every row sits in its own leaf.
- On the test rows the tree's RMSE rises and its R squared falls. The perfect training score said nothing about unseen data.
- The linear model's train and test numbers are close to each other. The noise level in the data (10.0) sets a floor on its error. Its small gap suggests it is not memorizing.
The size of the gap between training and test scores is a useful diagnostic. A large gap means the model fits the training data much better than it generalizes. This is called overfitting.
Reading the test score
The test score is an estimate of future performance, not a guarantee. Keep these points in mind:
- Small test sets are noisy. With 50 test rows, one extreme row can move RMSE noticeably. A different random split can give a different number.
- The split should resemble deployment. If the model will predict next month's values, a random split can be too optimistic. Splitting by time, so the test set comes after the training set, matches that use better.
- Use the same split to compare models. Fix
random_state, or reuse the same index arrays, so differences in score come from the models and not from the luck of the split.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Reporting training RMSE as the model's accuracy | Too optimistic, and worst for flexible models | Report the test RMSE |
| Calling `train_test_split` separately for features and targets without a shared seed | Rows and targets no longer line up | Split `X` and `y` in one call |
| Re-running the split until the test score looks good | The test set quietly becomes part of model selection | Choose the split once and tune on a validation set |
| Comparing models on different splits | Score differences mix model quality with split luck | Share one split or use cross-validation |
Training metrics are still worth printing. They show the gap and help you tell overfitting (a low training error with a high test error) from underfitting (a high error on both).
Exercise
A regression model has a training RMSE of 2.1 and a test RMSE of 9.8, both in the units of the target. A colleague says the model is accurate because its RMSE is only 2.1. What is wrong with that claim, and what does the gap suggest?
Show answer
The colleague is quoting the training score, which the model was fitted to and which is usually optimistic. The test RMSE of 9.8 is the better estimate of error on new data. The large gap suggests overfitting: the model memorized training rows instead of learning patterns that generalize. Reasonable next steps are to simplify the model, add regularization, or gather more data, and then re-check the test score.