Sub topic 8
Measuring on held-out data, not training data
What this chapter assumes
You should know how to compute MAE, RMSE, and R squared, either by hand or with sklearn.metrics. You should also know what a train/test split is and have a rough idea of what a regression model fits. This chapter covers where the data you score on comes from, because that choice decides whether the number you report is trustworthy.
Why training error misleads
A model is fitted by adjusting its parameters to reduce error on the training rows. Scoring it on those same rows asks how well it memorized them. That is not what you care about. You care about how it will do on rows it has never seen, such as next month's customers or tomorrow's sensor readings.
The gap between the two grows with model flexibility. A straight line has few parameters and cannot bend to follow noise. A deep decision tree, a high-degree polynomial, or a neural network can. Such a model can reach near-zero training error by fitting noise, and that noise will not repeat in new data. This is called overfitting.
Training metrics are therefore biased in one direction. They are optimistic: the training MAE and RMSE come out too low, and the training R squared comes out too high. The more flexible the model, the larger the bias.
The train/test split
The standard fix is to set aside some rows before fitting. The model never sees them during training. After fitting, you predict on those rows and compute the metrics against their true targets. These rows are called the held-out set, or the test set.
The next example fits two models on the same split. One is a linear model. The other is a decision tree with no depth limit, so it can memorize its training rows. It prints each metric on both the training and test rows.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, 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
)
def report(name, model):
model.fit(X_train, y_train)
splits = (("train", X_train, y_train), ("test", X_test, y_test))
for split, X_part, y_part in splits:
pred = model.predict(X_part)
mae = mean_absolute_error(y_part, pred)
rmse = np.sqrt(mean_squared_error(y_part, pred))
r2 = r2_score(y_part, pred)
print(f"{name:6s} {split:5s} MAE={mae:7.2f} RMSE={rmse:7.2f} R2={r2:6.3f}")
report("linear", LinearRegression())
report("tree", DecisionTreeRegressor(random_state=0))The exact numbers depend on your scikit-learn version, but the pattern is stable:
- The unrestricted tree gets a training MAE and RMSE of exactly 0 and a training R squared of 1.0. Every training row sits in its own leaf, so the tree reproduces each target.
- On the test rows the tree's errors are much larger. Its RMSE is typically several times the noise level of 10.
- The linear model scores almost the same on both splits. Its test RMSE is close to the noise level of 10. This is the best any model can do here, because the noise cannot be predicted.
Judged by training metrics, the tree looks perfect and wins. Judged by test metrics, the linear model wins clearly. Only the test metrics describe future performance.
What a held-out score does and does not tell you
A test score is an estimate of future error, and it carries its own uncertainty.
- Small test sets give noisy estimates. With 50 test rows, one extreme row can move RMSE noticeably. Changing the random seed of the split can change the score. If a difference between two models is smaller than that seed-to-seed variation, you cannot say which is better.
- The test set must look like future data. If production data differs from your test data (a different season, region, or customer type), the test score will not predict production error.
- The score is in the target's units. MAE and RMSE from a test set are still in the units of the target. R squared is still unitless. Moving to held-out data changes where the rows come from, not what the metrics mean.
R squared has one extra subtlety. On a test set it is computed with the test set's own mean as the baseline, not the training mean. Scikit-learn's r2_score(y_test, pred) does this automatically. The next chapter's topic, negative R squared, appears on held-out data when the model's errors exceed those of simply predicting that mean.
Common errors
Data leakage
Data leakage means information from the test rows influences the fitted model. The mistake is easy to make and hard to notice, because the score simply looks good.
Typical causes:
- Fitting a scaler, imputer, or feature selector on the full dataset before splitting. The test rows' mean and spread then shape the training features.
- Including a feature that is computed from the target, or that is only known after the outcome happens.
- Having duplicate or near-duplicate rows land on both sides of the split.
- Choosing hyperparameters by looking at the test score again and again. Each peek lets the test set steer your choices, so it stops being unseen.
The rule is to split first, then fit every preprocessing step on the training part only. A scikit-learn Pipeline enforces this because it refits each step on whatever data you hand to fit.
Random splits on ordered data
A random split shuffles rows. That is fine for independent rows. It is wrong for time series, where the model must predict the future from the past. A shuffled split lets the model train on rows that come after some of the test rows, so the test score is too good. For ordered data, split by time: train on earlier rows and test on later ones.
Grouped data has a similar problem. If several rows come from the same patient, store, or machine, a random split puts rows from the same group on both sides. The model then partly recognizes the group instead of generalizing. Split by group in that case.
Reusing the test set
If you try twenty model variants and report the best test score, that score is optimistic. You selected it because it was high, partly by luck. To avoid this, use a separate validation step for choosing models, and touch the test set once at the end.
Cross-validation for model selection
Cross-validation repeats the train/validation idea several times. With 5-fold cross-validation, the training data is cut into five parts. Each part takes a turn as the validation set while the model is fitted on the other four. You get five scores and can look at their mean and spread.
The example below combines it with a pipeline. The scaler is refitted inside every fold, so no fold leaks into another. It then evaluates once on the untouched test set.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
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
)
model = make_pipeline(StandardScaler(), LinearRegression())
cv = KFold(n_splits=5, shuffle=True, random_state=0)
# scikit-learn maximizes scores, so error metrics come back negated.
scores = cross_val_score(
model, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error"
)
rmse_per_fold = -scores
print("Validation RMSE per fold:", np.round(rmse_per_fold, 2))
print(f"Mean {rmse_per_fold.mean():.2f}, std {rmse_per_fold.std():.2f}")
# Final check: fit on all training data, score once on the test set.
model.fit(X_train, y_train)
test_rmse = np.sqrt(mean_squared_error(y_test, model.predict(X_test)))
print(f"Test RMSE: {test_rmse:.2f}")The spread across folds shows you how much a single split can mislead. The test RMSE at the end should fall near the fold scores. If it falls far outside them, suspect a mismatch between your training and test data.
A quick reference
| Situation | What goes wrong | What to do |
|---|---|---|
| Scoring on training rows | Error looks too low and R squared too high | Score on rows the model never saw |
| Scaler fitted before the split | Test statistics leak into training | Split first, or use a `Pipeline` |
| Many models compared on one test set | The best test score is optimistic | Pick with cross-validation, test once |
| Time-ordered data with random split | Model trains on the future | Split by time |
| Rows from the same group on both sides | Model recognizes groups | Split by group |
| Very small test set | Score changes a lot with the seed | Use cross-validation, report the spread |
Reporting held-out results
When you report a metric, say which data it was computed on. "RMSE of 9.8" is incomplete. "RMSE of 9.8 on a held-out test set of 50 rows" is something a reader can check and judge. Include the split method (random, by time, or by group), and give the training score next to it when you want to show how large the gap is.
Exercise
A model has a training RMSE of 2.1 and a test RMSE of 9.7. A teammate says the test number is wrong because it is so different from the training number. What is the more likely explanation, and what would you check next?
Show answer
The more likely explanation is overfitting. The training RMSE is optimistic because the model was fitted to those rows, and the test RMSE is the honest estimate. Next, check whether the model is too flexible (for example an unlimited tree depth) and compare against a simpler model's train and test scores. Also check that the test data is similar to the training data, and that no leakage inflates the training side.
Exercise
You fit a StandardScaler on the full dataset, then split into train and test, then fit a linear model on the training part. Why is the test score unreliable, and how do you fix it?
Show answer
The scaler used the test rows' mean and standard deviation, so information about the test set reached the training features. This is leakage and it makes the test score slightly optimistic. The fix is to split first and fit the scaler on the training rows only, or to put the scaler and model in a Pipeline so each fit step sees only training data.
Exercise
You compare ten model variants on the same test set and report the lowest RMSE. Why is that number likely too optimistic, and what is a better procedure?
Show answer
Choosing the best of ten scores selects partly for luck, so the winning score overstates real performance, and the test set is no longer unseen. A better procedure is to compare variants with cross-validation on the training data, pick one, and evaluate it once on the test set.