Sub topic 4
Train, validation, and test splits
Prerequisites and scope
This chapter assumes you can train a scikit-learn model, call predict, and explain overfitting. It covers why tuning needs three disjoint sets of data, how to build them, and the mistakes that make scores look better than they are. Cross-validation, which reuses the validation idea more efficiently, comes in the next chapter.
Why one split is not enough
A model fitted on some data will usually score well on that same data. The score tells you about memory, not about how the model handles new cases. So you hold out data that the model never trains on.
Tuning adds a second problem. Suppose you try 50 settings and keep the one with the best held-out score. That score is now biased upward. You picked the winner because it scored well on that data, and part of the win is luck. If you report the same number as your final estimate, you have used the held-out data twice: once to choose and once to judge.
The fix is to split the data into three roles:
| Set | Used to | Used how often |
|---|---|---|
| Training | Fit model parameters | Every trial |
| Validation | Compare hyperparameter settings and pick one | Every trial |
| Test | Estimate final performance | Once, at the end |
The test set stands in for future data. Once you look at it to make a decision, it stops being a fair stand-in.
Building the splits in scikit-learn
train_test_split makes two pieces. Call it twice to get three. Split off the test set first, so nothing you do later 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)
# Step 1: lock away the test set (20% of all data).
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
# Step 2: split the rest into train and validation.
# 0.25 of the remaining 80% is 20% of the total.
X_train, X_val, y_train, y_val = train_test_split(
X_dev, y_dev, test_size=0.25, random_state=0, stratify=y_dev
)
print(len(X_train), len(X_val), len(X_test))This gives a 60/20/20 split: 341, 114, and 114 rows. Note that test_size=0.25 in the second call is a fraction of the development data, not of the original data. This is a common arithmetic slip.
Now compare two settings using only the validation set:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
best_score, best_C = -1.0, None
for C in [0.01, 0.1, 1, 10, 100]:
model = make_pipeline(StandardScaler(), SVC(C=C))
model.fit(X_train, y_train)
score = model.score(X_val, y_val)
print(f"C={C:<6} validation accuracy={score:.3f}")
if score > best_score:
best_score, best_C = score, C
final = make_pipeline(StandardScaler(), SVC(C=best_C))
final.fit(X_dev, y_dev) # refit on train + validation
print("Test accuracy:", final.score(X_test, y_test)) # looked at onceThree details matter here:
- The scaler sits inside the pipeline, so it learns its mean and standard deviation from the training rows only. Fitting it on all data first would leak information from the validation and test rows.
- After choosing
best_C, the final model is refit on the training and validation data together. More data usually helps, and the chosen setting is kept fixed. - The test score is computed once, after all choices are made.
Choosing split sizes
There is no universal ratio. The right sizes depend on how much data you have and how noisy the metric is.
- Small datasets (hundreds of rows): a single validation split is noisy. A difference of one or two rows can change which setting wins. Prefer cross-validation, covered next.
- Medium datasets (thousands to tens of thousands): 60/20/20 or 70/15/15 works well.
- Very large datasets (millions): the test and validation sets can be a small percentage, such as 1 to 2 percent, because even that is thousands of examples.
A useful check is the standard error of an accuracy estimate. For accuracy near 0.9 on n examples, it is roughly the square root of 0.9 × 0.1 / n. With 100 validation rows that is about 0.03, so two settings that differ by 0.01 cannot be told apart. With 10,000 rows it is about 0.003.
Stratification
With stratify=y, each piece keeps about the same class proportions as the full data. Without it, a rare class can end up missing or underrepresented in the validation set by chance. This matters most for imbalanced classification. For regression, you can stratify on binned values of the target, though many people skip this.
Splits that respect the data's structure
Random splitting assumes rows are independent. When they are not, random splits leak information and give scores that are too high.
| Data situation | Problem with a random split | Better approach |
|---|---|---|
| Time series or any forecasting task | Training on the future, testing on the past | Split by time: train on earlier data, validate and test on later data |
| Several rows per patient, user, or device | Same entity appears in both train and validation, so the model recognizes the entity | `GroupShuffleSplit` or `GroupKFold` with a group id |
| Duplicate or near-duplicate rows | Copies land on both sides | Remove duplicates before splitting |
| Data from different sources or years | Model sees the same source in validation | Hold out whole sources or periods |
Here is a group-aware split:
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
rng = np.random.default_rng(0)
X = rng.normal(size=(1000, 5))
y = rng.integers(0, 2, size=1000)
groups = rng.integers(0, 100, size=1000) # 100 patients, about 10 rows each
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
train_idx, test_idx = next(splitter.split(X, y, groups=groups))
# No patient appears on both sides.
print(set(groups[train_idx]) & set(groups[test_idx]))The printed set is empty, which is the property you want.
Common errors
- Preprocessing before splitting. Scaling, imputing, selecting features, or target-encoding on the full dataset lets validation and test statistics shape the training step. Put these steps in a
Pipelineand fit the pipeline on training data only. - Tuning on the test set. Any decision made after seeing test results counts as tuning, including picking between two model families.
- Forgetting the seed. Without
random_state, the split changes on each run and results cannot be reproduced. Record the seed. - Looking at the validation score as a final result. The best validation score is biased upward from selection. Report the test score instead.
- Class imbalance without stratification. Validation scores can swing widely because of how few minority examples land in each piece.
- Changing the split between trials. Every setting must be compared on the same validation data, or differences reflect the split and not the setting.
How this connects to what follows
A single hold-out validation set is simple and fast, and it works when data is plentiful. When data is scarce, it wastes rows and gives noisy comparisons. Cross-validation addresses this by rotating which rows serve as validation. Grid and random search then wrap that procedure around many settings. The test set stays locked away through all of it.
Exercise
You have 10,000 labeled rows. You want 70% train, 15% validation, 15% test using two calls to traintestsplit. What test_size should you pass to each call, and which call comes first?
Show answer
First call: testsize=0.15, which locks away the test set and leaves 8,500 development rows. Second call, on those 8,500 rows: testsize=0.15/0.85, about 0.1765, which gives about 1,500 validation rows and 7,000 training rows. The key point is that the second fraction is relative to the development data, not to the original 10,000.
Exercise
A colleague scales all features with StandardScaler on the full dataset, then splits into train and validation, tunes, and reports the validation score. Name two problems with this workflow.
Show answer
First, the scaler's mean and standard deviation were computed using validation rows, which is leakage. It should be fit on training rows only, ideally inside a pipeline. Second, the reported validation score was also used to choose the setting, so it is optimistically biased. A separate test set, scored once, should be used for the final number.
Exercise
Your dataset has 5 rows per customer from 2,000 customers, and you want to predict churn. Why is traintestsplit a poor choice, and what should you use?
Show answer
A random row split puts rows from the same customer in both train and validation. The model can learn customer-specific patterns and appear to generalize when it does not. Use a group-aware splitter such as GroupShuffleSplit (or GroupKFold for cross-validation) with the customer id as the group, so each customer is entirely on one side.