Foundations to Frontier
Tests
D. Classical Machine Learning › D0 Core Concepts (concept pages)

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.

Level 0: Foundation

★☆☆☆☆ 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 CV
80%select inside each fold
48%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. 1. The test set is used…
  2. 2. In the demo, the true accuracy is…
  3. 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, GroupShuffleSplit
X_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. 1. With 2% positives, which split keeps the test set representative?
  2. 2. Several readings per patient call for…
  3. 3. Hyperparameters are chosen on…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Kinds of leakage

  1. 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.
  2. Group leakage: near-duplicate rows (same engine, same patient, augmented copies of one image) on both sides. The model memorises identities.
  3. 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.
  4. Target leakage: a feature that is only known after the outcome, or is derived from it (repair cost, discharge code, “account closed date”).
  5. 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. 1. A 'days_in_hospital' feature for predicting admission is…
  2. 2. A centred 7-day rolling mean as a feature leaks because…
  3. 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. 1. Standard error of 90% accuracy on 400 test rows?
  2. 2. A model will be deployed to new factories. Split by…
  3. 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

  1. S. Kaufman, S. Rosset, C. Perlich, O. Stitelman (2012). “Leakage in data mining: formulation, detection, and avoidance.” ACM TKDD 6(4).
  2. C. Ambroise, G. McLachlan (2002). “Selection bias in gene extraction on the basis of microarray gene-expression data.” PNAS 99(10).
  3. S. Kapoor, A. Narayanan (2023). “Leakage and the reproducibility crisis in machine-learning-based science.” Patterns 4(9).
  4. D. R. Roberts et al. (2017). “Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure.” Ecography 40(8).
  5. C. Dwork et al. (2015). “The reusable holdout: preserving validity in adaptive data analysis.” Science 349(6248).