Sub topic 5
Splitting data into train, validation and test sets
This chapter assumes you can call scikit-learn's fit and predict, and that you know what a feature matrix X and a target vector y are. Splitting comes before preprocessing and modeling, because every later estimate of quality depends on how you split.
Why one dataset becomes three
A model is judged by how well it predicts rows it has not seen. If you score it on the rows it learned from, the score rewards memorization. So you hold some rows back. Each held-back set answers a different question:
| Set | Used for | How often you look at it |
|---|---|---|
| Training | Fitting model parameters (and preprocessing statistics) | Constantly |
| Validation | Comparing models and choosing hyperparameters | Many times |
| Test | Reporting the final expected performance | Once |
The validation set exists because choosing among models is itself a kind of learning. Each time you pick the configuration with the best validation score, you fit a little to that set. After enough comparisons, the validation score is optimistic. The test set stays untouched so that one honest number remains.
A three-way split with scikit-learn
train_test_split produces two parts. For three, call it twice. Split off the test set first, so nothing you do afterwards can touch it.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
# Step 1: lock away 20% as the test set.
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
# Step 2: split the rest. 25% of 80% is 20% of the original data.
X_train, X_val, y_train, y_val = train_test_split(
X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=42
)
for name, part in [("train", y_train), ("val", y_val), ("test", y_test)]:
print(name, len(part), round(part.mean(), 3))The printed class share (the mean of a 0/1 target) should be almost identical in all three parts. That is what stratify does.
The second test_size is a fraction of the remaining rows, not of the full dataset. This is a common arithmetic slip. For a 60/20/20 split, use 0.2 first and then 0.25.
Choosing the proportions
There is no universal ratio. Use these considerations:
- With tens of thousands of rows or more, 98/1/1 can be enough, because 1% is still hundreds or thousands of rows.
- With a few hundred rows, a single validation set is noisy. Use cross-validation on the development set instead (a later chapter covers it), and keep only the test set separate.
- The test set must be large enough that its score is stable. For a rare class, count the rare rows in the test set, not the total rows. A test set with 8 positive cases gives a very uncertain recall.
Stratification
Random splitting can, by chance, give the test set a different class balance from the training set. On a dataset with 2% positives, an unstratified split can easily put 1% in one part and 3% in another. stratify=y keeps the class proportions about equal in each part.
Stratify classification targets, especially imbalanced ones. For a continuous regression target, you can stratify on bins of the target, for example quartiles made with pd.qcut, if the distribution is skewed.
Reproducibility
Without random_state, each run produces a different split, so scores change between runs and you cannot tell whether a change came from the model or the split. Fix the seed and record it. Be aware that a single fixed split is still only one sample of possible splits. Differences of a fraction of a percent between models on one split are often noise.
When a random split is wrong
A random row-level split assumes rows are independent and that future data looks like past data. Two common situations break this.
Grouped rows
If one patient, customer or device contributes several rows, a random split puts some of their rows in training and others in test. The model can recognize the entity rather than learn the general pattern. The score looks better than it will on new entities. Split by group so each group lands in exactly one part.
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
rng = np.random.default_rng(0)
groups = np.repeat(np.arange(100), 5) # 100 patients, 5 rows each
X = rng.normal(size=(500, 3))
y = rng.integers(0, 2, size=500)
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
train_idx, test_idx = next(splitter.split(X, y, groups=groups))
overlap = set(groups[train_idx]) & set(groups[test_idx])
print("rows:", len(train_idx), len(test_idx))
print("shared patients:", overlap)The overlap is an empty set. Note that GroupShuffleSplit does not stratify. If you need both grouping and stratification, look at StratifiedGroupKFold.
Data ordered in time
If the model will predict the future, the test set must come after the training data. Shuffling lets the model train on events that happen after some of its test rows, which is information it will not have in production.
import pandas as pd
df = pd.DataFrame({
"date": pd.date_range("2024-01-01", periods=100, freq="D"),
"x": range(100),
}).sample(frac=1, random_state=0) # shuffled on purpose
df = df.sort_values("date")
n = len(df)
train = df.iloc[: int(n * 0.6)]
val = df.iloc[int(n * 0.6): int(n * 0.8)]
test = df.iloc[int(n * 0.8):]
print(train["date"].max() < val["date"].min())
print(val["date"].max() < test["date"].min())Both lines print True. Sort first, then cut at positions. For cross-validation on time-ordered data, use TimeSeriesSplit.
Edge cases and failure modes
- Duplicates. Exact or near-duplicate rows on both sides of a split act like leakage. Remove duplicates before splitting, or group them.
- Splitting before or after cleaning. Split first. Any statistic computed from data (a mean for imputation, a scaler's variance, category lists) should be learned from the training rows only. The next chapter covers this.
- Re-splitting after a bad test score. If the test score disappoints and you reshuffle until it looks good, the test set has become a validation set. Decide the split once.
- Distribution mismatch. If production data differs from your sample, such as a new region or a new device, a random split still looks fine while real performance drops. Where possible, make the test set resemble deployment.
- Peeking. Looking at test rows during exploration, even just plotting them, can influence your feature choices. Do exploratory analysis on the training set.
Summary of decisions
- Do rows belong to groups? Split by group.
- Does the model predict the future? Split by time.
- Is the target imbalanced or categorical? Stratify.
- Is the dataset small? Keep a test set and use cross-validation on the rest instead of a fixed validation set.
- Otherwise, use a stratified random split with a fixed seed.
Exercise
A dataset has 1,000 rows from 200 customers, with about 5 rows per customer, and a target that is 10% positive. You run train_test_split(X, y, test_size=0.2, stratify=y, random_state=1) and get a validation accuracy of 97%, but the model performs much worse on new customers. What is the likely cause, and how would you change the split?
Show answer
The random row-level split puts rows from the same customer in both training and evaluation sets, so the model partly recognizes customers instead of learning patterns that generalize. Split by customer, for example with GroupShuffleSplit or StratifiedGroupKFold using the customer ID as the group, so each customer appears in only one part. Then check that the groups do not overlap.
Exercise
You want a 70/15/15 train/validation/test split. What test_size do you use in each of the two train_test_split calls, if the first call splits off the test set?
Show answer
First call: test_size=0.15, which leaves 85% of the data. Second call: test_size=0.15 / 0.85, about 0.1765, because the validation set must be 15% of the original data, which is about 17.65% of the remaining 85%.