GyaanStack. Blog

Articles / machine-learningpythonevals

Data leakage in machine learning: four leaks, measured, and how to fix each

Four kinds of data leakage reproduced in scikit-learn with real numbers (0.815 accuracy on random labels), then the fixes and a checklist to run before launch.

By Raghunath · · 16 min read

Data leakage is when a model gets to see, during training or validation, information it will not have at prediction time. The validation score goes up, and the production score does not follow it. scikit-learn's common pitfalls page gives the rule in one line: never call fit on the test data. Leakage is still easy to commit, because most leaks never call fit on a test set directly. They hide in a preprocessing step, a column filled in after the event, or a split that ignores time or identity.

This guide reproduces four leaks in about 150 lines of Python and measures each one both ways, leaky and honest. The numbers below are real output from one run with scikit-learn 1.9.1, pandas 3.1.1 and NumPy 2.5.5 on Python 3.15. The data is synthetic so the true answer is known in advance: when a model scores 0.815 on labels drawn by coin flip, there is no argument about whether that number is inflated.

Leak Leaky score Honest score Fix
Feature selection before the split 0.815 accuracy 0.465 accuracy Pipeline
Post-outcome feature (target leak) 0.951 AUC 0.734 AUC Drop the column; check timestamps
Shuffled split on a time series 0.942 R² -0.726 R² TimeSeriesSplit
Same patient in train and test 0.999 AUC 0.554 AUC GroupKFold

Where leaks enter a pipeline#

 raw data ──► clean / impute ──► features ──► select / scale ──► split ──► fit ──► score
     │              │                │               │              │
     │              │                │               │              └─ leak 3: random split on time-ordered rows
     │              │                │               │              └─ leak 4: same user/patient on both sides
     │              │                │               └─ leak 1: statistics computed on ALL rows, test included
     │              │                └─ leak 2: a column written after the outcome happened
     │              └─ leak 1 again: imputation means taken from the full table
     └─ leak 4 again: duplicate rows from a bad join or a re-ingest

 Rule of thumb: everything to the left of "split" must be either
 row-local (no statistics across rows) or moved inside the pipeline.

Leaks 1, 3 and 4 are about how you split and fit. Leak 2 is about what the data means, and no splitter catches it.

Setup#

python3 -m venv .venv
.venv/bin/pip install scikit-learn pandas numpy

All four demos share these imports and a fixed seed:

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import (GroupKFold, KFold, StratifiedKFold,
                                     TimeSeriesSplit, cross_val_score)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

SEED = 42

Leak 1: preprocessing fitted before the split#

The test: 200 rows, 10,000 columns of Gaussian noise, and labels from a coin flip. No model can beat 50% here. The leaky version picks the 20 columns most correlated with the label using all 200 rows, then cross-validates a logistic regression on those 20. The honest version puts the selector inside a pipeline so it is refit on each training fold and never sees that fold's validation rows.

def leak_1_preprocessing():
    """Feature selection fitted on all rows before cross-validation."""
    rng = np.random.default_rng(SEED)
    X = rng.normal(size=(200, 10_000))      # pure noise
    y = rng.integers(0, 2, size=200)        # random labels: true accuracy is 50%
    cv = StratifiedKFold(5, shuffle=True, random_state=SEED)

    # Leaky: pick the 20 "best" columns using every row, then cross-validate.
    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 lives inside the pipeline, so it is refit per fold.
    pipe = make_pipeline(SelectKBest(f_classif, k=20),
                         LogisticRegression(max_iter=1000))
    honest = cross_val_score(pipe, X, y, cv=cv)
    print(f"[1] select-then-split  leaky acc={leaky.mean():.3f}  "
          f"pipeline acc={honest.mean():.3f}")

    # Scaling before the split, for comparison: usually a tiny effect.
    Xs = rng.normal(size=(500, 20))
    ys = (Xs[:, 0] + rng.normal(size=500) > 0).astype(int)
    leaky_s = cross_val_score(LogisticRegression(),
                              StandardScaler().fit_transform(Xs), ys, cv=cv)
    honest_s = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()),
                               Xs, ys, cv=cv)
    print(f"[1] scale-then-split   leaky acc={leaky_s.mean():.3f}  "
          f"pipeline acc={honest_s.mean():.3f}")

Output:

[1] select-then-split  leaky acc=0.815  pipeline acc=0.465
[1] scale-then-split   leaky acc=0.692  pipeline acc=0.692

81.5% on pure noise. With 10,000 candidate columns and only 200 rows, some columns line up with the random labels by chance. Picking them with the validation rows included bakes those chance alignments into every fold. The pipeline result, 46.5%, is what coin-flip labels should give.

Fitting a StandardScaler on the full table before the split, by contrast, changed nothing here to three decimals. A mean and a standard deviation from 500 rows barely move when you add or remove 100 of them. That is why tutorials that warn about the scaler leak and then show a 0.002 difference leave readers unconvinced. The size of a preprocessing leak depends on how much the step learns from the data. Supervised steps that look at y (feature selection, target encoding, oversampling with SMOTE) leak the most. Unsupervised statistics on large tables leak the least. Put all of them inside the pipeline anyway, because you cannot know in advance which one will bite on your data.

The fix is the same for every step: wrap preprocessing and model in a Pipeline (or ColumnTransformer inside one, see pipelines and composite estimators) and pass the whole pipeline to cross_val_score or GridSearchCV. Then every fit happens on training rows only.

Leak 2: a feature written after the outcome#

Target leakage is a column whose value depends on the label. The classic case is churn. A customer phones to cancel, the CRM stamps their last support ticket as "cancellation", and a snapshot of the table taken later has that stamp sitting next to churned = 1. The model learns that cancellation tickets predict cancellations. In production you score customers before they call, so the column is never set and the model loses its best feature.

The synthetic churn table has four honest features with modest signal and one post-outcome flag that is set for 85% of churners and 2% of everyone else:

def make_churn(n=5000, seed=SEED):
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "tenure_months": rng.integers(1, 72, n),
        "monthly_charge": rng.normal(70, 20, n).round(2),
        "logins_last_30d": rng.poisson(12, n),
        "support_calls_90d": rng.poisson(1.5, n),
    })
    logit = (-1.0 - 0.04 * df.tenure_months + 0.02 * (df.monthly_charge - 70)
             - 0.08 * df.logins_last_30d + 0.35 * df.support_calls_90d)
    df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    # Written by the CRM when a customer phones to cancel, i.e. AFTER the outcome.
    df["last_ticket_is_cancel"] = np.where(
        df.churned == 1, rng.random(n) < 0.85, rng.random(n) < 0.02).astype(int)
    return df


def single_feature_auc(df, target):
    """Leak scan: how well does each column alone rank the target?"""
    out = {}
    for col in df.columns.drop(target):
        auc = roc_auc_score(df[target], df[col])
        out[col] = max(auc, 1 - auc)
    return pd.Series(out).sort_values(ascending=False).round(3)


def leak_2_target():
    df = make_churn()
    y = df.pop("churned")
    cv = StratifiedKFold(5, shuffle=True, random_state=SEED)
    rf = RandomForestClassifier(300, min_samples_leaf=5, random_state=SEED)
    leaky = cross_val_score(rf, df, y, cv=cv, scoring="roc_auc")
    honest = cross_val_score(rf, df.drop(columns="last_ticket_is_cancel"), y,
                             cv=cv, scoring="roc_auc")
    print(f"[2] target leak        leaky AUC={leaky.mean():.3f}  "
          f"honest AUC={honest.mean():.3f}")
    print("[2] single-feature AUC scan:")
    print(single_feature_auc(df.assign(churned=y), "churned").to_string())

Output:

[2] target leak        leaky AUC=0.951  honest AUC=0.734
[2] single-feature AUC scan:
last_ticket_is_cancel    0.916
tenure_months            0.706
support_calls_90d        0.642
monthly_charge           0.603
logins_last_30d          0.580

A Pipeline would not have helped. Cross-validation was done correctly and the 0.951 is a fair estimate of how the model does on data with that column filled in. The leak is in the data, so the fix is in the data: drop the column, or rebuild it as of the prediction date (for example "number of tickets in the 90 days before the scoring date").

The single-feature scan is a cheap way to find candidates. Score each column alone against the label; anything far above the rest is either your best feature or a leak, and you need to know which before launch. Here one column alone ranks churners at 0.916 AUC while the next best is 0.706. That gap is the signal to go and ask the team that owns the CRM when the field gets written. Tree feature importances or permutation importance show the same thing after training, but the one-column AUC needs no model and runs in seconds.

The 0.734 is the number to plan around. Churn, fraud and click prediction are noisy problems; on tabular data like this, an AUC in the 0.7 to 0.85 range is normal. A score in the high 0.9s on one of them should start an investigation, not a launch.

Leak 3: a shuffled split on a time series#

Here the task is daily sales for two years. Demand drifts as a random walk, weekends add 15 units, and temperature adds a seasonal term. Features are the day number, the weekday and the temperature. A random forest is cross-validated twice: once with shuffled KFold, once with TimeSeriesSplit, which always trains on the past and tests on the block that follows. The gap=7 argument drops the week between each training and test block, so the last training day is not right next to the first test day.

def make_daily_sales(days=730, seed=SEED):
    rng = np.random.default_rng(seed)
    t = np.arange(days)
    level = 200 + np.cumsum(rng.normal(0, 4, days))     # drifting demand
    weekday = t % 7
    temp = 25 + 6 * np.sin(2 * np.pi * t / 365) + rng.normal(0, 1.5, days)
    sales = level + 15 * (weekday >= 5) + 1.5 * (temp - 25) + rng.normal(0, 5, days)
    return pd.DataFrame({"day_index": t, "weekday": weekday,
                         "temperature": temp.round(1), "sales": sales.round(1)})


def leak_3_temporal():
    df = make_daily_sales()
    X, y = df.drop(columns="sales"), df.sales
    rf = RandomForestRegressor(300, random_state=SEED)
    leaky = cross_val_score(rf, X, y, cv=KFold(5, shuffle=True, random_state=SEED),
                            scoring="r2")
    honest = cross_val_score(rf, X, y, cv=TimeSeriesSplit(n_splits=5, gap=7),
                             scoring="r2")
    print(f"[3] temporal           shuffled KFold R2={leaky.mean():.3f}  "
          f"TimeSeriesSplit R2={honest.mean():.3f}")
    print("[3] TimeSeriesSplit fold R2:", np.round(honest, 2))

Output:

[3] temporal           shuffled KFold R2=0.942  TimeSeriesSplit R2=-0.726
[3] TimeSeriesSplit fold R2: [-0.15  0.22  0.15 -0.02 -3.83]

With a shuffled split, nearly every test day has its neighbours from the day before and the day after in the training set. The forest uses day_index to look up those neighbours and interpolates between them. That gives an R² of 0.942, but only because the model is filling gaps inside a period it has already seen. Forecasting means extrapolating past the last day you have, and trees cannot extrapolate: for any day beyond the training range they predict roughly the level of the last training days. Once demand drifts, the error grows, which is what the last fold shows at -3.83. An R² below zero means the model did worse than predicting the test block's own mean.

The negative score points at the fix. day_index is a trap feature, and the model needs lagged sales (yesterday, same day last week) computed only from data before the prediction day. When you build those lags, compute them with shift on the sorted series, never with a centred rolling window, which pulls in future values.

Also look at the spread across folds. Per-fold scores from TimeSeriesSplit show how performance changes as the data drifts, which a single mean hides.

Leak 4: the same entity on both sides of the split#

Patients with several scans, customers with many orders and users with many sessions all produce correlated rows. If one patient's scans land in both train and test, the model can score well by recognising the patient instead of learning the condition. Exact duplicate rows from a bad join or a double ingest are the extreme case of the same problem.

In this demo, 150 patients each have 8 scans. Each patient has a stable 20-number "fingerprint", the label is per patient, and only one feature carries a weak signal that would carry over to a new patient.

def make_scans(patients=150, per_patient=8, seed=SEED):
    """Several scans per patient; most of the label is patient-specific."""
    rng = np.random.default_rng(seed)
    rows, groups, labels = [], [], []
    for p in range(patients):
        fingerprint = rng.normal(size=20)          # stable per-patient traits
        label = rng.integers(0, 2)
        for _ in range(per_patient):
            x = fingerprint + rng.normal(scale=0.3, size=20)
            x[0] += 0.4 * label                    # weak signal that generalises
            rows.append(x); groups.append(p); labels.append(label)
    return np.array(rows), np.array(labels), np.array(groups)


def leak_4_groups():
    X, y, g = make_scans()
    rf = RandomForestClassifier(300, random_state=SEED)
    leaky = cross_val_score(rf, X, y, cv=KFold(5, shuffle=True, random_state=SEED),
                            scoring="roc_auc")
    honest = cross_val_score(rf, X, y, cv=GroupKFold(5), groups=g, scoring="roc_auc")
    print(f"[4] group leak         row KFold AUC={leaky.mean():.3f}  "
          f"GroupKFold AUC={honest.mean():.3f}")

Output:

[4] group leak         row KFold AUC=0.999  GroupKFold AUC=0.554

A near-perfect 0.999 collapses to 0.554 once each patient's scans stay on one side. GroupKFold takes a groups array and guarantees no group appears in both the training and validation folds. If classes are imbalanced, StratifiedGroupKFold does the same while keeping class ratios similar across folds. The hard part is choosing the group: patient, not scan; household, not account, if one household shares a device; author, not document. Pick the unit you will see new examples of in production.

For the duplicate case, hash the rows and count how many test rows already exist in train. The same few lines tell you how many entities sit on both sides of a plain random split:

from sklearn.model_selection import train_test_split


def row_overlap(train: pd.DataFrame, test: pd.DataFrame) -> int:
    train_hashes = set(pd.util.hash_pandas_object(train, index=False))
    return int(pd.util.hash_pandas_object(test, index=False).isin(train_hashes).sum())


def group_overlap(train_groups, test_groups) -> int:
    return len(set(train_groups) & set(test_groups))


rng = np.random.default_rng(0)
df = pd.DataFrame(rng.integers(0, 5, size=(1000, 4)), columns=list("abcd"))
df["customer_id"] = rng.integers(0, 300, 1000)
df = pd.concat([df, df.sample(100, random_state=0)])   # 100 copied rows, a common ETL bug
train, test = train_test_split(df, test_size=0.2, random_state=0)
print("exact duplicate rows in test:", row_overlap(train, test), "of", len(test))
print("customers on both sides:", group_overlap(train.customer_id, test.customer_id),
      "of", test.customer_id.nunique())
exact duplicate rows in test: 41 of 220
customers on both sides: 143 of 147

With 100 copied rows in 1,100, a random 80/20 split put 41 copies in the test set whose twin was in training. And 143 of the 147 customers in the test set also appear in training. Both counts should be zero before you trust a score. hash_pandas_object only catches exact copies; near-duplicates such as resized images or lightly edited text need embeddings or perceptual hashes. The data augmentation post has an embedding-based version for text.

Why the leaky numbers all look so reasonable#

Every leaky score in this guide came out of standard, correct-looking code. cross_val_score ran, the folds were stratified, the seeds were fixed. A code review that checks syntax and API use would pass all four. What went wrong each time is a mismatch between how the validation rows relate to the training rows and how production rows will relate to them:

  • Leak 1: validation rows influenced which features exist. Production rows will not.
  • Leak 2: validation rows carry a field that production rows will not have yet.
  • Leak 3: validation rows sit between training rows in time. Production rows come after all of them.
  • Leak 4: validation rows belong to entities the model already saw. Production rows mostly will not.

So the question to ask of any validation setup is "does a validation row look like a row I will score next month, as of the moment I score it?" If not, the score answers a different question from the one you care about.

This is not only an industry problem. The Princeton reproducibility project keeps a running list of published papers where errors, data leakage among them, were later found; at the time of writing it counts 41 papers from 30 fields, collectively affecting 648 papers. Their Patterns paper gives a fuller taxonomy of leakage types than the four covered here.

Leakage checklist#

Run through this before you report a number or ship a model.

Splitting

  • [ ] Every preprocessing step that computes statistics across rows (impute, scale, encode, select, resample) is inside a Pipeline that is passed to cross-validation or search.
  • [ ] The test set was split off before any exploration, and hyperparameter search used only training folds. Tuning on the test set is leakage too.
  • [ ] Time-ordered data uses TimeSeriesSplit (with a gap if labels take time to settle) or a fixed date cutoff, for example train on January to August and test on September.
  • [ ] Rows that share an entity are split with GroupKFold or StratifiedGroupKFold, and the group is the unit you will see new instances of in production.
  • [ ] Exact and near-duplicate overlap between train and test is counted and is zero.

Features

  • [ ] For each column, you know when it gets written relative to the prediction moment. Ask the owning team if the schema does not say.
  • [ ] Features are rebuilt "as of" the prediction date: point-in-time joins, lags with shift, no centred windows, no aggregates that include the label period.
  • [ ] Any ID, timestamp or row number used as a feature has a reason to be there.
  • [ ] The single-feature AUC (or correlation) scan has no outlier you cannot explain.

Sanity checks on the score

  • [ ] The score is in a plausible range for the problem. Near-perfect results on churn, fraud or forecasting are a reason to dig.
  • [ ] Re-running the whole pipeline, preprocessing included, on shuffled labels gives chance-level performance. If it does not, some step outside the folds is seeing the labels (leak 1 above would fail this test).
  • [ ] Per-fold scores are reported, not only the mean.
  • [ ] After launch, the production metric is compared with the validation estimate on the first few weeks of real outcomes. A large gap means a leak, a drift, or both.

The pipeline and the splitters handle the mechanical leaks. Target leaks come from not knowing how the data was produced, so the most useful step on that list is the conversation with whoever owns each table. For the wider set of checks that sit around a model in production, see MLOps vs LLMOps. If you need a reminder of what an honest held-out comparison looks like when the model is an LLM, the Hugging Face encoder vs LLM classification post runs one end to end.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.