Skip to content
30 November 2026 An independent technology publication
Explainer

Data leakage in machine learning: 6 dangerous mistakes, reproduced in Python

Data leakage makes models look great in testing and fail in production. See 6 real leaks reproduced in Python, how much each inflates scores, and the fix.

Data leakage in machine learning: 6 dangerous mistakes, reproduced in Python, DevQuarry featured image

Data leakage happens when information that would not be available at prediction time ends up in the data used to train or evaluate a model. The model then scores well in testing and disappoints in production, because part of its “skill” came from peeking at the answer.

Leakage is easy to commit and hard to see. Nothing crashes, the scores just look a bit too good. To make that concrete, I reproduced six common leaks in Python on real and synthetic data and measured how far each one inflates the score. The worst turned coin-flip labels into 85% accuracy.

Data leakage in machine learning: leaky vs correct scores, DevQuarry featured image

Key takeaways

  • Data leakage inflates offline scores without any error message. The model looks better than it will ever be.
  • In these tests, leakage pushed accuracy on random labels from 54% to 85%, and fraud recall from 87% to a fake 100%.
  • Most leaks come from doing something to the whole dataset before splitting it: scaling, encoding, feature selection or oversampling.
  • Put every data-dependent step inside a scikit-learn Pipeline, split by time or by group when rows are related, and question any feature you would not have at prediction time.

What is data leakage?

Data leakage is any path by which the model sees information during training or evaluation that it will not have when it makes real predictions. That information can be the target itself, a value computed from it, a statistic of the test set, or a near-copy of a test row.

Princeton researchers Sayash Kapoor and Arvind Narayanan reviewed published work across science and found data leakage in 294 papers spread over 17 fields (Patterns, September 2023). In one case study on civil war prediction, the claimed advantage of complex models over logistic regression disappeared once the leaks were fixed. If peer-reviewed papers fall into it, a project with a deadline will too.

Two families of leakage cover almost every case:

FamilyWhat leaksTypical example 
Train/test contaminationInformation from the test rows reaches trainingScaling, encoding or oversampling the full dataset before splitting
Target leakageA feature carries the answerA column that is only filled in after the outcome happens

Kapoor and Narayanan split these further into eight types, including no test set at all, duplicates across splits, temporal leakage and non-independence between training and test samples. The six experiments below cover the ones I see most often in student projects and Kaggle notebooks.

Why data leakage is so hard to catch

A model with leakage does not throw an exception or print a warning. It behaves exactly like a good model until it meets data it has never seen. A few signs are worth treating as alarms:

  • A validation score far above anything reported for similar problems.
  • One feature with an importance far larger than all the others.
  • Cross-validation scores that are high and nearly identical in every fold.
  • A big gap between offline metrics and the first week of production results.
  • A “simple” baseline that suddenly performs like a state-of-the-art model.

None of these proves data leakage on its own. Each one is a reason to stop and check how the data was split and when each feature becomes available.

How I tested each leak

Every experiment below runs twice: once with the leak and once done correctly. Same data, same model, same random seeds. The only change is where the split happens or which features are allowed.

The environment:

ComponentVersion 
Python3.13
scikit-learn1.9.1
XGBoost3.4.1
imbalanced-learn0.14.2
Hardware2 CPU cores, no GPU

Experiments 3, 4 and 5 use the public credit card fraud dataset from the ULB Machine Learning Group: 284,807 card transactions from two days in September 2013, of which 492 are fraud. The others use synthetic data, where I know for certain that the true signal is zero.

Install the libraries and load the shared imports:

bash
pip install scikit-learn xgboost imbalanced-learn pandas


import sys
import numpy as np
import pandas as pd
import xgboost as xgb
from imblearn.over_sampling import RandomOverSampler
from imblearn.pipeline import make_pipeline as make_imb_pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, recall_score, roc_auc_score
from sklearn.model_selection import (GroupKFold, KFold, RepeatedStratifiedKFold,
                                     cross_val_score, train_test_split)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import TargetEncoder

rng = np.random.default_rng(0)
CSV = sys.argv[1] if len(sys.argv) > 1 else "creditcard.csv"

Here is the scoreboard before we go through each case:

#LeakLeaky scoreCorrect score 
1Feature selection before cross-validation85.3% accuracy54.0% accuracy
2Target encoding on the full dataset0.887 ROC-AUC0.490 ROC-AUC
3A feature recorded after the outcome0.982 PR-AUC0.779 PR-AUC
4Random split on time-ordered data0.851 PR-AUC0.779 PR-AUC
5Oversampling before the split100.0% recall87.2% recall
6Related rows split across train and test78.0% accuracy54.0% accuracy
Data leakage results chart: leaky vs correct score for six experiments

Mistake 1: Selecting features before cross-validation

Feature selection is a classic source of data leakage. Any selection step that looks at the labels must happen inside each training fold. If you rank features on the full dataset and then cross-validate, the test folds have already voted on which features survive.

To show how strong this effect is, I made a dataset that contains no signal at all: 200 rows, 10,000 columns of random numbers and labels from a coin flip. No model can honestly beat 50% here.

bash
print("1. Feature selection before cross-validation (pure noise data)")
X = rng.normal(size=(200, 10_000))
y = rng.integers(0, 2, 200)                      # labels are coin flips
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)
X_top = SelectKBest(f_classif, k=20).fit_transform(X, y)   # leak: selection saw every label
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_top, y, cv=cv).mean()
clean = cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)),
                        X, y, cv=cv).mean()
print(f"   leaky accuracy {leaky:.1%} | correct accuracy {clean:.1%}\n")


Output:
1. Feature selection before cross-validation (pure noise data)
   leaky accuracy 85.3% | correct accuracy 54.0%

With 10,000 random columns, some will line up with the labels by chance. Choosing the 20 best on all 200 rows means the test folds helped pick them, so the model “predicts” noise at 85%. Inside a pipeline, the selection runs again on each training fold and the score falls back to roughly chance (54% over 50 folds).

How to avoid it:

  1. Put SelectKBest, SelectFromModel, RFE and any correlation filter inside a Pipeline.
  2. Pass the whole pipeline to cross_val_score or GridSearchCV, never the transformed array.
  3. Be extra careful when you have many more columns than rows, as in genomics or text features. That is where the inflation is largest.

Mistake 2: Target encoding on the whole dataset

Target encoding replaces a category with the average target value for that category. It is powerful for high-cardinality columns like merchant IDs or ZIP codes, and it is one of the easiest ways to cause data leakage.

In this test, each of 5,000 transactions gets a merchant_id from 2,500 possible values, and the label is random. The merchant tells you nothing. The leaky version computes each merchant’s mean label on all rows, including the row being predicted.

bash
print("2. Target encoding an ID column on the full dataset")
n = 5000
df = pd.DataFrame({"merchant_id": rng.integers(0, 2500, n), "noise": rng.normal(size=n)})
df["y"] = rng.integers(0, 2, n)                  # target unrelated to merchant
df["merchant_mean"] = df.groupby("merchant_id")["y"].transform("mean")   # leak
Xtr, Xte, ytr, yte = train_test_split(df, df["y"], test_size=0.3, random_state=0)
leaky_m = LogisticRegression().fit(Xtr[["merchant_mean", "noise"]], ytr)
leaky = roc_auc_score(yte, leaky_m.predict_proba(Xte[["merchant_mean", "noise"]])[:, 1])
enc = TargetEncoder(cv=KFold(5, shuffle=True, random_state=0))   # cross-fitted, training split only
tr_enc = enc.fit_transform(Xtr[["merchant_id"]], ytr)
te_enc = enc.transform(Xte[["merchant_id"]])
clean_m = LogisticRegression().fit(np.c_[tr_enc, Xtr["noise"]], ytr)
clean = roc_auc_score(yte, clean_m.predict_proba(np.c_[te_enc, Xte["noise"]])[:, 1])
print(f"   leaky ROC-AUC {leaky:.3f} | correct ROC-AUC {clean:.3f}\n")


Output:
2. Target encoding an ID column on the full dataset
   leaky ROC-AUC 0.887 | correct ROC-AUC 0.490

Most merchants appear only twice, so a merchant’s average label is largely the row’s own label. The model learns to read it straight back, and an ROC-AUC of 0.887 appears out of nothing. scikit-learn’s TargetEncoder avoids this by cross-fitting: in fit_transform, each row’s encoding is computed from other folds only. Fit it on the training split, then call transform on the test split.

One version note from the run: in scikit-learn 1.9 the shuffle and random_state arguments of TargetEncoder are deprecated. Passing a splitter such as cv=KFold(5, shuffle=True, random_state=0), as above, is the supported way to control shuffling.

Mistake 3: Using a feature that only exists after the outcome

This is classic target leakage. A column looks like an ordinary input, but in reality it is filled in after the thing you are trying to predict has happened.

Fraud data is full of these. Chargebacks are filed after a customer disputes a fraudulent charge. A “reviewed by analyst” flag is set because a case looked suspicious. A “refund issued” column exists because the fraud was already confirmed. To show the effect, I added a chargeback_filed column to the real fraud data that is 1 for 90% of fraud cases and 0 otherwise.

bash
print("3. A feature that only exists after the outcome (target leakage)")
cc = pd.read_csv(CSV).sort_values("Time").reset_index(drop=True)
FEATS = [c for c in cc.columns if c not in ("Class", "Time")]
cc["chargeback_filed"] = ((cc["Class"] == 1) & (rng.random(len(cc)) < 0.9)).astype(int)
cut = int(len(cc) * 0.8)
tr, te = cc.iloc[:cut], cc.iloc[cut:]
def pr_auc(cols, train=tr, test=te):
    m = xgb.XGBClassifier(n_estimators=300, learning_rate=0.05, max_depth=6, n_jobs=2, random_state=0)
    m.fit(train[cols], train["Class"])
    return average_precision_score(test["Class"], m.predict_proba(test[cols])[:, 1])
print(f"   with chargeback_filed PR-AUC {pr_auc(FEATS + ['chargeback_filed']):.3f} | "
      f"without it PR-AUC {pr_auc(FEATS):.3f}\n")


Output:
3. A feature that only exists after the outcome (target leakage)
   with chargeback_filed PR-AUC 0.982 | without it PR-AUC 0.779

A PR-AUC of 0.98 on fraud data should make anyone suspicious. Notice that the split here was done correctly, by time. Target leakage survives a perfect split, because the problem is in the feature, not in which rows went where.

A practical test for every column: write down the exact moment the prediction will be made, then ask whether the value of this feature is known at that moment. If the answer is “only sometimes” or “after a manual review”, leave it out or rebuild it as of that timestamp.

Mistake 4: Splitting time-ordered data at random

When rows are ordered in time, a random split causes data leakage from the future: the model trains on later rows and is tested on earlier ones. Patterns from a given hour or a given fraud campaign appear on both sides of the split, which makes the test look easier than real use.

Using the same fraud data and the same XGBoost model, I compared a random stratified split with a split where the model trains on the first 80% of the timeline and is tested on the last 20%:

bash
print("4. Random split vs time split on transaction data")
r_tr, r_te = train_test_split(cc, test_size=0.2, random_state=0, stratify=cc["Class"])
print(f"   random split PR-AUC {pr_auc(FEATS, r_tr, r_te):.3f} | time split PR-AUC {pr_auc(FEATS):.3f}\n")


Output:
4. Random split vs time split on transaction data
   random split PR-AUC 0.851 | time split PR-AUC 0.779

The random split adds about 0.07 PR-AUC. That sounds small until you remember that the real model will only ever see the future. The time-split number is the honest one. This dataset covers just two days, so in data that spans months, with seasonality and shifting fraud tactics, the gap is usually larger.

For time-ordered data:

  • Split on a timestamp, not with train_test_split(shuffle=True).
  • For cross-validation, use TimeSeriesSplit, which always trains on earlier folds and tests on later ones.
  • Build lag features and rolling averages from past rows only. A rolling mean centred on the current row leaks the next few values.
  • Leave a gap between training and test periods when labels arrive late. Fraud labels, for instance, often take weeks to confirm.

Mistake 5: Oversampling before the split

Oversampling copies or synthesises minority-class rows so the model sees more of them. Done before the split, it causes data leakage by putting copies of the same fraud case in both the training set and the test set. The model then “recognises” test rows it has effectively already seen.

I took all 492 fraud cases plus 20,000 random legitimate ones, then compared oversampling-then-splitting with splitting first and oversampling only the training data inside an imbalanced-learn pipeline:

bash
print("5. Oversampling before the split")
small = pd.concat([cc[cc.Class == 1], cc[cc.Class == 0].sample(20_000, random_state=0)])
Xs, ys = small[FEATS], small["Class"]
X_over, y_over = RandomOverSampler(random_state=0).fit_resample(Xs, ys)   # leak: copies cross the split
a_tr, a_te, b_tr, b_te = train_test_split(X_over, y_over, test_size=0.3, random_state=0, stratify=y_over)
rf = RandomForestClassifier(n_estimators=200, n_jobs=2, random_state=0).fit(a_tr, b_tr)
leaky = recall_score(b_te, rf.predict(a_te))
c_tr, c_te, d_tr, d_te = train_test_split(Xs, ys, test_size=0.3, random_state=0, stratify=ys)
pipe = make_imb_pipeline(RandomOverSampler(random_state=0),
                         RandomForestClassifier(n_estimators=200, n_jobs=2, random_state=0)).fit(c_tr, d_tr)
clean = recall_score(d_te, pipe.predict(c_te))
print(f"   leaky fraud recall {leaky:.1%} | correct fraud recall {clean:.1%}\n")

A perfect 100% recall is the giveaway. After random oversampling, almost every fraud row in the test set has an identical twin in the training set, and a random forest memorises those twins easily. The same thing happens with SMOTE, only less obviously, because SMOTE’s synthetic rows are interpolated from real neighbours that can sit on the other side of the split.

The fix is mechanical. Use imblearn.pipeline.Pipeline (or make_pipeline from imbalanced-learn, as above) so that resampling runs only when the pipeline is fitted, and only on training data. The imbalanced-learn documentation explains why scikit-learn’s own Pipeline cannot do this. Our fraud detection tutorial shows the same pattern in a complete project.

Many datasets contain several rows per patient, customer, device or session. If rows from the same person land in both training and test, data leakage lets the model learn to recognise the person rather than the pattern you care about.

In this simulation, 300 people each have 8 visits. Each person has five stable traits that barely change between visits, and each person’s label is random. There is nothing to learn about the label, only about who the person is.

bash
print("6. Several rows per person, split by row instead of by person")
people, visits = 300, 8
person = np.repeat(np.arange(people), visits)
trait = np.repeat(rng.normal(size=(people, 5)), visits, axis=0)       # stable per person
Xg = trait + rng.normal(scale=0.3, size=trait.shape)
yg = np.repeat(rng.integers(0, 2, people), visits)                    # label set per person, unrelated to traits
rf = RandomForestClassifier(n_estimators=200, n_jobs=2, random_state=0)
leaky = cross_val_score(rf, Xg, yg, cv=KFold(5, shuffle=True, random_state=0)).mean()
clean = cross_val_score(rf, Xg, yg, cv=GroupKFold(5), groups=person).mean()
print(f"   KFold accuracy {leaky:.1%} | GroupKFold accuracy {clean:.1%}")


Output:
6. Several rows per person, split by row instead of by person
   KFold accuracy 78.0% | GroupKFold accuracy 54.0%

With ordinary KFold, a person’s other visits are in the training folds, so the forest matches the test visit to its siblings and copies their label. GroupKFold keeps every visit from the same person in a single fold, and the score drops to where it belongs.

Use group-aware splitting whenever there is an ID that repeats: GroupKFold, StratifiedGroupKFold or GroupShuffleSplit in scikit-learn. Medical imaging (several scans per patient), recommendation logs (many events per user) and sensor data (many readings per machine) are the usual suspects.

The less obvious leaks

The six experiments above are the ones I could reproduce cleanly. A few other forms of data leakage come up often enough to check for:

Preprocessing statistics from the test set

Fitting a StandardScaler, an imputer or a PCA on the full dataset uses the test set’s mean, variance or components. For scaling, the effect is usually small. For imputation with many missing values, or for PCA on wide data, it can be noticeable. The fix is the same as always: fit inside a pipeline.

Duplicates and near-duplicates

The fraud dataset has 1,081 rows that are exact copies, timestamp included. Ignore the timestamp and the count rises to 9,144 rows that repeat every feature and the label. When duplicates fall on both sides of a split, the test set partly measures memory. Deduplicate before splitting, or split by a group key so copies stay together. Near-duplicates are harder, for example the same photo resized or the same product description with a typo fixed. Hash-based or embedding-based deduplication helps there.

Tuning on the test set

If you try twenty hyperparameter settings and keep the one with the best test score, the test set has become a validation set. Its score is now optimistic. Keep three splits (train, validation, test) or use nested cross-validation, and look at the test set once, at the end.

Leaks through the data pipeline

Sometimes the leak happens before the data reaches you. A warehouse table might be overwritten nightly with the latest values, so a “customer tier” column shows today’s tier for a transaction from last year. Point-in-time correct joins, where every feature is fetched as of the event timestamp, are the standard defence. Feature stores often provide this as a built-in option.

Three quick tests that catch data leakage

You can find many leaks without knowing in advance what to look for. I ran three cheap checks on the fraud data, and each took under a minute on two CPU cores. The full script is below, followed by its output.

bash
import sys
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import cross_val_predict, StratifiedKFold, train_test_split

cc = pd.read_csv(sys.argv[1] if len(sys.argv) > 1 else "creditcard.csv").sort_values("Time").reset_index(drop=True)
FEATS = [c for c in cc.columns if c not in ("Class", "Time")]

# Check 1: exact duplicate rows that land on both sides of a split
tr, te = train_test_split(cc, test_size=0.2, random_state=0, stratify=cc["Class"])
key = FEATS + ["Class"]
shared = te.merge(tr[key].drop_duplicates(), on=key, how="inner")
print(f"Duplicate rows in the whole file: {cc.duplicated(subset=key).sum():,}")
print(f"Test rows with an exact copy in training (random split): {len(shared):,}")

# Check 2: adversarial validation, can a model tell training rows from test rows?
def adversarial_auc(train, test):
    X = pd.concat([train[FEATS], test[FEATS]])
    is_test = np.r_[np.zeros(len(train)), np.ones(len(test))]
    clf = xgb.XGBClassifier(n_estimators=200, max_depth=4, learning_rate=0.1, n_jobs=2, random_state=0)
    p = cross_val_predict(clf, X, is_test, cv=StratifiedKFold(5, shuffle=True, random_state=0),
                          method="predict_proba")[:, 1]
    return roc_auc_score(is_test, p)

cut = int(len(cc) * 0.8)
print(f"Adversarial ROC-AUC, random split: {adversarial_auc(tr, te):.3f}")
print(f"Adversarial ROC-AUC, time split:   {adversarial_auc(cc.iloc[:cut], cc.iloc[cut:]):.3f}")

# Check 3: single-feature screen, which column alone predicts the label best?
y = cc["Class"]
single = {c: roc_auc_score(y, cc[c]) for c in FEATS}
single = {c: max(a, 1 - a) for c, a in single.items()}
top = sorted(single.items(), key=lambda kv: -kv[1])[:5]
print("Strongest single features (ROC-AUC on their own):")
for c, a in top:
    print(f"  {c:<7}{a:.3f}")


Output:
Duplicate rows in the whole file: 9,144
Test rows with an exact copy in training (random split): 2,558
Adversarial ROC-AUC, random split: 0.499
Adversarial ROC-AUC, time split:   0.858
Strongest single features (ROC-AUC on their own):
  V14    0.949
  V4     0.938
  V12    0.937
  V11    0.918
  V10    0.914

Test 1: count duplicates across the split

A random split of this file puts 2,558 test rows next to an identical twin in training. Most of those are legitimate transactions, so the effect on fraud scores is modest here, but on a smaller or more repetitive dataset this kind of overlap can carry most of the score. Run the merge before you trust any random split.

Test 2: adversarial validation

Adversarial validation trains a classifier to guess whether a row came from the training set or the test set. If it cannot tell (ROC-AUC near 0.5), the two sets look alike. If it can, something differs between them.

The random split scores 0.499, as expected. The time split scores 0.858: later transactions are easy to tell apart from earlier ones. That does not mean the time split is wrong. It means the data drifts within two days, which is exactly why the random split flatters the model in Mistake 4. In a project where you expected train and test to look alike, a high adversarial score points you at the columns that differ, and those columns often turn out to be IDs, timestamps or features that changed definition.

Test 3: single-feature screen

Score every column on its own against the label. A real feature rarely beats 0.95 ROC-AUC alone on a hard problem. Here the best is V14 at 0.949, which is high but in line with what this dataset is known for, and several other PCA components sit close behind it, so no single column stands out. A column that reaches 0.99 by itself while the rest sit near 0.6 is the classic signature of target leakage, and it deserves a look at how and when it was recorded.

Data leakage vs overfitting

People often mix the two up, because both produce a model that does worse in real use than in development. They have different causes and different fixes.

OverfittingData leakage 
What goes wrongThe model memorises noise in the training dataThe evaluation lets the model see information it will not have later
What the scores showTraining score high, validation score lowerTraining and validation scores both high
Visible during development?Yes, as a train-validation gapUsually no
Typical fixMore data, regularisation, simpler modelChange the split, the pipeline or the features

The visibility row matters most. Overfitting shows up as a gap you can see, so you can tune against it. Data leakage closes the gap, because the validation set is contaminated too. Regularising a leaky model makes the numbers slightly worse without touching the cause.

Data leakage in deep learning and LLM projects

The same rules apply outside tabular data, with a few twists:

  • Image datasets often contain several photos of the same object, patient or scene. Split by that entity, as in Mistake 6, or near-identical images will sit on both sides.
  • Augmentation belongs to training only. Augmented copies of a test image placed in the training set are the image version of oversampling before the split.
  • Text datasets scraped from the web can overlap with public benchmarks. When a model was trained on pages that quote benchmark questions, its benchmark score partly measures recall. This is usually called benchmark contamination, and it is a form of train-test contamination at internet scale.
  • Fine-tuning data built by an LLM from your evaluation set leaks in the same way. Keep the evaluation questions away from every prompt used to generate training data.
  • Early stopping on the test set is tuning on the test set. Use a separate validation split for the stopping signal.

A checklist to prevent data leakage

Run through this data leakage checklist before you trust any validation score:

  1. Split first. Do nothing that looks at the data until the test set is set aside.
  2. Wrap every data-dependent step (scaling, imputation, encoding, feature selection, resampling) in a Pipeline.
  3. Use imbalanced-learn’s pipeline when resampling, so oversampling touches training folds only.
  4. Split by time for time-ordered data and by group when IDs repeat.
  5. For each feature, write down when its value becomes known and drop anything recorded after the prediction moment.
  6. Deduplicate before splitting, and check for near-duplicates in images and text.
  7. Tune on validation data or with nested cross-validation. Look at the test set once.
  8. Treat any surprisingly high score as a bug until you have explained it.
  9. Compare against a simple baseline. If logistic regression suddenly rivals a large model, look for a leak.
  10. After launch, compare live metrics with offline ones. A sharp drop is often the first sign of a leak that slipped through.

Here is the same advice as a table you can keep next to your notebook:

SituationWrongRight 
Scaling, imputing, encodingfit_transform on all rowsInside a Pipeline, fitted per fold
Feature selectionRank features on all rowsSelector inside the Pipeline
Class imbalanceOversample, then splitimbalanced-learn Pipeline, training data only
Time seriestrain_test_split(shuffle=True)Time cut-off, TimeSeriesSplit
Several rows per personKFoldGroupKFold or StratifiedGroupKFold
Hyperparameter searchPick best test scoreValidation set or nested CV

scikit-learn’s own guide to common pitfalls covers the preprocessing cases in more depth and is worth reading once.

How data leakage shows up in production

A leaky model usually fails in one of two ways after deployment. Either its accuracy drops sharply on day one, because a leaked feature is missing or different at prediction time, or it degrades over weeks, because a random split hid how quickly patterns change.

Both are expensive. The first wastes the launch. The second is worse, because the model looks fine at first and the drift is blamed on “changing data” rather than on the evaluation. Monitoring helps you notice: track the input feature distributions and, once labels arrive, the live precision and recall against your offline numbers.

Data leakage is also one reason I distrust leaderboards that report a single number. In our XGBoost vs LightGBM vs CatBoost benchmark, the choice of split moved scores by more than the choice of library. When you read a claim that one model beats another, ask how the data was split before you ask which model won.

FAQ

What is data leakage in simple terms?

Data leakage is when a model gets information during training or testing that it will not have when used for real. It makes the model look more accurate than it is, so the problem only appears after deployment.

What is the difference between target leakage and train-test contamination?

Target leakage means a feature contains information about the answer, such as a column recorded after the outcome. Train-test contamination means information from the test rows reaches training, for example by scaling, encoding or oversampling the whole dataset before splitting. Both inflate scores; they need different fixes.

Does using a Pipeline prevent all data leakage?

No. A scikit-learn Pipeline prevents contamination from preprocessing steps fitted on test data, which covers many cases. It cannot fix a leaky feature, a random split on time-ordered data, or duplicated rows across splits. Those need decisions about features and splitting strategy.

How do I know if my model has data leakage?

Look for scores that are unusually high, one feature dominating importance, near-identical cross-validation folds, or a large drop between offline and live performance. Then re-run the evaluation with a time-based or group-based split and with suspicious features removed, and see whether the score holds.

Is SMOTE data leakage?

SMOTE itself is not leakage. Applying it before the train-test split is, because synthetic rows are built from neighbours that may end up in the test set. Run SMOTE inside an imbalanced-learn pipeline so it only ever sees training data.

Make the honest number your default

Every leak in this article made a model look better, never worse. That bias is what makes data leakage dangerous: nobody goes looking for problems when the numbers are good. Split first, keep every fitted step inside a pipeline, match the split to how the data was generated, and ask of every feature when it becomes known. The resulting score will be lower and you can rely on it.

If you are building your first project, the machine learning roadmap for 2026 puts evaluation and leakage checks early, before model tuning, for exactly this reason.

About the author Aradhya Chaudhary

Data Scientist | Freelancer | Speaker & Writer skilled in programming, development and building AI/ML backed systems.

More from Aradhya
Keep reading

More in AI & ML

All of AI & ML →