Train, Validation and Test Splits, and Data Leakage
A model's score only means something if it was measured on data the model and the person building it never used. Data are therefore split into a training set to fit the model, a validation set to make choices, and a test set used once at the end. Splits must respect the structure of the data: classes (stratification), groups such as patients or engines, and time. Data leakage is any way information from the evaluation data, or from the future, gets into training; it makes models look much better than they are. This page covers split design, sizes, and the main leakage types with ways to detect them. In the exercises you implement random, stratified, grouped and time-based splits and leak detectors; then you measure how much five classic leaks inflate reported accuracy.
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.
Don’t peek at the exam
If a student sees the exam questions while studying, a perfect score tells you nothing about what they learned. The same is true for models: we hide some data (the test set) and only check the model on it at the very end. Leakage is any sneaky way the model, or we, got a peek.
Fooling yourself with noise
select on all data, then CV80%select inside each fold48%truth (coin-flip labels)50%
60 examples, all features random. With many features, some correlate with the labels by pure chance; picking them using all rows lets the test folds choose the features, so cross-validation rewards a coincidence. Any step that looks at the labels (feature selection, target encoding, tuning) must happen inside the training part of each split.
Why engineers care
Leakage is the most common reason a model that scored 99% in development fails in the field. In fault detection, the same engine’s data on both sides of the split, or a “repair code” column filled in after the failure, can make a useless model look perfect.
📝 Quick check (Level 0)
0/3 answered
1. The test set is used…
2. In the demo, the true accuracy is…
3. Leakage makes models look…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.
Three sets, three jobs
Set
Used for
Typical share
training
fitting model parameters
60–80%
validation
choosing models, hyperparameters, thresholds, features
10–20% (or cross-validation, D0.4)
test
one final, unbiased estimate
10–20%
How to split:
random for i.i.d. rows;
stratified to keep class proportions, especially for rare classes;
grouped to keep all rows of a patient, engine, user or satellite on the same side;
time-based to train on the past and test on the future, often with a gap.
from sklearn.model_selection import train_test_split, GroupShuffleSplitX_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)tr, te = next(GroupShuffleSplit(test_size=0.2, random_state=0).split(X, y, groups=engine_id))
📝 Quick check (Level 1)
0/3 answered
1. With 2% positives, which split keeps the test set representative?
2. Several readings per patient call for…
3. Hyperparameters are chosen on…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.
Kinds of leakage
Preprocessing or selection leakage: scalers, imputers, feature selection or target encoding fitted on all data. Harmless for simple scaling, catastrophic for anything that looks at labels.
Group leakage: near-duplicate rows (same engine, same patient, augmented copies of one image) on both sides. The model memorises identities.
Temporal leakage: random splits of time series let the model interpolate between neighbours. Features computed with future data (centred rolling means, end-of-day totals) have the same effect.
Target leakage: a feature that is only known after the outcome, or is derived from it (repair cost, discharge code, “account closed date”).
Test reuse: checking the test score after every change slowly fits the test set.
Detection:
check for duplicates and group overlap across splits;
a single feature with AUC near 0 or 1 is suspicious;
performance that is too good to be true usually is;
validate on a later time period or on new groups.
🐍 Exercise 1: splits and leak detectors
Implement random three-way, stratified, grouped and time-based (with gap) splits; find test rows duplicated from training; compute single-feature AUC with tie handling and flag features whose AUC is suspiciously close to 0 or 1.
📝 Quick check (Level 2)
0/3 answered
1. A 'days_in_hospital' feature for predicting admission is…
2. A centred 7-day rolling mean as a feature leaks because…
3. A single feature with AUC 0.99 should be…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.
Designing evaluation like an adversary
Mirror deployment: the split should reproduce what is new at prediction time, such as new customers, new engines, next month or a new site.
Sizes: the test set must be large enough that its uncertainty is small compared with the differences you care about. For accuracy p on n test rows, the standard error is √(p(1−p)/n), so n = 1000 gives about ±1.4%.
Freeze the test set, record its hash, and report it once. Use a fresh holdout for each new major decision when you can.
Distribution shift: if the test period differs from the training period, report both in-distribution and shifted results.
Interview questions.
How would you split data from 50 hospitals? Group by hospital, or hold out whole hospitals to measure generalisation to new sites.
Why can a random split overestimate performance on time series? Autocorrelation makes test points near-copies of training points.
📝 Quick check (Level 3)
0/3 answered
1. Standard error of 90% accuracy on 400 test rows?
2. A model will be deployed to new factories. Split by…
3. Repeatedly checking the test score while tuning leads to…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.
How much do leaks inflate the score?
Exercise 1. Stratified splitting of 90 negatives and 10 positives puts exactly 2 positives in a 20% test set. The grouped split shares no group between its sides. The time split with a gap trains on times 1–6 and tests on 8–10. A feature equal to the label plus tiny noise is flagged with AUC ≈ 1, while a genuinely informative feature (AUC ≈ 0.6) is not.
Exercise 2: five leaks, measured (mean of 10 runs). Columns are:
the leaky estimate;
an honest estimate made the right way;
the true accuracy of the leaky pipeline on genuinely new data.
Leak
Leaky estimate
Honest estimate
True accuracy
select 20 of 2 000 noise features on all 100 rows, then 5-fold CV
0.83
0.48
0.50
random row split, 40 engines × 25 rows, 1-NN
1.00
0.50 (grouped CV)
0.49
shuffled split of a regime-switching time series, 1-NN
0.92
0.54 (chronological)
0.52
repair cost (known only after failure) as a feature
0.95
0.74 (feature removed)
0.50
scaler fitted on train + validation
0.75
0.75
0.77
The leaks that matter are the ones that let the model see the labels or the identity of the test examples:
Selecting features on all the data turns pure noise into an apparently 83% accurate model.
Engine signatures and temporal neighbours give near-perfect scores to models that are no better than chance on new engines or future periods.
The target-leaking model reports 0.95, yet deployed, when repair cost is not yet known, it does no better than a coin. Removing the feature gives an honest 0.74.
Fitting a scaler on all the data changed nothing here.
🐍 Exercise 2 (research): how much does leakage inflate accuracy?
Simulate five leaks: feature selection before cross-validation on noise, random splits of grouped engine data, shuffled splits of a time series, a post-outcome target-leaking feature, and a scaler fitted on all data; compare the leaky estimate, an honest estimate and the true accuracy on new data, averaged over 10 runs.
Leakage in AI, robotics and aerospace
Predictive maintenance: split by engine or vehicle, never by row; leave a gap before the failure horizon.
Robot learning: hold out whole environments or objects, not frames from the same episodes.
Earth observation: spatial autocorrelation means neighbouring tiles leak; use spatial block splits.
Medical AI: patient-level splits; a 2019 review found many published models leaked through image-level splits.
References
S. Kaufman, S. Rosset, C. Perlich, O. Stitelman (2012). “Leakage in data mining: formulation, detection, and avoidance.” ACM TKDD 6(4).
C. Ambroise, G. McLachlan (2002). “Selection bias in gene extraction on the basis of microarray gene-expression data.” PNAS 99(10).
S. Kapoor, A. Narayanan (2023). “Leakage and the reproducibility crisis in machine-learning-based science.” Patterns 4(9).
D. R. Roberts et al. (2017). “Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure.” Ecography 40(8).
C. Dwork et al. (2015). “The reusable holdout: preserving validity in adaptive data analysis.” Science 349(6248).
The average loss on a set of examples that played no role in fitting or selecting the model; it is an unbiased estimate of the risk if test examples are drawn from the deployment distribution.
If m features are each pure noise, the largest absolute sample correlation with the labels grows like √(2 log m / n); selecting it on the same data used for evaluation therefore yields a positively biased estimate whose bias grows with m.
The test set should be new in the same way that deployment data will be new: new rows, new groups, or the future.
Practice
Show:
Level 0
Problem 1Level 0
Which set is used only once, at the end?
The test set.
Problem 2Level 0
Which set is used to choose hyperparameters?
The validation set.
Problem 3Level 0
Name for information from the test data getting into training?
Leakage.
Level 1
Problem 4Level 1
Positives in a stratified 20% test set from 10 positives?
2.
Problem 5Level 1
AUC of scores (0.1, 0.4, 0.35, 0.8) for labels (0, 0, 1, 1)?
0.75.
Problem 6Level 1
Split type for several rows per patient?
A group split.
Problem 7Level 1
Standard error of 90% accuracy measured on 400 examples?
√(0.9·0.1/400) = 0.015.
Level 2
Problem 8Level 2
Leak type of a feature known only after the outcome?
Target leakage.
Problem 9Level 2
Leaky CV accuracy after selecting noise features on all data in exercise 2?
≈ 0.83.
Problem 10Level 2
True accuracy of any classifier on coin-flip labels?
0.5.
Problem 11Level 2
Test rows needed for SE ≈ 1.6% at 50% accuracy?
√(0.25/n) = 0.016 → n ≈ 1000.
Problem 12Level 2
Groups shared between train and test in a correct group split?
0.
Problem 13Level 2
AUC of a constant feature?
0.5: all ties.
Level 3
Problem 14Level 3
Explain why a random split of engine data gives near-perfect 1-NN accuracy.
Each engine has a distinctive signature, so every test row has a training row from the same engine as its nearest neighbour, and that row carries the engine’s label; the model identifies the engine rather than recognising health, which fails on new engines. ∎
Problem 15Level 3
Explain why fitting a scaler on all data is usually harmless but target encoding is not.
A scaler uses only feature means and variances, which differ little between subsets and carry no label information; target encoding uses the test labels themselves to build a feature, directly injecting the answers. ∎
Problem 16Level 3
Design a split for forecasting satellite battery degradation.
Train on earlier periods and test on later ones (with a gap at least the prediction horizon), and also hold out whole satellites to check generalisation to new spacecraft; fit all preprocessing on training data only. ∎
Problem 17Level 3
Explain how repeatedly using the test set causes overfitting.
Each decision based on the test score selects models that happen to do well on those particular examples; over many decisions, the chosen model is tuned to the test set’s noise, so its score overestimates performance on new data. ∎
Level 4
Problem 18Level 4
Leaky estimate with the target-leaking repair-cost feature?
≈ 0.95.
Problem 19Level 4
Leaky accuracy from shuffling the time series?
≈ 0.92.
Problem 20Level 4
Honest accuracy after removing the leaking feature?
≈ 0.74.
Coding practice
🐍 Code 1 (Level 1): stratified test set
Same class ratio.
🐍 Code 2 (Level 1): group overlap
Groups on both sides.
🐍 Code 3 (Level 1): time split
Past for training, future for testing.
🐍 Code 4 (Level 2): AUC
Pairwise ranking probability.
🐍 Code 5 (Level 1): duplicates across splits
Exact copies.
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Train, Validation and Test Splits, and Data Leakage: topic test
10 questions, drawn at random from a bank of 16. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.