A final-year project lands on my desk with a confusion matrix that is almost all diagonal and a headline number of 99% accuracy. The first question I ask is not about the algorithm. It is this: at what point did your test data stop being a secret? In most of the project reviews and consulting work I do on machine learning, a too-good score has the same cause. The model was allowed to peek at the answers. That is called data leakage, and it is the most common reason a model that shines in the notebook falls flat the day it meets real data.
This guide is for practitioners: ML engineers, data analysts and anyone building a model for a client, a thesis or a startup demo. I ran every example below this morning, 3 December 2026, with Python 3.13.5 and scikit-learn 1.9.1. The numbers you see are the real output, not illustrations.
What this guide covers
- What leakage is, in one sentence
- Leak 1: feature selection before the split
- Leak 2: scaling before the split
- Leak 3: duplicates across train and test
- Leak 4: columns that know the answer
- Leak 5: shuffling a time series
- The fix: split first, then Pipeline everything
- A checklist you can run today
What leakage is, in one sentence
Kaufman, Rosset, Perlich and Stitelman define leakage as the introduction of information about the target that should not legitimately be available to the model (Kaufman et al., 2012, ACM TKDD). Their paper also makes the point that matters most for us: leakage leads to overestimating how good the model is, and the client usually finds out only after deployment.
The scikit-learn team puts the practical rule plainly in its Common pitfalls and recommended practices page: keep the test data out of every step that learns something from data, and that includes preprocessing, not only the final model.

Leak 1: feature selection before the split
This one is the most dramatic, so I start here in class. I built a dataset that contains no signal at all: 200 rows, 10,000 columns of random numbers, and random 0/1 labels. Any honest model should score about 50%, a coin flip.
The leaky version picks the 20 "best" columns using all 200 labels, then cross-validates. The honest version puts the selector inside a Pipeline so it only sees the training fold each time.
X = rng.normal(size=(200, 10000)); y = rng.randint(0, 2, size=200)
# LEAKY: the selector has already seen every label
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=cv)
# HONEST: selection is refitted inside each training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=cv)
Output from my run:
== 1. Feature selection before the split (pure noise) ==
X shape: (200, 10000) class balance: [110 90]
Leaky (select, then CV): 0.860 +/- 0.025
Honest (Pipeline in CV): 0.490 +/- 0.056
Read that again. 86% accuracy on pure noise. With 10,000 random columns, some of them line up with the labels by chance. If you choose them using all the labels, you have quietly copied part of the test answers into your features. Wide data makes this worse: gene expression, text with thousands of word columns, or a survey with hundreds of questions.
Leak 2: scaling before the split
Fitting StandardScaler on the full dataset is the classic textbook mistake. I am going to be honest about what my run showed, because it is useful. On the built-in breast cancer dataset (569 rows, 30 features), the leak made no visible difference:
== 2. Scaling before the split (breast cancer) ==
X shape: (569, 30)
Leaky (scale, then CV): 0.9789
Honest (Pipeline in CV): 0.9789
So why care? Because the mistake is still a mistake, and the size of the damage depends on the data. A mean and a standard deviation carry little information on 569 clean rows. Swap the scaler for target encoding, oversampling with SMOTE, or imputation driven by the label, and the same habit leaks far more. The scikit-learn pitfalls page uses this exact pattern as its warning example. Build the habit on the cheap cases so it holds on the expensive ones.
Leak 3: duplicates across train and test
Real project data is full of repeats. The same customer appears in three monthly extracts. The same patient visits four times. A data entry clerk imports a sheet twice. Augmented images sit next to their originals. If one copy lands in training and another in testing, the model is graded on something it has already memorised.
To show this, I made 300 random records with random labels, then repeated each one three times with tiny noise, giving 900 rows. A random forest was scored two ways: plain shuffled KFold, and GroupKFold with each original record as a group, so all copies stay on the same side.
== 3. Duplicate rows across train and test (noise labels) ==
rows: 900 unique records: 300
Leaky (random KFold): 0.980
Honest (GroupKFold by record): 0.497
98% versus 49.7%, and remember, the labels were random. Before you split, run df.duplicated().sum() and also check duplicates on your ID columns. If one person or device can have many rows, split by that ID.
Leak 4: columns that know the answer
This is the sneakiest kind because the code looks perfect. The problem is in the spreadsheet. A column was recorded after the thing you are trying to predict, so it carries the answer. Think "loan_recovery_officer_assigned" in a default model, "dropout_form_filed" in a student retention model, or "referred_for_surgery" in a diagnosis model.
I added that last one to the breast cancer data: a column that matches the true diagnosis 95% of the time, the way a referral record would.
noise = rng.rand(len(yb))
df["referred_for_surgery"] = np.where(noise < 0.95, 1 - yb, yb)
== 4. Target-derived feature (breast cancer) ==
Without the column: 0.9789
With the column: 0.9912
Top 3 importances:
referred_for_surgery 0.178
worst area 0.119
worst radius 0.101
There is your 99%. The jump looks small because the honest model was already strong, which is exactly why this leak survives review. Nobody questions 99.1% when 97.9% was believable. The clue is in the importances: one administrative column outranks every real measurement. Whenever a single feature dominates, ask the data owner one question: is this value known at the moment we need the prediction? If not, drop it.
Leak 5: shuffling a time series
Forecasting problems have an arrow of time. Rainfall, river levels, sales, mobile money volumes and exam trends all depend on what came before. If you shuffle the rows and split at random, the model trains on Thursday and Saturday and is "tested" on Friday. That is interpolation, not forecasting.
I generated a 1,000-step random walk with a slight upward drift and asked a random forest to predict the value from the time step. Then I scored it with shuffled KFold and with TimeSeriesSplit, which always trains on the past and tests on the future.
== 5. Shuffled split on a time series ==
Leaky MAE (shuffled KFold): 0.70
Honest MAE (TimeSeriesSplit): 9.03
Series std: 7.52
The shuffled score says the error is 0.70. The honest score says 9.03, which is worse than the spread of the series itself. Same model, same data. That gap is the difference between a demo and a forecast you can act on. This is a point I take seriously from my own research: our team's flood forecasting work in Kasese District (Journal of Flood Risk Management, 2025) is the kind of problem where only a time-ordered evaluation tells you anything useful about the next rainy season.

The fix: split first, then Pipeline everything
The cure is boring, which is good. Three rules cover most cases.
1. Hold out a test set before you look at anything. Split on day one. Put the test set away and do not plot it, impute it or select features with it.
2. Every step that calls fit goes inside a Pipeline. Imputers, scalers, encoders, selectors, PCA, resamplers. The scikit-learn Pipeline docs describe this as one of the main reasons pipelines exist: the same fitted steps are applied to training and test data in the right order.
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
pipe = make_pipeline(
SimpleImputer(strategy="median"),
StandardScaler(),
SelectKBest(f_classif, k=20),
LogisticRegression(max_iter=1000),
)
print(cross_val_score(pipe, X_train, y_train, cv=5).mean()) # tune on this
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test)) # report this, once
3. Match the splitter to the data. Independent rows: stratified K-fold. Repeat customers, patients or devices: GroupKFold. Anything with dates: TimeSeriesSplit, or a simple cut-off date where everything after it is the test set.
A checklist you can run today
Take your current project and go down this table. It takes under an hour, and it is cheaper than defending a number you cannot reproduce.
| Check | How | Red flag |
|---|---|---|
| Split happens first | Find the line with train_test_split. Is anything fitted above it? | fit_transform on full X |
| Preprocessing in a Pipeline | Search for fit( outside a Pipeline | Scaler or selector fitted on its own |
| Duplicates | df.duplicated().sum() and duplicates by ID | Same ID on both sides of the split |
| Feature timing | For each column, ask when it is recorded | Recorded after the outcome |
| Dominant feature | Look at the top importances | One admin column beats all real measurements |
| Time order | Do rows have dates? | Shuffled split on dated data |
| Sanity test | Shuffle y and rerun | Score stays well above chance |
The last row is my favourite. Shuffle the labels with np.random.permutation(y) and run the whole pipeline again. A clean pipeline drops to chance. A leaky one keeps finding "patterns" in nonsense, just like the 86% on noise above.
A modest, honest 82% that holds up in the field is worth more to a client, an examiner or a funder than a 99% that collapses on new data. Make the test set a secret, and keep it that way.
Sources and further reading
- Kaufman, S., Rosset, S., Perlich, C. and Stitelman, O. (2012). Leakage in data mining: Formulation, detection, and avoidance. ACM Transactions on Knowledge Discovery from Data, 6(4), Article 15.
- scikit-learn developers. Common pitfalls and recommended practices.
- scikit-learn developers. Pipelines and composite estimators.
- scikit-learn developers. TimeSeriesSplit and GroupKFold API reference.
- Development and Implementation of a Machine Learning-Based Flood Forecasting System in Kasese District, Uganda (2025). Journal of Flood Risk Management, DOI 10.1111/jfr3.70039.