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.

Not startedJump to quiz

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

#LeakWhat goes wrongFix
1Test set reused for selectionPicking the model with the best test scoreSelect with validation data or CV; test once
2Preprocessing before splittingScaling/imputation statistics computed on all dataSplit first; fit preprocessing on training data only
3Feature selection before CVFeatures chosen using every row's labelSelect features inside each training fold
4Related records across splitsSame patient or customer in train and testGroup-based splitting
5Time leakageThe future influences predictions about the pastChronological split; forward-chaining validation
6Target leakageA feature reveals the outcome, or exists only after itUse 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.

PatientG1G2G3Label y
P11101
P21011
P30111
P40010
P50000
P6 (held out)1010
  • 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.

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

JFMAMJJASOND
Wrong: random
Right: by time
TrainingTest
Random splitting of daily stock prices lets the model learn from November when "predicting" February.

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:

JanFebMarAprMayJunJul
Round 1
Round 2
Round 3
Round 4
Training windowValidate on the next month

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?"

  1. Identify the problem: "Mean and SD are computed on the entire dataset before splitting."
  2. Name the leak: "Test-set information has influenced preprocessing."
  3. Explain the consequence: "The evaluation is over-optimistic."
  4. 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

ScenarioVerdict
Impute missing blood-test values with the whole dataset's median, then split 80/20Leak 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 CVLeak 3. Select inside each fold.
Weekly sales for 3 years, random 80/20 split, to forecast next quarterLeak 5. Split chronologically.
Standardise on training only, choose among 12 models by CV on training, test onceNo leak.
Three photos per patient, photos split randomlyLeak 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:

TypeMain problem
Model-selection leakageTest results influence model selection
Preprocessing leakageValidation/test information influences preprocessing
Feature-selection leakageValidation labels influence feature selection
Target leakageFuture information reveals the target
Duplicate leakageRelated records appear across datasets
Temporal leakageFuture 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

1 Test reuse · 2 Preprocess before split · 3 Feature selection before CV · 4 Related records across splits · 5 Time leakage · 6 Target leakage.

Six golden rules

Split before preprocessing. Never tune on test. Select features inside folds. Keep related rows together. Respect time order. Use only prediction-time features.

One test for every leak

Did anything from held-out data, the future, or the outcome influence a calculation or decision before the final score? If yes → leak.

Standardisation

with from the training set only, reused for validation and test.

"Is this approach reasonable?"

1) Identify the problem. 2) Name the leak. 3) Explain the consequence (optimistic estimate). 4) Recommend the fix.

See every cheatsheet by category →

Check your understanding

Score 75% or more to master this lesson and earn XP. Answer first, then check.

Q1diagnoseA team fills missing blood-test values with the median of the whole dataset, then splits it 80/20. Which leak is this?
Q2diagnoseTo predict whether a customer will cancel next month, a model uses "number of calls to the cancellation hotline this month". Which leak is this?
Q3calculateTraining statistics for house size are and sq ft. What is the standardised value of a 1,800 sq ft house in the test set?
Q4diagnoseA team standardises using training data only, picks the best of 12 models by 5-fold CV on the training set, and evaluates the winner once on the test set. Verdict?
Q5diagnoseA dermatology dataset has three photos per patient. The photos are split at random into training and test sets. What's the fix?
Q6diagnoseFrom 20,000 candidate genes, a team keeps the 50 most correlated with the label using all rows, then reports 5-fold CV accuracy. What's wrong?