Stop 06 · Data Preparation & Feature EngineeringTopics · 9/10

Data Leakage

Part of the Machine Learning Roadmap

In short

Your model scores 98% in the notebook and falls apart in production. Nine times out of ten the cause is data leakage: the model saw information during training that it will never have in real life.

Data leakage happens when information that would not be available at prediction time sneaks into training, like a future value or a statistic computed on the test set. It produces great validation scores and then a model that fails in the real world.

The jaadu peeks at a sealed exam envelope with a corner torn open in an empty classroom, papers slipping out of the gap.

Think of it like this

The leaked board exam paper

If the board exam paper leaks a day early, a student who memorises the answers scores 98%. Then in the next exam, without a leak, the same student fails. A leaky model is that student. Its high validation score came from seeing the answers, not from learning the subject.

Watch it happen

Two kinds of leakage

Target leakage

  • A feature secretly contains the answer.
  • Example: 'refund_issued' used to predict whether an order will be returned.
  • Example: 'days_overdue' used to predict loan default at application time.

Train-test contamination

  • Test data influences training steps.
  • Example: scaling or imputing with means from the full dataset before splitting.
  • Example: random split on time series, so the model trains on the future.

Ask of every feature and every preprocessing step: would I really have this, computed this way, at the moment I make a prediction?

The big ideas

What you need to know

Think in prediction time

Only use information that exists before the moment of prediction. Anything recorded after is off limits.

Split before you preprocess

Fit scalers, imputers, encoders and feature selectors on training data only. Pipelines make this automatic.

Respect time order

For data over time, train on the past and validate on the future with TimeSeriesSplit, not a random shuffle.

Keep groups together

If one customer has many rows, put all of them in train or all in test using GroupKFold.

See it in code

Walk through the code

python
1import numpy as np2from sklearn.feature_selection import SelectKBest, f_classif3from sklearn.linear_model import LogisticRegression4from sklearn.model_selection import cross_val_score5from sklearn.pipeline import make_pipeline6 7rng = np.random.default_rng(0)8X = rng.normal(size=(100, 5000))     # pure noise features9y = rng.integers(0, 2, size=100)     # random labels10 11# WRONG: choose features using every row, then cross-validate12X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)13leaky = cross_val_score(LogisticRegression(), X_sel, y, cv=5).mean()14 15# RIGHT: selection is refit inside each training fold16pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())17honest = cross_val_score(pipe, X, y, cv=5).mean()18 19print(round(leaky, 2), round(honest, 2))   # leaky is far above 0.5, honest is near 0.5

1/45,000 columns of random noise and random labels. There is nothing real to learn.

The labels are random, so no model can truly beat a coin flip. Leakage makes it look like one does.

Save yourself the pain

Common mistakes

Oops

Calling StandardScaler().fit_transform(X) on the whole dataset before train_test_split.

Do this instead

Split first, or put the scaler in a Pipeline so cross-validation fits it on training folds only.

Oops

Celebrating a score that is far better than anyone else has reported.

Do this instead

Treat a surprisingly high score as a bug report. Check feature importances for a column that gives away the answer.

Oops

Randomly shuffling sales data before splitting.

Do this instead

Use a time-based split so the model never trains on days after the ones it is tested on.

Your mission

Leak hunt

~25 min

Quick check

You predict whether a patient will be admitted to hospital. Which feature is most likely leakage?

Go deeper

  1. 1Check every feature and ask 'would I know this at the moment of prediction?'
  2. 2Fit scalers, imputers and encoders on training data only, ideally inside a Pipeline.
  3. 3Be suspicious of any validation score that looks too good to be true.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge