Sub topic 3
Train, validation, and test sets
This chapter assumes you can fit a scikit-learn model with fit and predict. It also assumes you know what a loss function is and why training error alone can mislead. The chapter explains why one dataset must be divided into separate parts, what each part is for, and how to split data without corrupting your estimates.
Why one dataset is not enough
A model's training error measures how well it fits data it has already seen. A flexible model can drive that error very low by memorising noise, so training error says little about future performance. To estimate generalisation, you need data the model did not learn from.
Two different decisions need that unseen data:
- Model selection: choosing the polynomial degree, regularisation strength, number of layers, or number of training epochs.
- Final assessment: reporting how well the chosen model will perform in practice.
If you use the same data for both, the assessment is optimistic. Each time you compare candidates on a dataset and keep the best one, that dataset leaks a little information into your choices. After enough comparisons, the best score partly reflects luck and fit to that particular sample. Using three sets avoids this.
The three roles
| Set | Used for | Used how often | Typical share |
|---|---|---|---|
| Training | Fitting model parameters (weights, coefficients) | Every training step | 60% to 80% |
| Validation | Comparing models, tuning hyperparameters, early stopping | Many times | 10% to 20% |
| Test | One final estimate of generalisation | Once, at the very end | 10% to 20% |
A hyperparameter is a setting you choose before training rather than learn from data, such as the polynomial degree or the penalty strength alpha. Parameters are learned on the training set. Hyperparameters are chosen using the validation set. The test set informs neither.
Splitting in scikit-learn
train_test_split produces two parts. To get three, call it twice: first set aside the test set, then split the remainder into training and validation sets.
The example below uses 200 noisy sine samples. The test set takes 20% of the data. The validation set takes 25% of the remaining 80%, which is 20% of the total. That leaves a 60/20/20 split.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(200, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=200)
X_temp, X_test, y_temp, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_temp, y_temp, test_size=0.25, random_state=0
)
print(len(X_train), len(X_val), len(X_test))
best_degree, best_val = None, float("inf")
for degree in (1, 2, 3, 4, 6, 9, 12):
model = make_pipeline(
PolynomialFeatures(degree), StandardScaler(), LinearRegression()
)
model.fit(X_train, y_train)
val_mse = mean_squared_error(y_val, model.predict(X_val))
print(degree, round(val_mse, 3))
if val_mse < best_val:
best_degree, best_val = degree, val_mse
final = make_pipeline(
PolynomialFeatures(best_degree), StandardScaler(), LinearRegression()
)
final.fit(np.vstack([X_train, X_val]), np.concatenate([y_train, y_val]))
test_mse = mean_squared_error(y_test, final.predict(X_test))
print("chosen degree:", best_degree, "test MSE:", round(test_mse, 3))The loop uses only training and validation data. Only after the degree is chosen does the code touch the test set, and it does so exactly once. Refitting the chosen configuration on training plus validation data is common practice. The validation data has done its job and can now contribute to the final fit. The test set stays untouched.
The validation errors will usually fall and then rise as the degree grows. The best degree is the one with the lowest validation error, not the lowest training error.
Splitting well
A random split is a reasonable default, but several situations need a different approach.
Classification with imbalanced classes
If one class is rare, a random split can leave the validation or test set with too few examples of it. Pass stratify=y to train_test_split so each part keeps roughly the same class proportions.
Time-ordered data
If rows are ordered in time, random shuffling lets the model train on the future and predict the past. That inflates scores compared with real use. Split chronologically instead: train on the earliest data, validate on the next period, and test on the most recent. For repeated evaluation, TimeSeriesSplit provides chronological folds.
Grouped data
Suppose several rows come from the same patient, user, or device. If some of a patient's rows are in training and others in validation, the model can recognise the patient rather than learn the general pattern. Keep each group entirely in one set, for example with GroupShuffleSplit or GroupKFold.
Small datasets
With only a few dozen examples, a single 20% validation set is a noisy estimate. Changing the random seed can change which model looks best. The next chapters cover cross-validation, which addresses this by rotating the validation role across the data.
How big should each set be?
There is no fixed rule. The trade-off is this:
- A small training set gives a model that is worse than it could be, because it has less to learn from.
- A small validation or test set gives a noisy estimate, because the error is averaged over few examples.
With millions of examples, 1% for each of validation and test can be enough. With a few hundred, a fixed split is fragile. Judge by how much the score changes when you re-split with a different seed.
Preprocessing belongs after the split
Fitting a scaler on the full dataset before splitting lets statistics from validation and test rows (their mean and standard deviation) influence the training data. This is a form of data leakage. The effect is often small for scaling, but it is large for steps such as feature selection or target encoding.
Fit every preprocessing step on the training portion only, then apply it to the other sets. A scikit-learn Pipeline, as in the code above, does this automatically. A later chapter treats leakage in detail.
Common mistakes
- Reporting validation error as the final result. It was used to choose the model, so it is slightly optimistic.
- Tuning against the test set because "it is just a quick check".
- Splitting after oversampling or augmenting, which puts near-copies of the same example in different sets. Split first, then augment only the training set.
- Splitting randomly when the data is time-ordered or grouped.
Exercise
You tune the regularisation strength of a ridge model by trying 50 values and keeping the one with the lowest score on the test set. You then report that test score as your expected real-world error. What is wrong, and how do you fix it?
Show answer
The test set was used to make a modelling decision, so the reported score is optimistically biased: the best of 50 candidates partly reflects chance fit to that sample. Fix it by choosing the strength on a validation set (or with cross-validation on the training data), then evaluating the chosen model on the test set once.
Exercise
A dataset has 10 rows per customer, ordered by purchase date, and you want to predict next month's spending. Why is a plain random 60/20/20 split a poor choice, and what would you use instead?
Show answer
A random split puts rows from the same customer, and from later dates, into training while earlier rows go to validation and test. The model can then exploit customer identity and future information, inflating scores. Split chronologically (train on earlier months, validate and test on later ones) and keep each customer's rows within a single set if the goal is to generalise to new customers.