Home/ Machine Learning/ Data Leakage in Machine Learning: Detect It, Fix It, Prove It
Machine Learning

Data Leakage in Machine Learning: Detect It, Fix It, Prove It

Data leakage inflates your model’s score until it fails in production. Measure the damage on real data, find the six common leaks, and fix them with scikit-learn pipelines.

Your churn model scores 0.98. The notebook runs clean, the chart looks excellent, and the model collapses the first week it meets real customers. That gap is the signature of data leakage: the model was allowed to learn from information that will not exist at the moment it has to make a prediction.

The term is overloaded, so pin it down first. In security, “data leakage” means data escaping an organisation. Here it means something narrower and more mechanical: a feature, or a preprocessing step, that carries information from the test set or from the future into training. The model is not cheating on purpose. Nothing crashes. The score is simply wrong.

This guide uses the real IBM Telco Customer Churn dataset, so every number is reproducible. You will see a baseline of 0.84 AUC jump to 0.98 with one column, watch two subtler leaks inflate a score, and then build the pipeline pattern that makes all of them impossible.

Setup: the data and the script

The dataset has 7,043 customers and 21 columns: contract type, tenure, monthly charges, support services, and whether the customer churned. It is a good teaching set because it is genuinely mixed — numeric and categorical columns, 11 blank values in TotalCharges, and a churn rate of 26.5%. A plain logistic regression reaches about 0.84 AUC on it, which is a believable ceiling. Anything much higher is a signal, not a triumph.

Download it and install the two libraries:

curl -O https://raw.githubusercontent.com/IBM/telco-customer-churn-on-icp4d/master/data/Telco-Customer-Churn.csv
pip install pandas scikit-learn

If curl is not available, the same file is on Kaggle as *Telco Customer Churn*. Every experiment below is in the downloadable script, which fetches the CSV itself and reproduces every score in this article:

  • Download: data-leakage-demo.zip — unzip it, then run python data-leakage-demo.py (tested with Python 3.14, pandas 3.0.5, scikit-learn 1.9.0)

The CSV is IBM’s public sample dataset; check the repository’s licence before redistributing it.

What data leakage actually is

Supervised learning assumes a clean boundary: the model learns from the training rows and is judged on rows it has never seen. Leakage breaks that boundary in one of two directions. Either a column contains information that is only available *after* the outcome, or a preprocessing step was fitted on data that includes the test rows.

Think of a student who has seen the answer key. Their exam score is not a slightly optimistic estimate of their ability — it measures nothing. That distinction matters: overfitting produces a score that is too high but still related to performance; leakage produces a score that is unrelated to it. A leaky model can be confidently wrong in production, because the feature it leaned on does not exist there.

Leakage is also quiet. It produces no exception, no warning, and often a better-looking report. That is why it survives code review and ships.

It enters a project at one of three points. During data collection, a field records something that happens after the label. During preprocessing, a transformer learns from rows it will later be judged on. During splitting, rows that belong together — the same customer, the same day, the same machine — land on both sides. Naming the entry point usually names the fix.

The six leaks you will actually hit

These are ordered by how often they appear in real code reviews, not by how exotic they sound. Each one is invisible in a metric and obvious once you know where to look.

Target leakage

A column is created after the outcome. In a churn project, cancellation_reason, refund_issued, or a retention_offer recorded by the retention team are all post-outcome fields: they only exist because the customer already left.

The test is a question, not a statistic: when was this value written? If the answer is “after the thing we are predicting”, the column cannot be a feature.

Train–test contamination

The scaler, imputer, encoder or PCA was fitted on the full dataset before splitting. StandardScaler then learns a mean that includes the test rows, and every validation score is slightly dishonest.

On 7,000 rows the effect is small, which is exactly why the habit survives. On 200 rows with many features it is not small, and it is never correct.

Feature-selection leakage

You rank features by correlation with the target, keep the top ten, then cross-validate. The ranking used every label, including the labels in each validation fold, so the selector has already seen the answers.

Measured on a 200-row sample with 1,000 noise columns added: selecting ten features on all the data gives 0.8310 AUC; selecting inside each fold gives 0.7571. The difference is fake skill produced by choosing columns that happen to correlate with the test labels.

Group leakage

The same customer, patient, device or session appears in both training and test. Duplicated rows do this most obviously, but so does a random split over repeat purchases or multiple visits per patient.

Measured with a 1-nearest-neighbour model on the churn data: 0.6410 AUC with unique customers, 0.7702 once 30% of rows are duplicated. The model is not generalising; it is recognising rows it has already memorised.

Temporal leakage

A random split trains on 2026 and tests on 2024. Lag features are computed from future values, a rolling average includes tomorrow, or a column like “days since last purchase” was calculated when the dataset was exported rather than at prediction time.

If the rows have an order in time, the split must respect it.

Target-encoding leakage

Mean encoding replaces a category with the average target value for that category. If that average is computed on all rows, each row’s encoding contains its own label. High-cardinality columns — customer ID, postcode, sales rep — can then memorise the target almost perfectly.

The fix is out-of-fold encoding: compute the means from the training folds only, and smooth rare categories toward the global mean. scikit-learn’s TargetEncoder, fitted inside a pipeline, cross-fits the encoding on the training folds, which removes the self-leak without extra code.

A score that looks too good: the leak, demonstrated

Here is the honest baseline, followed by the same model with one leaked column. Everything is inside a pipeline, so preprocessing cannot contaminate the score.

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("telco-customer-churn.csv")
df["TotalCharges"] = pd.to_numeric(df["TotalCharges"], errors="coerce")

y = (df["Churn"] == "Yes").astype(int)
X = df.drop(columns=["customerID", "Churn"])

num = ["tenure", "MonthlyCharges", "TotalCharges"]
cat = [c for c in X.columns if c not in num]
cv = StratifiedKFold(5, shuffle=True, random_state=42)

def cv_auc(frame, numeric=num):
    prep = ColumnTransformer([
        ("num", Pipeline([("imp", SimpleImputer(strategy="median")),
                          ("scale", StandardScaler())]), numeric),
        ("cat", Pipeline([("imp", SimpleImputer(strategy="most_frequent")),
                          ("encode", OneHotEncoder(handle_unknown="ignore"))]), cat),
    ])
    model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=2000))])
    return cross_val_score(model, frame, y, cv=cv, scoring="roc_auc").mean()

print(round(cv_auc(X), 4))  # 0.8449

rng = np.random.default_rng(0)
leaky = X.assign(retention_offer=np.where(rng.random(len(y)) < 0.95, y, 1 - y))
print(round(cv_auc(leaky, num + ["retention_offer"]), 4))  # 0.9834
print(round(cv_auc(leaky.drop(columns="retention_offer")), 4))  # 0.8449

Three numbers, and only the middle one is a problem:

  • 0.8449 — the honest baseline.
  • 0.9834 — the same data plus retention_offer, a field that only exists after the customer has left.
  • 0.8449 — back to reality once the column is dropped.

Nothing in that run looks broken. There is no warning, no convergence error, no suspicious NaN. The model did exactly what it was asked: it noticed that one column predicts the label almost perfectly and leaned on it. In production that column is missing, the model falls back to its weakest signal, and the collapse looks like concept drift rather than a design error.

One practical detail: ColumnTransformer only passes the columns you name. A new column that is in neither num nor cat is silently dropped, which is why the leaky run passes num + ["retention_offer"]. If you add a feature and the score does not move, check that it reached the transformer at all.

To hunt for this pattern before modelling, rank every numeric column by its correlation with the target:

X.assign(churn=y).corr(numeric_only=True)["churn"].abs().sort_values(ascending=False).head(10)

A feature sitting near 0.9 on a problem where everything else is below 0.4 deserves a timestamp check, not a celebration.

Data leakage vs overfitting

The two get blamed for each other, but they are different failures.

Overfitting is memorising noise inside legitimate features. The model has seen real, available-at-prediction-time inputs and learned their accidental quirks. The fix is regularisation, simpler models, more data, or early stopping.

Leakage is training on information that should not be available at all. The fix is deleting the column or restructuring the pipeline; no amount of regularisation will help, because the signal is real and strong.

A quick diagnostic: remove the single most important feature and retrain. If the score falls off a cliff, suspect leakage. If it falls a little and the model still generalises, you are probably looking at ordinary variance. For the full picture of the other failure, see Overfitting vs Underfitting in Machine Learning.

How to detect leakage in your own project

Run these six checks before you trust a score. They take ten minutes and catch most real cases.

  1. The score is implausibly high. Compare with published results on the same dataset, not with your own expectations. On Telco churn, 0.98 AUC is a red flag; 0.84 is normal.
  2. One feature dominates. Inspect coefficients or permutation importance. If a single column carries the model, ask when that column is written.
  3. A feature’s timestamp is after the outcome. Check the source system, not the dataframe. “Created at” fields usually settle the argument.
  4. Cross-validation is far above the holdout. A gap of several points means something in the CV loop is seeing more than it should.
  5. Rows repeat across folds. Count duplicates and repeated entity IDs before splitting.
  6. Time was ignored. If any column is a date or a duration, ask whether a shuffled split makes sense.
Check Catches Quick command
Near-perfect score Target leakage, duplicates compare with a published baseline
One dominant feature Target leakage permutation_importance on the holdout
Feature written after outcome Target leakage timestamp audit in the source system
CV ≫ holdout Preprocessing or selection leak cross_val_score vs a locked holdout
Repeated entities Group leakage df.duplicated(subset=["customerID"]).sum()
Shuffled time split Temporal leakage confirm shuffle=False or TimeSeriesSplit

Metrics can hide leakage too. This dataset is 26.5% churn, so a model that predicts “no churn” every time is already 73.5% accurate. Accuracy alone will not tell you whether a score is honest; How to Evaluate a Supervised Learning Model covers the metrics that will.

The fastest confirmation is an ablation. Train the model twice, once with the suspicious column and once without, and compare both the cross-validation and holdout scores. If the column is worth several points and its values are only written after the event, you have found the leak. If the gap is small and the column genuinely exists at prediction time, keep it — that is signal, not leakage.

The fix: a pipeline that cannot leak

The rule is one sentence: split first, then fit every preprocessing step on the training fold only.

scikit-learn’s Pipeline enforces that rule structurally. When you pass a pipeline to cross_val_score, the pipeline is cloned for each fold and fitted on that fold’s training rows; the validation rows are only ever transformed, never fitted.

numeric = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
])
categorical = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("encode", OneHotEncoder(handle_unknown="ignore")),
])
prep = ColumnTransformer([
    ("num", numeric, num),
    ("cat", categorical, cat),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=2000))])

scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(scores.mean().round(4))  # 0.8449

The distinction to internalise is fit_transform versus transform. fit_transform learns the parameters — the median, the mean and standard deviation, the category list — and applies them. transform only applies parameters that were already learned. A pipeline calls fit_transform on the training fold and transform on everything else, which is precisely the behaviour you would have to reproduce by hand, correctly, every time.

Two details matter in production:

  • handle_unknown="ignore" makes unseen categories encode as all zeros instead of raising an error when a new contract type appears after deployment.
  • The fitted pipeline is one object. joblib.dump(model, "churn.joblib") saves the imputers, the scaler, the encoder and the coefficients together, so the serving code cannot apply a different transformation than the training code did.

If you already have a notebook rather than a pipeline, the conversion is mechanical. List every step that calls fit. Move each one inside the ColumnTransformer. Replace the manual fit_transform(X) on the full frame with pipeline.fit(X_train, y_train), and let cross-validation own the folds. Any remaining line that fits on all rows is the one to delete.

It is worth checking the result against a locked holdout as well as cross-validation. On this data the holdout gives 0.8419 and the 5-fold CV gives 0.8449 — close enough that the two agree, which is what an honest evaluation looks like. For the mechanics of the split itself, see Training Data vs Testing Data.

Why does the wrong version survive review? Because on a dataset this size, fitting a scaler on all rows changes the score by a rounding error. The habit is invisible until the dataset is small, the features are many, or the leak is selection rather than scaling. If a step learns anything from data — imputation, scaling, encoding, PCA, feature selection — it belongs inside the pipeline. Feature Scaling shows how much the scaler itself depends on the rows it is fitted to, and Principal Component Analysis is the same problem in a different costume.

Group leakage: the same customer, twice

Duplicates are the most common form of group leakage, and the easiest to demonstrate. A 1-nearest-neighbour model is the right detector: it predicts from the closest training row, so an exact duplicate is an exact answer.

from sklearn.neighbors import KNeighborsClassifier

X_num = pd.get_dummies(X).astype(float).fillna(0)
knn = Pipeline([("scale", StandardScaler()),
                ("knn", KNeighborsClassifier(n_neighbors=1))])
cv = StratifiedKFold(5, shuffle=True, random_state=42)

print(round(cross_val_score(knn, X_num, y, cv=cv, scoring="roc_auc").mean(), 4))  # 0.6410

rng = np.random.default_rng(1)
idx = rng.choice(len(X_num), size=int(0.30 * len(X_num)), replace=False)
X_dup = pd.concat([X_num, X_num.iloc[idx]], ignore_index=True)
y_dup = pd.concat([y, y.iloc[idx]], ignore_index=True)
print(round(cross_val_score(knn, X_dup, y_dup, cv=cv, scoring="roc_auc").mean(), 4))  # 0.7702

A jump from 0.6410 to 0.7702 caused by copying rows is not learning. The model found neighbours that were the same row.

In real projects the duplicates are rarely exact. The same customer appears twice with a slightly different address, or one patient contributes six visits. The fix is to split by entity, not by row:

from sklearn.model_selection import GroupKFold

groups = df["customerID"]  # or patient_id, device_id, session_id
for train_idx, test_idx in GroupKFold(n_splits=5).split(X, y, groups):
    ...

GroupKFold keeps every row for an entity on one side of the split. Before that, remove exact duplicates: df.duplicated().sum() tells you whether there is anything to remove. When the groups are uneven — many customers with one row, a few with fifty — StratifiedGroupKFold keeps both the class balance and the group boundary. If you work with distance-based models regularly, K-Nearest Neighbors explains why they are so sensitive to this.

Time series: when a random split is always wrong

For forecasting, a shuffled split guarantees leakage: the model trains on December and is tested on June. It has seen the future. Scores look excellent and mean nothing.

from sklearn.model_selection import TimeSeriesSplit

for train_idx, test_idx in TimeSeriesSplit(n_splits=5).split(X):
    model.fit(X.iloc[train_idx], y.iloc[train_idx])
    score = model.score(X.iloc[test_idx], y.iloc[test_idx])

Three rules follow from the same idea:

  • Split chronologically, with an expanding or sliding window. TimeSeriesSplit does this by default.
  • Build lag and rolling features from past values only. A seven-day average must not include tomorrow.
  • Never impute with statistics computed over the whole series, and never forward-fill from a later observation. Both move future information backwards.

If features span several days, leave a gap between the end of the training window and the start of the test window, so a rolling feature cannot reach across the boundary. That gap is sometimes called an embargo, and it is the difference between a backtest you can trust and one you cannot.

Cross-Validation in Machine Learning covers the non-temporal case, including why k-fold is the default everywhere except time.

Frequently asked questions

What is data leakage in machine learning?

Data leakage is any information in training that will not be available when the model makes a real prediction. It comes from a post-outcome feature, from preprocessing fitted on test rows, or from a split that lets the same entity or the future into both sides. The score rises and its meaning disappears.

What is the difference between data leakage and overfitting?

Overfitting is memorising noise in legitimate features and improves with regularisation, simpler models or more data. Leakage is training on information that should not exist at prediction time, and only removing that information fixes it. If dropping one feature collapses the score, suspect leakage.

Does scaling before the train–test split cause leakage?

Yes. A scaler fitted on all rows learns a mean and standard deviation that include the test data, so the test set is no longer unseen. The effect is usually small on large datasets, which is why it goes unnoticed, but it is always wrong. Fit the scaler inside a pipeline so it only ever sees training folds.

Does cross-validation prevent data leakage?

No. Cross-validation only helps if every fitted step runs inside the fold. If you scale, impute, encode or select features before calling cross_val_score, each fold has already seen all the data and the estimate is inflated.

Is feature selection before splitting a leak?

Yes. Choosing columns by their correlation with the full target uses the labels of the validation rows. On a 200-row sample with 1,000 noise columns, selecting ten features outside the fold gave 0.8310 AUC against 0.7571 when selection ran inside cross-validation.

Is a random split always wrong for time series?

For forecasting, yes. A shuffled split trains on later observations and tests on earlier ones, so the model has seen the future. Use TimeSeriesSplit and build every lag from past values only.

Conclusion

Leakage is not a modelling problem; it is a bookkeeping problem. Split first. Fit every transformer on the training fold. Wrap the whole chain in a pipeline so the rule is enforced by code rather than by memory. Then treat any score that looks too good as a bug report until you have proved otherwise.

References and further reading

 

Scroll to Top