Lesson 2.8 · 14 min read · about 1 h 30 min to master at a very slow pace
Data Leakage and Good ML Practices
The six common ways information leaks into model evaluation: test-set reuse, preprocessing before splitting, feature selection before CV, related records across splits, time leakage and target leakage. Each with a scenario, why it is wrong and the fix.
The one principle
A model may only learn from information that would genuinely be available when it makes real predictions. Anything else makes measured performance look better than real performance.
Data leakage is when information that shouldn't be available during model development or prediction influences the model-building process. The model isn't necessarily trained on test rows. The leak can be a statistic, a choice or a feature.
The six leaks at a glance
| # | Leak | What goes wrong | Fix |
|---|---|---|---|
| 1 | Test set reused for selection | Picking the model with the best test score | Select with validation data or CV; test once |
| 2 | Preprocessing before splitting | Scaling/imputation statistics computed on all data | Split first; fit preprocessing on training data only |
| 3 | Feature selection before CV | Features chosen using every row's label | Select features inside each training fold |
| 4 | Related records across splits | Same patient or customer in train and test | Group-based splitting |
| 5 | Time leakage | The future influences predictions about the past | Chronological split; forward-chaining validation |
| 6 | Target leakage | A feature reveals the outcome, or exists only after it | Use only features available at prediction time |
Leak 1: reusing the test set for model selection
Covered in lesson 2.6: trying 40 models and keeping the best test score makes the reported score optimistic, because the selection adapted to that test set. Takeaway: the test set must stay independent of every development decision.
Leak 2: preprocessing before splitting
Preprocessing turns raw data into model-ready form: standardisation, normalisation, missing-value imputation, category encoding, PCA. The leak appears when its parameters (means, medians, category lists, components) are learned from the whole dataset before splitting.
Why standardise at all?
Features on very different scales (house size in sq ft, number of bedrooms) can distort distance-based methods and penalised models. Standardisation puts each feature on a comparable scale:
(the mean) is the centre of the distribution; (the standard deviation) measures how spread out values are. Two neighbourhoods can have the same average house size, 1,500 sq ft, but in one every house is 1,400–1,600 (small ) while the other ranges from 600 to 3,000 (large ). A of +1 means "one typical spread above average".
Scenario: house prices
1,000 houses. Wrong: compute , on all 1,000, then split. The validation and test rows have shaped and .
Right: split first (700 / 150 / 150). Compute the statistics from the 700 training rows only, say , . Apply those same numbers to training, validation and test. Don't recompute statistics on the validation or test sets.
Why not separate statistics for the test set?
Take a 1,800 sq ft house. With the training statistics: . If the test set were standardised with its own statistics, say , : .
The same house now looks below average instead of above. The model learned what means on the training scale; changing the ruler for the test set breaks that, and it hides genuine differences between the test and training distributions.
The same applies to imputing missing values with a mean or median, min–max scaling, PCA and learning category mappings: fit on training data, apply everywhere.
Leak 3: feature selection before cross-validation
Scenario: cancer from gene measurements
200 patients, 100 gene measurements, outcome cancer (1) or not (0). The data scientist uses all 200 patients to find the 20 genes most associated with cancer, keeps those, then runs 10-fold CV and reports 3% error.
Why it's wrong: the labels of patients who later sit in validation folds already helped choose the genes. With many candidate features, some genes correlate with the label purely by chance; picking them using all labels produces artificially strong CV results. Even if every gene were pure noise, this procedure could report a low error.
Right: for every fold, take the 9 training folds, select the 20 best genes using only those, train, and evaluate on the held-out fold. Each round may pick different genes. In practice use a pipeline that does selection and training together inside each fold.
A tiny version you can check by hand
Six patients, three genes; we keep the single gene that agrees with the label most often. Patient P6 is the held-out validation patient.
| Patient | G1 | G2 | G3 | Label y |
|---|---|---|---|---|
| P1 | 1 | 1 | 0 | 1 |
| P2 | 1 | 0 | 1 | 1 |
| P3 | 0 | 1 | 1 | 1 |
| P4 | 0 | 0 | 1 | 0 |
| P5 | 0 | 0 | 0 | 0 |
| P6 (held out) | 1 | 0 | 1 | 0 |
- Correct (P1–P5 only): G1 agrees 4/5, G2 agrees 4/5, G3 agrees 3/5. Tie; the rule takes the first, G1. G1 predicts P6 = 1, which is wrong.
- Wrong (all six): G1 4/6, G2 5/6, G3 3/6. G2 wins and predicts P6 = 0, which is right.
The wrong approach "did better", but only because P6's own label broke the tie in G2's favour. The validation result was decided by the answer it was supposed to be predicting. Across many folds and genes, that inflates the score.
Leak 4: related observations across splits
100 patients each have 5 blood-test records (500 rows). Splitting the rows at random puts records of the same patient in both training and test. Patients have individual patterns (their typical blood pressure, history), so the model can learn who the patient is rather than a general medical pattern, and score unusually well on another record of someone it has already seen. On completely new patients it does worse.
Fix: split by patient ID so all of a patient's records stay together (group split; in scikit-learn, GroupKFold and GroupShuffleSplit). The same applies to many transactions per customer, purchases per shopper, or measurements per machine.
Leak 5: time leakage
Evaluated on 10 February, a randomly-split model has already trained on November and December data, which wouldn't exist yet in a real forecast. Fix: split chronologically, and validate with forward chaining, always predicting the period just after the training window:
Leak 6: target leakage
A feature directly or indirectly reveals the outcome, often because it only becomes known after the event being predicted. The model looks superb in testing and is useless in real use.
Scenario: loan defaults with 99% accuracy
Features: age, salary, credit score, loan amount, employment status, and collections status (whether the loan was sent to debt collection). Follow the timeline: (1) customer applies; (2) bank records salary, age, credit score; (3) bank wants to predict default; (4) customer defaults; (5) loan goes to collections. Collections status only exists after step 4, but the prediction must be made at step 3. Drop it.
Similarly, when predicting 30-day hospital readmission, age, history and blood pressure at discharge are fine; a feature recording "readmitted within 30 days" is the outcome itself.
Answering "is this approach reasonable?"
- Identify the problem: "Mean and SD are computed on the entire dataset before splitting."
- Name the leak: "Test-set information has influenced preprocessing."
- Explain the consequence: "The evaluation is over-optimistic."
- Recommend the fix: "Split first, fit preprocessing on training data only, apply the fitted transformation to validation and test."
One test for every leak
Ask: did anything from the held-out data, from the future, or from the outcome influence a calculation or a decision before the final score? If yes, there is leakage.
Spot the leak: practice
| Scenario | Verdict |
|---|---|
| Impute missing blood-test values with the whole dataset's median, then split 80/20 | Leak 2. Compute the median on training data only. |
| Predicting "will cancel next month" using "calls to the cancellation hotline this month" | Leak 6. A consequence of the intent to cancel; not available in time. |
| Keep the 50 features most correlated with the label (all rows), then report 5-fold CV | Leak 3. Select inside each fold. |
| Weekly sales for 3 years, random 80/20 split, to forecast next quarter | Leak 5. Split chronologically. |
| Standardise on training only, choose among 12 models by CV on training, test once | No leak. |
| Three photos per patient, photos split randomly | Leak 4. Split by patient. |
Stuck? Common doubts
Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.
First passWhy is repeatedly checking test scores and choosing the best model a form of leakage?
Because the test set influenced a decision. Even though no model trained on test rows, the choice of model adapted to that particular test set, and the winner partly won by chance. Its test score is therefore optimistic. Select on validation data or CV and use the test set once at the end.
First passWhy is calculating the mean and standard deviation on the entire dataset a problem?
Those statistics then include the validation and test rows, so information about the held-out distribution enters the pipeline before evaluation. Split first, compute the statistics on the training set only, and reuse them to transform validation and test data.
First passWhy does selecting features using the full dataset leak into the validation folds?
Choosing features "most associated with the label" uses every row's label, including rows that later serve as validation. So the validation labels helped decide which features the model uses, and the CV score is inflated, especially when there are many candidate features that correlate with the label by chance.
First passWhy must all records of the same patient or customer stay in the same split?
Records of one person are similar to each other. If they appear in both training and test, the model can recognise the person instead of learning a general pattern, which inflates the test score. Real deployment involves new people, so split by person (group split).
First passWhy can randomly splitting time-series data give unrealistic results?
A random split lets the model train on later dates and be tested on earlier ones, i.e. learn from the future. In real forecasting the future isn't available. Use a chronological split and forward-chaining validation.
First passWhy can't we use features that become available after the prediction time?
At the moment the real prediction is made, those features don't exist yet. A model that relies on them looks excellent in testing (they effectively reveal the answer) and fails in practice. Use only information available at the intended prediction time.
Going deeperIf we follow the train–validation–test workflow correctly, is all leakage eliminated?
No. The workflow prevents test-set reuse, but leakage has several forms:
| Type | Main problem |
|---|---|
| Model-selection leakage | Test results influence model selection |
| Preprocessing leakage | Validation/test information influences preprocessing |
| Feature-selection leakage | Validation labels influence feature selection |
| Target leakage | Future information reveals the target |
| Duplicate leakage | Related records appear across datasets |
| Temporal leakage | Future information influences past predictions |
A correct split is necessary, not sufficient.
Going deeperShould training, validation and test sets each get their own mean and standard deviation?
No. Calculate the mean and SD on the training data only, and reuse those exact values for validation and test. Recomputing them per set changes the reference scale: the same 1,800 sq ft house would be with training statistics but with test statistics, and genuine differences between the sets get hidden.
Going deeperWith correct feature selection, do we still use all 100 genes in the validation fold?
All 100 measurements are available, but the selection uses only the training fold: pick the best 20 genes from the training fold, then use those same 20 genes for that fold's validation data. Validation labels never influence which genes are chosen.
Going deeperIf both approaches end up picking the same genes, how does it matter whether selection happens before or after CV?
Sometimes they do pick the same genes, and then the scores coincide. The problem is the cases where they don't: in the six-patient example, the held-out patient's label was the only reason G2 beat G1. The wrong approach can even produce a better individual prediction, but that doesn't make the method valid. The goal of evaluation is a trustworthy performance estimate, not making each prediction right by peeking.
Going deeperIn loan-default prediction, is the problem that a new customer has never taken a loan, so we can't predict their default?
That's a different problem, usually called limited or thin credit history. Target leakage is about using information that only becomes available after the prediction point. Collections status is known too late to predict default at application time. The model must use only information available when the prediction is made.
Cheatsheet
The six leaks
Six golden rules
One test for every leak
Standardisation
"Is this approach reasonable?"
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.