TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Data Leakage in Evaluation

Data Leakage in Evaluation

A model that scores 0.97 in validation and 0.60 in production was usually not unlucky. Most often some information that will not exist at prediction time, or that comes from the evaluation data itself, slipped into training. That is data leakage, and its signature is an evaluation score that is too good to be true. The Leakage Rules in Data Preparation lists the rules for building pipelines; this lesson is about recognising leakage from the evaluation side: what inflated scores look like, how to measure the inflation, and how to make the estimate honest again.

Five kinds of leakage

Kind What happens Typical example
Target leakage a feature is a consequence or a proxy of the label "refund issued" when predicting churn; "treatment given" when predicting diagnosis
Preprocessing leakage a step fitted on all data before splitting (scaler, imputer, encoder, feature selection) selecting the 20 best features of 2000 on the full data set
Train-test contamination the same or nearly the same example on both sides several photos of one patient, duplicated rows, augmented copies
Temporal leakage the model sees the future random split of a time series; features computed with a window that reaches past the prediction time
Tuning on the test set the test set chooses a model or a threshold trying 50 configurations and reporting the best test score

In each case the score is optimistic by an unknown amount. The fix is always the same principle: everything the model learns, including preprocessing and choices, must come from data that is on the training side of the split, and from information available at prediction time.

The lab: three leaks side by side

The lab builds a leaky and an honest pipeline and scores both, plus the score on genuinely new data. Start with feature selection (the default). With seed 1, 50 rows of 500 pure-noise features with random labels give a leaky cross-validated accuracy of 0.94, an honest one of 0.54 and 0.48 on new data: chance is 0.5, so the leaky number is pure fiction. Switch Leak to "scaler before split": the effect is small, as the lab says, because a mean and a standard deviation carry little information about individual validation rows. Then try the random split of a time series.

Leaky: test rows shape a stepall datapick 20 featuressplit 5 foldsscoreHonest: test rows unseen until scoringall datasplit 5 foldspick 20 on trainscoreThe 20 features were chosen because theyfit the test rows by chance: the scoreis pure memorised noise.Validation accuracy00.250.50.7510.94leaky0.54honest0.48new data- - chance (random labels)

Preprocessing leakage in code

The same trap as the lab's, larger: 100 rows, 2000 random features, random labels. Feature selection before cross-validation sees the validation folds' labels; inside a Pipeline it is refitted on each training fold only.

python · try it yourself
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))                  # pure noise
y = rng.integers(0, 2, 100)                       # random labels: true accuracy is 0.5
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)          # LEAK: uses every label
leaky = cross_val_score(LogisticRegression(), X_sel, y, cv=cv)
honest = cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression()), X, y, cv=cv)
print(f"selection before CV : {leaky.mean():.3f} +/- {leaky.std():.3f}")
print(f"selection inside CV : {honest.mean():.3f} +/- {honest.std():.3f}")
selection before CV : 0.810 +/- 0.073
selection inside CV : 0.520 +/- 0.051

Selection before CV reports 0.810, a respectable-looking model, on data with no signal at all. With 2000 noise features, some are correlated with these 100 particular labels by chance; choosing them with every label and then "validating" on those same labels is circular. Inside the pipeline the estimate drops to 0.520, chance level, which is the truth. Note how plausible the leaky number is: not 1.0, just good enough to be believed.

Target leakage: a feature from the future

Target leakage does not need a bug in the pipeline; it is in the data. A churn table has three honest behaviour features and one column, closure_request, that the support system fills in when a customer asks to close the account, which mostly happens after they have decided to leave. A quick screen that scores each feature alone by its ROC-AUC finds it:

python · try it yourself
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(1)
n = 3000
X = rng.normal(size=(n, 3))                                   # usage, tenure, support tickets
logit = -1.5 + 0.8 * X[:, 0] - 0.6 * X[:, 1] + 0.5 * X[:, 2]
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
closure_request = np.where(rng.random(n) < 0.9, churn, 1 - churn)     # recorded after the decision
X_all = np.column_stack([X, closure_request])
names = ["usage", "tenure", "tickets", "closure_request"]

X_tr, X_te, y_tr, y_te = train_test_split(X_all, churn, test_size=0.3, random_state=0, stratify=churn)
print("single-feature AUC on the training part:")
for j, name in enumerate(names):
    auc = roc_auc_score(y_tr, X_tr[:, j])
    print(f"  {name:16s} {max(auc, 1 - auc):.3f}")
for cols, label in [([0, 1, 2, 3], "with closure_request"), ([0, 1, 2], "without it")]:
    m = LogisticRegression().fit(X_tr[:, cols], y_tr)
    print(f"test AUC {label:21s} {roc_auc_score(y_te, m.predict_proba(X_te[:, cols])[:, 1]):.3f}")
single-feature AUC on the training part:
  usage            0.680
  tenure           0.645
  tickets          0.621
  closure_request  0.906
test AUC with closure_request  0.944
test AUC without it            0.785

The behaviour features score 0.62 to 0.68 alone; closure_request scores 0.906. With it the test AUC is 0.944, without it 0.785. The 0.944 is real on this test set, but it will not survive deployment: when the model has to make its prediction (say a month ahead, so the retention team can act), the closure request does not exist yet. The honest model is the one without it, 0.785. No split strategy can catch this kind of leak; only knowing when each column is recorded can.

Contamination: the same patient twice

A clinic has 3 scans per patient, 100 patients, and the label (healthy or not) is a property of the patient. Scans of one patient are nearly identical. Here the label has no relation to the features at all, so the true accuracy of any model is 0.5. A random K-fold puts scans of the same patient on both sides; a 1-nearest-neighbour classifier then just finds the sibling scan:

python · try it yourself
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score, KFold, GroupKFold

rng = np.random.default_rng(2)
patients = rng.normal(size=(100, 10))                         # one feature vector per patient
labels = rng.integers(0, 2, 100)                              # unrelated to the features
X = np.repeat(patients, 3, axis=0) + 0.05 * rng.normal(size=(300, 10))   # 3 near-identical scans
y = np.repeat(labels, 3)
groups = np.repeat(np.arange(100), 3)

knn = KNeighborsClassifier(n_neighbors=1)
random_cv = cross_val_score(knn, X, y, cv=KFold(5, shuffle=True, random_state=0))
group_cv = cross_val_score(knn, X, y, cv=GroupKFold(5), groups=groups)
print(f"random K-fold : {random_cv.mean():.3f}")
print(f"group K-fold  : {group_cv.mean():.3f}")
random K-fold : 0.960
group K-fold  : 0.387

The random split reports 0.960 on labels that are pure noise. With groups kept together the score falls to 0.387, which is chance level for this tiny problem: the 1-NN model is guessing (see the practice question for why it lands that far from 0.5). The same contamination happens with duplicated rows, with augmented copies of an image added before the split, and with the same user's sessions on both sides.

Temporal leakage

When rows are ordered in time and the model will predict the future, a random split lets it interpolate between neighbouring days it has seen, a much easier task than extrapolating. The lab's third mode shows this with a random walk: the random split looks excellent, the forward-in-time evaluation does not. Time-Series Backtesting shows how to evaluate properly. Features need the same care: a "30-day average" must be computed from the 30 days before the prediction time, not centred on it.

A leakage checklist for any evaluation

  1. Too good to be true? Compare with a simple baseline and with published results. A jump from 0.75 to 0.98 deserves suspicion before celebration.
  2. Screen single features. A lone feature with AUC near 1 is either a breakthrough or a leak; ask when and how it is recorded.
  3. Pipeline check. Every fitted step lives inside the Pipeline that cross-validation clones.
  4. Split by the right unit. Patients, users, sessions, documents, time: whatever repeats must not cross the split (Stratified and Group Cross-Validation).
  5. Look for duplicates across train and test (exact and near-duplicate hashes).
  6. The test set is used once. Choices are made on validation folds (nested CV).

Practice

  1. A model predicting hospital readmission uses the feature "number of follow-up appointments booked". Leak or not?
Answer

It depends on when the feature is known. If appointments are booked at discharge, before the prediction is made, it is legitimate. If the count includes appointments booked later (often because the patient was readmitted), it is target leakage. Always ask: what is the value of this feature at the moment of prediction?

  1. You standardise the whole data set, then run 5-fold CV. The lab says the effect is small. Why fix it anyway?
Answer

Because the effect is small only for a mean and a standard deviation on enough data. The same habit with feature selection, target encoding or oversampling produces large leaks, and a pipeline that is correct by construction removes the whole class of bugs.

  1. In the contamination example, the group split gives 0.387. If the model is guessing, why is it so far from 0.5?
Answer

The 300 predictions are not 300 independent guesses. The three scans of a patient almost always find the same nearest patient in the training folds, so they are right or wrong together: there are effectively only 100 independent guesses, and the accuracy of 100 coin flips has a standard deviation of 0.25/100=0.05\sqrt{0.25 / 100} = 0.05. A result 0.11 below 0.5 is unusual but possible; with another seed it lands elsewhere around 0.5. The random split's 0.960 is far outside that range.

Test yourself

Feature selection on the full data set, then cross-validation. What kind of leakage is this?

  1. Target leakage
  2. Preprocessing leakage
  3. Temporal leakage
  4. No leakage, selection is unsupervised

Several images of the same patient are split at random between training and test. What is the fix?

  1. Stratify by label
  2. Split by patient (group K-fold)
  3. Use more folds
  4. Standardise inside the pipeline

A single feature reaches a ROC-AUC of 0.95 alone, while all others are below 0.65. What is the first thing to check?

  1. Whether the model needs more trees
  2. When and how that feature is recorded: could it be a consequence of the label?
  3. Whether to remove the other features
  4. The learning rate

In the lab with seed 1, feature selection before the split gives 0.94, honest CV 0.54 and new data 0.48. Which estimate should you report?

  1. 0.94
  2. The honest 0.54 (with its uncertainty): it is close to what new data gives
  3. The average of the three
  4. None: the model is broken