Reading history

Data Leakage in Machine Learning: How to Spot and Prevent It

7 min read 0 views

Learn what data leakage is, see how preprocessing before the split and leaky columns inflate scores in Python, and use pipelines and a checklist to prevent it.

Your model scores 95% in testing, then does badly on real data. One common cause is data leakage: during training, the model saw information it will not have when it makes real predictions. In this lesson you will cause leakage on purpose, measure how much it inflates the score, and learn the habits that stop it.

In this lesson you will learn

  • What data leakage is and why it gives scores that are too good
  • How preprocessing before the split leaks test data into training
  • What target leakage is and how to spot a leaky column
  • How pipelines keep each step inside the training folds
  • A short checklist to run before you trust any score

You should know train-test split, cross-validation and scikit-learn pipelines.

What Is Data Leakage?

A test set is meant to act like the future. The model must never see it while learning. Leakage happens when some piece of the test data, or of the answer itself, slips into training. The model then looks clever in testing, but that skill is fake. It vanishes on real data.

Think of a student who has seen the exam paper the night before. Their mark is high, but it says nothing about what they know. Leakage gives your model the exam paper.

Wrong order: the selector sees every rowAll 100 rowsPick 20 bestcolumns (all rows)Split into5 foldsScore: 0.91(fake)Right order: the selector sees training folds onlyAll 100 rowsSplit into5 foldsPick columns ontraining folds onlyScore: 0.47(honest)

There are two main kinds:

  • Train-test contamination: a step such as scaling, filling missing values or picking features learns from all rows, including the test rows.
  • Target leakage: a column holds information that only exists after the outcome is known.

Leakage From Preprocessing

To prove the problem, we make data with no pattern at all. There are 100 rows, 5,000 columns of random numbers, and random yes/no labels. An honest model can only guess, so its accuracy should be near 0.5. Then we pick the 20 columns that look most linked to the label, once before cross-validation and once inside it.

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

# 100 patients, 5,000 columns of pure random noise, random yes/no labels.
# No model can truly do better than a coin flip (about 0.5).
rng = np.random.default_rng(1)
X = rng.normal(size=(100, 5000))
y = rng.integers(0, 2, 100)

# WRONG: choose the 20 "best" columns using ALL rows, then cross-validate
X_picked = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_picked, y, cv=5).mean()
print(f"select first, then CV : {leaky:.2f}")

# RIGHT: selection happens inside each training fold only
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(f"selection inside CV   : {honest:.2f}")

Output

select first, then CV : 0.91
selection inside CV   : 0.47
  • The wrong order reports 91% accuracy on pure noise. With 5,000 random columns, some will match the labels by luck. Because the selector saw every row, it picked columns that happen to match the test rows too.
  • Inside a pipeline, the selector is fitted again on each training fold. It never sees the rows it is scored on, so the accuracy drops to 0.47, which is coin-flip level. This is the true answer.
  • The same trap applies to StandardScaler, imputers and encoders. The effect is usually smaller than here, but it always makes the score too hopeful.

Target Leakage

Target leakage is harder to see because the code looks fine. The problem is in the data. Below, we predict which mobile customers will cancel. One column, days_since_deactivation, is filled in only after a customer has already left.

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

# Customers of a mobile operator. Did they cancel (churn = 1)?
rng = np.random.default_rng(7)
n = 1000
df = pd.DataFrame({
    "months_active": rng.integers(1, 60, n),
    "monthly_bill": rng.normal(500, 150, n).round(),
    "support_calls": rng.poisson(2, n),
})
risk = 0.04 * df["support_calls"] - 0.01 * df["months_active"] + rng.normal(0, 0.3, n)
df["churn"] = (risk > 0).astype(int)
# Recorded AFTER a customer cancels: the date the SIM was deactivated.
# Customers who stayed have no deactivation, so this column is 0 for them.
df["days_since_deactivation"] = np.where(df["churn"] == 1, rng.integers(1, 30, n), 0)

def score(cols):
    X_tr, X_te, y_tr, y_te = train_test_split(df[cols], df["churn"], random_state=0)
    model = RandomForestClassifier(random_state=0).fit(X_tr, y_tr)
    return model.score(X_te, y_te), model

base = ["months_active", "monthly_bill", "support_calls"]
acc, _ = score(base)
print(f"honest features   : accuracy {acc:.3f}")
acc, model = score(base + ["days_since_deactivation"])
print(f"with leaky column : accuracy {acc:.3f}")
top = pd.Series(model.feature_importances_, model.feature_names_in_).idxmax()
print("most important column:", top)

Output

honest features   : accuracy 0.740
with leaky column : accuracy 1.000
most important column: days_since_deactivation
  • With honest columns the model reaches 74%. That is a fair estimate.
  • Adding the leaky column gives a perfect 100%. A perfect score on a real problem should make you suspicious, not happy.
  • Feature importance points straight at the culprit. When one column dominates, ask: “Would I know this value at the moment I need the prediction?” Here the answer is no, because a customer who is still with us has no deactivation date.

Where Leakage Hides

SourceExampleFix
Scaling or imputing before the splitMean of all rows used to fill gapsPut the step in a pipeline
Feature selection on all rowsPicking the “best” columns firstSelect inside the pipeline
Columns recorded after the outcomeRefund issued, discharge dateDrop them; check each column’s timing
Shuffling time seriesTraining on March to predict FebruarySplit by time
Same person in train and testSeveral scans of one patientUse GroupKFold
Duplicate rowsA copy of a test row sits in trainingRemove duplicates before splitting

For the time and group cases, see time series forecasting and cross-validation strategies.

Checklist before you trust a score

  • Is every step that learns from data inside the pipeline?
  • Was each column available at prediction time?
  • Is the score much higher than people get on similar problems?
  • Does one feature have most of the importance?

Common Mistakes

  1. Calling fit_transform on the full dataset. Split first, or better, use a pipeline so cross-validation refits each step.
  2. Tuning on the test set. If you try many settings and keep the best test score, the test set has become part of training. Tune with cross-validation and touch the test set once.
  3. Trusting a column because its name sounds harmless. Ask when and how each value was recorded.
  4. Celebrating a near-perfect score. Real problems are rarely that easy. Look for leakage first.

Practice Exercises

Exercise 1. In dl1.py, change k=20 to k=200. What happens to each score, and why?

Show answer

The honest score stays near 0.5, because there is still no real pattern. The leaky score rises to about 0.99. More hand-picked columns give the model more chance matches to memorise, and those matches include the test rows. The gap between the two numbers is the size of the leak.

Exercise 2. A hospital model predicts pneumonia. One column is “antibiotic given (yes/no)”. Is it safe to use?

Show answer

Probably not. Antibiotics are often given because doctors already suspect pneumonia, so the column carries the answer. If the model must predict before treatment starts, drop the column.

Frequently Asked Questions

Is it leakage to scale data before a train-test split?

Yes, a small one. The scaler’s mean and standard deviation include test rows. With large datasets the effect is usually tiny, but a pipeline removes it for free, so there is no reason to risk it.

How can I find target leakage in a new dataset?

Train a quick model and look at feature importance. A single column with very high importance, or a score that looks too good, is a warning sign. Then check with someone who knows when each column is recorded.

Summary

  • Leakage means the model saw information it will not have in real use.
  • Preprocessing on all rows leaks test data; pipelines fix it.
  • Target leakage comes from columns recorded after the outcome.
  • An unusually high score is a reason to look for leakage.

Next: Feature Engineering in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *