Sub topic 2
Splitting data: train, validation, and test
This chapter assumes you know what features, labels, and overfitting are. It also assumes you can read basic scikit-learn code (fit, transform, predict) and NumPy arrays. The split is the base of every leakage defense in later chapters, so it is worth getting right early.
Why three sets
A model is judged on data it has not seen. Two different decisions need that kind of data, and they must not share it.
- Fitting: the model learns its parameters from the training set.
- Choosing: you compare models, features, and hyperparameters on the validation set.
- Reporting: you estimate final performance once on the test set.
Each time you look at a score and then change something, the data behind that score leaks a little into your choices. The validation set absorbs this effect while you iterate. The test set stays clean only if you do not use it for any decision.
| Set | Used for | How often you may look |
|---|---|---|
| Training | Learning parameters, fitting preprocessing | Constantly |
| Validation | Model selection, tuning, early stopping | Many times |
| Test | One final performance estimate | Once, at the end |
A common ratio is 60/20/20 or 70/15/15. With small data, a fixed validation set is noisy, and cross-validation (covered in a later chapter) replaces it. The test set is still held out.
Making the split
The simplest tool is train_test_split. Calling it twice produces three sets. Split off the test set first, so that nothing you do to the rest can touch it.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_features=10, random_state=0)
# Step 1: lock away the test set
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
# Step 2: split the remainder into training and validation
X_train, X_val, y_train, y_val = train_test_split(
X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=0
)
print(len(X_train), len(X_val), len(X_test)) # 600 200 200The second split uses test_size=0.25 because 25% of the remaining 80% is 20% of the whole.
Three arguments matter here.
random_statefixes the shuffle, so the split is reproducible. Without it, two runs give different sets, and a score you reported cannot be checked.stratify=ykeeps the class proportions the same in every part. This matters most with rare classes, where a random split can leave a set with almost no positives.shuffle=Trueis the default. It is correct for independent rows and wrong for ordered or grouped data, as described below.
The split comes first
The most important rule in this chapter is about order: split before you do anything that learns from the data. Learning from the data includes scaling, imputing, encoding categories, selecting features, and resampling. Any step that computes a statistic from rows is a form of fitting.
The following code shows the difference. The first version computes the mean and standard deviation from all rows. The second computes them from training rows only.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=500, n_features=10, random_state=0)
# Leaky: the scaler learns the mean and variance of the test rows too
X_scaled = StandardScaler().fit_transform(X)
X_train_bad, X_test_bad, y_train_bad, y_test_bad = train_test_split(
X_scaled, y, random_state=0
)
# Correct: split first, fit the scaler on training rows only
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)In the leaky version, the test rows have already shaped the scaling. The effect on one scaler is small, but the habit does not stay small. Imputation, target encoding, and feature selection leak much more, and a later chapter covers them. Pipelines, also covered later, make the correct order automatic.
Keep the test set untouched
The test set is easy to ruin without noticing. These habits all erode it.
- Checking test scores after each experiment, then keeping the change that raised them. The test set is now acting as a validation set.
- Looking at test-set distributions to decide how to clean or bin a feature.
- Retraining and re-testing until the number looks acceptable.
- Using the test set to choose a decision threshold.
None of these feels like cheating. The result is the same: the reported score is optimistic, because the model and its settings were selected by it. If you break the seal, you need a new test set that has not been seen.
A practical rule is to write down, before you start, the one moment when the test set will be scored. Many teams store the test rows in a separate file or table with restricted access, so that casual use is harder.
Rows must be independent
train_test_split assumes each row is an independent draw from the same population. A random shuffle then produces sets that resemble each other and resemble future data. When that assumption fails, a random split leaks, even if every fitted step is in the right order.
Three common breakdowns:
- Time order. Rows are observations over time, and the model will predict the future. A random split puts future rows in training. A time-based split is needed, and the temporal leakage chapter covers it.
- Groups. Several rows come from the same patient, user, or device. A random split puts siblings on both sides, and the model can memorize the group. Group-aware splits are needed.
- Duplicates. The same or near-identical row appears more than once, so the test set contains copies of training rows.
You can check the second and third cases before modeling. This snippet counts exact duplicate rows that cross the split.
import numpy as np
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
base = rng.integers(0, 5, size=(200, 4))
X = np.vstack([base, base[:50]]) # 50 rows are exact copies
y = rng.integers(0, 2, size=len(X))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
train_rows = {tuple(row) for row in X_train}
shared = sum(tuple(row) in train_rows for row in X_test)
print(f"{shared} of {len(X_test)} test rows also appear in training")Any nonzero count means the test score partly measures memory. Remove duplicates before splitting, or assign duplicates to the same side.
For the time-ordered case, the check is simple to state. The test rows should come after the training rows.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1) # rows ordered by time
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
assert train_idx.max() < test_idx.min()
print(train_idx, test_idx)For grouped rows, GroupKFold keeps each group on one side:
import numpy as np
from sklearn.model_selection import GroupKFold
X = np.arange(12).reshape(-1, 1)
y = np.array([0, 1] * 6)
groups = np.repeat([0, 1, 2, 3], 3) # e.g. three rows per patient
for train_idx, test_idx in GroupKFold(n_splits=2).split(X, y, groups):
assert set(groups[train_idx]).isdisjoint(groups[test_idx])Later chapters explain both tools in full. Here the point is that the split strategy must match how the model will be used. Ask what a new, unseen case looks like in production. If it is a new patient, split by patient. If it is a later date, split by date.
Edge cases
- Small datasets. A 20% test set of 100 rows is 20 rows, and the score will swing widely with the seed. Use repeated or nested cross-validation for selection, and accept a wide error bar on the final number.
- Rare classes. Use
stratify. With very few positives, check that each set has enough of them to compute the metric at all. - Imbalanced data and resampling. Oversampling or SMOTE must happen after the split and only on training rows. Oversampling first copies rows into the test set.
- Stratifying on groups or time.
stratifydoes not respect groups or order. For those, use the dedicated splitters. - A validation set that drifts from test. If validation and test come from different periods or sources, validation scores will not predict test scores. Build them the same way.
- Final retraining. After selecting a model, you may refit on training plus validation before the single test evaluation. The test set still stays out.
Quick reference
| Question | Answer |
|---|---|
| When do I split? | Before any step that learns from data |
| Which set do I tune on? | Validation, or cross-validation folds on the development set |
| Which set do I report on? | Test, once |
| Rows from the same entity? | Group-aware split |
| Rows ordered by time? | Time-based split |
| Rare classes? | Stratify |
Exercise
You scale all features with StandardScaler().fit_transform(X), then call train_test_split, train a model, and report test accuracy. Name the problem, say why the score is unreliable, and give the corrected order of steps.
Show answer
The scaler computed its mean and standard deviation using the test rows, so test-set information influenced the training features. This is preprocessing leakage, and the test score is not a clean estimate of performance on unseen data. The correct order is: split first, fit the scaler on the training rows only, then use that fitted scaler to transform both the training and test rows.
Exercise
A dataset has five rows per customer, and you plan to predict behavior for new customers. A random train_test_split gives 0.97 accuracy, but production accuracy is much lower. What is the likely cause, and what split should you use instead?
Show answer
Rows from the same customer appear in both training and test sets, so the model can recognize customers instead of learning general patterns. This is group leakage. Use a group-aware split such as GroupKFold (or GroupShuffleSplit) with customer ID as the group, so each customer lands entirely in one set.