A student gets hold of the question paper the night before the exam and scores 100. The mark is real, but it says nothing about what they know. Give them a fresh paper and the 100 disappears.
Data leakage in machine learning is the same thing: information the model shouldn't have had gets into training, usually without anyone noticing. The test score looks excellent, the model gets deployed, and in real use it performs far worse. Leakage is one of the most common reasons machine learning projects fail, and it's hard to spot because nothing crashes: the only symptom is a score that's too good. You'll see the main kinds on real data, how to catch each one, and how to avoid them.
What you need first: scikit-learn pipelines, how to frame a machine learning problem (especially prediction time) and feature engineering basics.
Key terms
- Data leakage: any way information from outside the training data, or from the future, reaches the model during training, making its test score too optimistic.
- Target leakage: a feature that contains the answer, usually because it's recorded after the outcome.
- Train-test contamination: test rows influence training, for example by fitting a scaler on all the data before splitting.
- Temporal leakage: training on data from after the moments you're predicting, so the model "knows the future".
- Prediction time: the moment the model will make each prediction in real use. Only information available then is fair to use.
Leakage in one picture
Most leakage comes down to doing things in the wrong order. Any step that learns from data, such as fitting a scaler, filling gaps with an average, or choosing the best features, must learn only from training rows:
On the left, the orange step learned from the test rows before they were set aside. On the right, the test rows are locked away first, so they stay truly unseen. Keep this picture in mind; every example below is a version of it.
Target leakage: a feature that contains the answer
The Titanic dataset lists 891 passengers and whether they survived. Look at its columns:
Download the data: titanic.csv (56 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("titanic.csv").
import numpy as np
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset("titanic")
print(titanic.shape)
print(titanic.columns.tolist())
(891, 15)
['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']
The label is survived. A beginner might use every other column as a feature. Try exactly that with a few of them, including alive, and see what happens. A decision tree (a flowchart of yes/no questions, introduced in the scikit-learn tutorial) is the model:
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
columns = ["pclass", "sex", "age", "fare", "sibsp", "parch", "alive"]
X = pd.get_dummies(titanic[columns], dtype=int)
X["age"] = X["age"].fillna(28) # a fixed number, so nothing is learned from the data
y = titanic["survived"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y)
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("test accuracy:", round(tree.score(X_test, y_test), 3))
test accuracy: 1.0
A perfect score on the test set. For a disaster where survival depended on luck as much as anything, that should make you suspicious straight away. Rule one of leakage: a score that's too good to be true usually is. Now check alive against the label:
print(pd.crosstab(titanic["alive"], titanic["survived"]))
survived 0 1
alive
no 549 0
yes 0 342
pd.crosstab counts how often each pair of values occurs. Every "yes" in alive is a 1 in survived, and every "no" is a 0. The column is the label, written as words. The model didn't learn anything about the Titanic; it learned to read the answer.
Remove it and train again:
X_honest = X.drop(columns=["alive_no", "alive_yes"])
X_train, X_test = X_honest.loc[X_train.index], X_honest.loc[X_test.index]
honest_tree = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_train, y_train)
print("test accuracy:", round(honest_tree.score(X_test, y_test), 3))
test accuracy: 0.794
That's the real performance. (max_depth=4 stops the tree after four levels of questions, so it can't memorise the training passengers; you'll learn why that matters in the overfitting lesson.)
alive is an obvious case because it's an exact copy. Real target leakage is usually a column recorded after the outcome, which carries the answer partly:
| Project | Leaky feature | Why it leaks |
|---|---|---|
| Will this loan default? | Number of late EMIs on this loan | Only exists after the loan is given |
| Does this patient have diabetes? | Takes metformin (a diabetes medicine) | Prescribed because of the diagnosis |
| Will this customer cancel? | Reason for cancellation | Filled in when they cancel |
| Will this student fail? | Attended the re-exam | Only failing students attend |
| Delivery time | Rider's actual route length | Known only after delivery |
How to catch target leakage
Two checks find most of it.
Ask the prediction-time question for every feature: "Will I know this value at the moment I make the prediction?" Write the prediction time down while framing the problem, then go through the columns one by one.
Test each feature on its own. A single feature that predicts the label almost perfectly deserves a close look. Here, a tiny tree is trained on one column at a time:
for column in ["pclass", "sex", "fare", "alive"]:
one = pd.get_dummies(titanic[[column]], dtype=int)
a_train, a_test = one.loc[y_train.index], one.loc[y_test.index]
stump = DecisionTreeClassifier(max_depth=2, random_state=0).fit(a_train, y_train)
print(f"{column:7} alone: {stump.score(a_test, y_test):.3f}")
pclass alone: 0.623
sex alone: 0.771
fare alone: 0.646
alive alone: 1.000
sex alone already scores well, which matches the history ("women and children first"), so it's a genuine signal. But alive alone is perfect, which no honest single feature should be. When you see that, find out exactly how and when the column is recorded.
Train-test contamination: learning from the test rows
This kind of leakage hides in preprocessing. Any step that learns from data can leak if it runs before the split.
To see how badly it can go, here's a dataset where there's nothing to learn: 1,000 rows of 2,000 columns of random numbers, with random 0/1 labels. No model can honestly do better than about 50%. The "wrong" version picks the 20 features most related to the label using all the rows, then splits. The "right" version splits first, and picks features inside a pipeline using only training rows:
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X_noise = rng.normal(size=(1000, 2000))
y_noise = rng.integers(0, 2, size=1000)
# Wrong: choose features with all 1,000 rows, then split
chosen = SelectKBest(f_classif, k=20).fit(X_noise, y_noise).get_support()
a_train, a_test, b_train, b_test = train_test_split(X_noise[:, chosen], y_noise, test_size=0.5, random_state=0)
wrong = LogisticRegression().fit(a_train, b_train).score(a_test, b_test)
# Right: split first; the pipeline chooses features from training rows only
a_train, a_test, b_train, b_test = train_test_split(X_noise, y_noise, test_size=0.5, random_state=0)
pipeline = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
right = pipeline.fit(a_train, b_train).score(a_test, b_test)
print(f"wrong order: {wrong:.3f} right order: {right:.3f}")
wrong order: 0.662 right order: 0.478
SelectKBest(f_classif, k=20) scores every column by how differently it behaves for label 0 and label 1, and keeps the top 20. get_support() returns True for the kept columns.
Predict before reading on: why did the wrong order score so well on pure noise? With 2,000 random columns, some will match the labels by chance, including the test rows' labels. Choosing features with all 1,000 rows picked exactly those lucky columns. The model then "found" that luck again in the test rows, because the test rows helped choose them. In the right order, features are chosen from training rows only, their lucky matches don't carry over to the test rows, and the score falls to about 50%, the honest answer.
The same rule applies to every step that learns:
| Step | What it learns | Leaks if fit on all rows? |
|---|---|---|
StandardScaler | Mean and standard deviation | Yes, slightly |
SimpleImputer(strategy="mean") | Mean of each column | Yes, slightly |
| Feature selection using the label | Which columns match the labels | Yes, badly |
| Target encoding (average label per category) | Average outcome per category | Yes, badly |
pd.get_dummies on all rows | The list of categories | A little: unseen categories look known |
| A row-wise feature (ratio, log, date part) | Nothing | No |
Scaling and mean-filling usually leak only a little, because a mean barely changes when you remove a quarter of the rows. Anything that uses the label leaks a lot. But you don't need to judge each case: put every learning step inside a pipeline, and the problem can't happen.
Temporal leakage: predicting the past from the future
A wholesale trader wants to predict tomorrow's onion price. Here are two years of made-up daily prices that drift up and down, as real prices do:
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
days = np.arange(730)
price = 40 + np.cumsum(rng.normal(0, 0.8, size=730)) # each day = yesterday + a random change
print(f"price ranges from ₹{price.min():.1f} to ₹{price.max():.1f} per kg")
price ranges from ₹24.7 to ₹49.2 per kg
np.cumsum adds up the daily changes as it goes, so each price is the previous day's price plus a small random step. That's called a random walk, and many real prices behave a bit like one.
Now compare two ways of making a test set. A random split, which is what train_test_split does by default, against a time split that trains on the first 584 days (80%) and tests on the last 146:
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_absolute_error
X_days = days.reshape(-1, 1)
d_train, d_test, p_train, p_test = train_test_split(X_days, price, test_size=0.2, random_state=0)
random_model = KNeighborsRegressor(n_neighbors=5).fit(d_train, p_train)
random_error = mean_absolute_error(p_test, random_model.predict(d_test))
cut = 584
time_model = KNeighborsRegressor(n_neighbors=5).fit(X_days[:cut], price[:cut])
time_error = mean_absolute_error(price[cut:], time_model.predict(X_days[cut:]))
print(f"random split: off by ₹{random_error:.2f} per kg on average")
print(f"time split: off by ₹{time_error:.2f} per kg on average")
random split: off by ₹0.67 per kg on average
time split: off by ₹6.93 per kg on average
The model is a nearest-neighbours regressor: it predicts a day's price as the average of the five nearest days it has seen. Predict: which test is the honest one? The trader always predicts days they haven't reached yet. With a random split, almost every test day has training days just before and just after it, so the model only has to fill gaps between known prices. That's far easier than forecasting, and the error is ten times smaller than it really is. The picture shows why:
fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
test_days = np.sort(d_test.ravel())
axes[0].plot(days, price, color="#a8a29e", linewidth=1)
axes[0].scatter(test_days, price[test_days], s=8, color="#c2410c", label="test days")
axes[0].set_title("Random split: test days scattered")
axes[0].set_xlabel("Day")
axes[0].set_ylabel("Price (₹ per kg)")
axes[0].legend()
axes[1].plot(days[:cut], price[:cut], color="#a8a29e", linewidth=1)
axes[1].plot(days[cut:], price[cut:], color="#0f766e", linewidth=2, label="test days")
axes[1].plot(days[cut:], time_model.predict(X_days[cut:]), color="#c2410c", linestyle="--", label="prediction")
axes[1].set_title("Time split: test days in the future")
axes[1].set_xlabel("Day")
axes[1].legend()
plt.show()
On the left, every orange test day is surrounded by grey training days, so filling it in is easy. On the right, the model has nothing after day 583, so its prediction is flat while the real price keeps moving. The right-hand error is the one the trader will actually experience.
The fix for time-ordered data: split by time, never randomly. Train on the past, test on the future. Also check features: "average price over the next 7 days" or a moving average that includes future days leaks the same way. Cross-validation explained shows TimeSeriesSplit, which does this for several rounds.
The same thing on both sides of the split
A last kind of leakage: the same person or object appears in both training and test rows.
- Duplicate rows. If a record was entered twice, one copy can land in training and one in testing. The model is then tested on a row it has already seen. Remove true duplicates first: remove duplicate rows shows how.
- Several rows per person. Five X-ray images of the same patient, or 50 orders from the same customer. If some are in training and some in testing, the model can recognise the person rather than learn the pattern. Split by person, so all of one person's rows are on the same side. Cross-validation explained covers
GroupKFoldfor this.
A leakage checklist
Go through this before you trust any score:
- Is the score too good? Compare with what experts or simple rules achieve. Near-perfect scores on a hard problem mean leakage until proven otherwise.
- Prediction time: is every feature known at the moment of prediction?
- Single-feature check: does any one feature predict the label almost perfectly?
- Order: did you split before any step that learns (scaling, filling, encoding, selecting)? Is every such step inside a pipeline?
- Time: if rows have dates, did you split by time?
- Identity: can the same person, customer or object appear on both sides of the split? Are there duplicates?
- Test set use: did you make any decision (features, settings, model) by looking at the test score? If so, it's no longer a fair test.
Common mistakes
- Scaling, imputing or encoding before
train_test_split. Fit those steps on training data only, ideally in a pipeline. - Selecting features with all the data. On wide data, this alone can turn noise into a "good" model.
- Random splits on dates. The model fills in gaps instead of forecasting.
- Trusting a perfect score. Investigate before celebrating.
- Checking the test score after every change. Each look leaks a little; use a validation set or cross-validation for decisions.
Practice
- A hospital model predicts heart disease with 99% accuracy. One feature is "was referred to a cardiologist". What would you check, and why?
Show the answer
Check when the referral happens. If patients are referred because doctors already suspect or diagnosed heart disease, the feature is recorded after (and because of) the outcome: target leakage. At prediction time, for a new patient, the referral won't have happened yet. Remove the feature and see how much the accuracy drops.
- Spot the bug:
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X_honest)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, random_state=0)
Show the answer
The scaler is fitted on all rows before the split, so the test rows' means and standard deviations shaped the scaling. Split first, then use make_pipeline(StandardScaler(), model) and fit it on the training rows. For a scaler the effect is usually small, but the habit matters, because the same mistake with feature selection or target encoding can be huge.
- In the noise experiment, change
k=20tok=100in the wrong version. Predict whether the leaked score goes up or down, then run it.
Show the answer
chosen = SelectKBest(f_classif, k=100).fit(X_noise, y_noise).get_support()
a_train, a_test, b_train, b_test = train_test_split(X_noise[:, chosen], y_noise, test_size=0.5, random_state=0)
print(round(LogisticRegression().fit(a_train, b_train).score(a_test, b_test), 3))
0.692
It goes up, from 0.662 to 0.692. With 100 hand-picked columns there are more chance matches with the test labels for the model to exploit. Yet every one of those columns is pure noise, and the honest answer is still about 50%.
- You're predicting which customers will cancel their mobile plan next month. Your table has one row per customer per month for two years. How would you split the data?
Show the answer
By time: train on earlier months, test on the latest months, because the model will always predict the future. Also make sure no feature uses information from after the month being predicted (for example, "total calls this year" computed at the end of the year). If the same customers appear in both periods, that's fine here, because in real use you'll also predict for customers you've seen before.
- Why is "number of late EMIs on this loan" a leaky feature for predicting loan default at application time, but "number of late EMIs on previous loans" is fine?
Show the answer
Late EMIs on this loan only exist after the loan is approved and running, which is after prediction time (the application). Late EMIs on earlier loans are already in the credit history when the person applies, so they're known at prediction time.
- A teammate's model scores 0.95 in testing and 0.70 after deployment. Name three leakage causes you'd investigate.
Show the answer
Any three of: a feature recorded after the outcome (target leakage); preprocessing or feature selection fitted on all the data before splitting; a random split on time-ordered data; the same customers or duplicate rows on both sides of the split; decisions made by repeatedly checking the test score. Other causes of a drop, such as the data changing after deployment, are also worth checking, but leakage comes first.
Interview questions
What is data leakage, and how do you prevent it?
Data leakage is when information unavailable at prediction time, or from the test set, influences training, so evaluation is over-optimistic. Prevent it by splitting before any data-dependent preprocessing, fitting all preprocessing inside a pipeline on training data, checking each feature against the prediction time, splitting time series chronologically, keeping groups (such as patients) on one side of the split, and using the test set only once.
What's the difference between target leakage and train-test contamination?
Target leakage is about features: a feature contains information about the label that won't exist at prediction time, such as a post-outcome record. Train-test contamination is about process: test data influences training, such as fitting a scaler or selecting features on the full dataset before splitting. Both inflate test scores.
Why shouldn't you randomly split time-series data?
A random split puts future observations into the training set, so the model can interpolate between known neighbouring points instead of forecasting. Test errors become much lower than real forecasting errors. Split chronologically, training on the past and testing on later periods.
Key takeaways
- Leakage means the model saw information it won't have in real use, so the test score is too good.
- Target leakage: a feature recorded after the outcome. Catch it with the prediction-time question and single-feature checks.
- Contamination: steps that learn from data must be fit on training rows only. Pipelines make this automatic.
- Time data must be split by time; random splits turned a ₹6.93 error into an apparent ₹0.67.
- Keep the same person or object on one side of the split, and remove duplicates.
- A near-perfect score on a hard problem is a warning, not a win.
Frequently asked questions
Is scaling before splitting really that bad?
Usually the effect on the score is small, because means and standard deviations barely change. But it's still wrong, it's an easy habit to fix with a pipeline, and the same mistake with steps that use the label (feature selection, target encoding) can make a useless model look excellent.
How can I tell if my model has leakage?
Look for scores that are much better than experts or simple baselines achieve, a single feature that predicts the label almost perfectly, a large gap between test and real-world performance, or features whose values are only known after the outcome. Then review the order of your preprocessing steps.
Does cross-validation prevent leakage?
No. Cross-validation can leak in exactly the same ways if preprocessing is done before it, or if folds mix time periods or groups. Cross-validate a pipeline, and use time-based or group-based folds when the data needs them.
What to learn next
- Public datasets for machine learning practice: the next lesson, where to find data and what to check before you trust it.
- Project: prepare messy data for machine learning: put cleaning, encoding, pipelines and leakage checks together on real data.
- Cross-validation explained: fair evaluation with several splits, including time and group splits.
- Scikit-learn pipelines: revisit how to package every learning step.