TExcelTAD

The Leakage Rules

Data leakage is any path by which information that would not be available at prediction time reaches the model during training or evaluation. Its symptom is always the same: a validation score that is better than the model will ever be in use. Leakage is the most common reason a model that "scored 0.95" disappoints in production, and it is easy to commit because every leaky step looks reasonable on its own. Every lesson in this course has pointed here; this lesson collects the rules in one place, shows the most dramatic leak in a lab, and ends with a checklist.

The rules

  1. Split before fitting anything. Decide the training, validation and test rows (or the cross-validation folds) first.
  2. Fit every data-dependent step on training data only: imputers, scalers, encoders (especially target encoding), feature selectors, dimensionality reduction, resamplers, thresholds.
  3. Apply the fitted steps unchanged to validation and test data (transform, never fit_transform).
  4. Keep related samples on one side: rows of the same patient, customer, device, video or near-duplicate go into the same split (group splits).
  5. Never use the future to predict the past: time-ordered splits, and features built only from information known at prediction time.

A sixth rule follows from the first five: use the test set once. Every decision taken after looking at test results quietly turns it into a validation set.

The lab: three leaks, three sizes

The lab scores the same procedure two ways, leaky and honest, and compares both with the score on fresh data from the same source (the number the estimate is supposed to predict). The default case is feature selection before the split: 50 rows, 500 features of pure noise, random labels. The 20 features most correlated with the label are picked using all 50 rows, and only then is a classifier cross-validated on them.

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)

With seed 1 the leaky estimate is 0.94, the honest one (selection repeated inside each training fold) 0.54, and fresh data gives 0.48: chance, since there is nothing to learn. Among 500 noise features, some are correlated with the 50 random labels by accident, and choosing them on all rows makes them "predict" the validation rows they were chosen on. Try other seeds: the leaky estimate stays between 0.84 and 0.94, while the honest one wanders between 0.38 and 0.66 around the 0.5 of chance (50 rows make every estimate noisy), and fresh data stays close to 0.5.

Switch to scaler before split: here the leaky and honest estimates are both 0.925 and fresh data gives 0.867. Fitting a scaler on all rows is a real leak (the mean and standard deviation include the test fold), but the effect on the estimate is usually small, as the lab says on screen. It is still wrong, and the same mistake with a step that learns more from the data (selection, target encoding, imputation with a model) is not small. Finally, random split of a time series gives R² = 0.991 leaky against -7.158 when the test days really come after the training days, and -0.981 on the next 40 days: a shuffled split lets the model interpolate between neighbouring days instead of forecasting.

The same leak in scikit-learn

The fix is structural: put the selector in a pipeline, and cross-validate the pipeline.

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 StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(60, 2000))                      # 2000 noise features
y = rng.permutation(np.repeat([0, 1], 30))           # random labels
cv = StratifiedKFold(5, shuffle=True, random_state=0)

X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)          # WRONG: uses all rows
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=cv)

pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=cv)                        # selection inside each fold

X_new = rng.normal(size=(1000, 2000)); y_new = rng.integers(0, 2, 1000)
fresh = pipe.fit(X, y).score(X_new, y_new)
print(f"selection before CV: {leaky.mean():.3f}")
print(f"selection inside CV: {honest.mean():.3f}")
print(f"on 1000 new rows:    {fresh:.3f}")
selection before CV: 0.933
selection inside CV: 0.517
on 1000 new rows:    0.488

The same story with scikit-learn's SelectKBest on 2,000 noise features: 0.933 when the selection saw all rows, 0.517 when it is refitted inside each training fold, 0.488 on 1,000 new rows. The pipeline version gives an estimate you can trust; the leaky version would have been a confident report of a model that does nothing.

Target leakage: a feature from the future

Not all leaks come from preprocessing. A target leak is a feature that is only known after the outcome, or is a consequence of it: chargeback_filed in a fraud model, discharge_medication in a model that predicts a diagnosis at admission, days_since_last_payment computed on the day of the export in a churn model. The split can be perfect and the score still meaningless. A practical detector: a single feature that predicts the label almost perfectly is a suspect until someone who knows the data explains it.

python · try it yourself
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.metrics import roc_auc_score

rng = np.random.default_rng(1)
n = 1500
amount = rng.lognormal(3.5, 1.0, n)
night = rng.integers(0, 2, n)
new_device = rng.integers(0, 2, n)
fraud = (rng.random(n) < 0.02 + 0.10 * night * new_device + 0.03 * (amount > 100)).astype(int)
chargeback = np.where(fraud == 1, rng.random(n) < 0.9, rng.random(n) < 0.01).astype(int)  # filed weeks later

clean = np.column_stack([amount, night, new_device])
leaky = np.column_stack([clean, chargeback])
for name, X in [("without chargeback", clean), ("with chargeback   ", leaky)]:
    auc = cross_val_score(RandomForestClassifier(n_estimators=100, random_state=0), X, fraud,
                          cv=5, scoring="roc_auc").mean()
    print(f"{name}: CV ROC AUC {auc:.3f}")

names = ["amount", "night", "new_device", "chargeback"]
single = {nm: round(roc_auc_score(fraud, leaky[:, j]), 3) for j, nm in enumerate(names)}
print("single-feature AUC:", single)
without chargeback: CV ROC AUC 0.597
with chargeback   : CV ROC AUC 0.934
single-feature AUC: {'amount': 0.535, 'night': 0.674, 'new_device': 0.653, 'chargeback': 0.936}

Without the leaky column, the honest features reach a cross-validated ROC AUC of 0.597: fraud here is hard to predict, as it often is. Adding chargeback lifts it to 0.934, and on its own chargeback has an AUC of 0.936, far above any honest feature (0.535 to 0.674). Nothing was wrong with the split; the feature simply does not exist yet when a transaction has to be approved or declined. Drop it, or rebuild every feature "as of" the moment of prediction.

The checklist

Before you trust a score, answer these for every feature and every step:

Question If the answer is "no"
Was the split made before any step was fitted? refit everything inside a pipeline
Is every fitted step (impute, scale, encode, select, reduce, resample, threshold) inside the pipeline that is cross-validated? move it in
Is every feature known at the moment the prediction will be made? drop it or rebuild it as of prediction time
Are rows of one entity (person, device, video, session) all on one side? use a group split
For temporal data, is all training data older than all test data, with a gap for windowed features? use a time split
Are there near-duplicates across the split? deduplicate or group them
Has the test set been used for any decision? set aside a new test set if you can, or report the score as optimistic
Is the score suspiciously good, or one feature suspiciously strong? investigate before celebrating

Pitfalls

  • "It's only the scaler": small leaks are still leaks, and the habit carries over to steps where the leak is large.
  • Leaks in the data source: a table exported today has columns updated after the event; ask how each column is produced and when.
  • Leaks through tuning: many rounds of "try, look at the validation score, adjust" overfit the validation set; keep a test set aside for the end.
  • Copy-pasting fit_transform on test data: test data is only ever transformed.

Practice

  1. A churn model uses number_of_support_calls, counted over the customer's whole history up to the export date. Customers who churned in March have their calls counted until March; customers still active, until the export in June. Is this a leak?
Answer

Yes, a subtle target leak: active customers had more time to make calls, so the feature partly measures "still a customer", which is the label. Count calls in a fixed window before a fixed prediction date for everyone (for example the 90 days before 1 March), and predict churn after that date.

  1. Which of these must be fitted inside the cross-validation pipeline: a SimpleImputer with the median, pd.get_dummies on a column with fixed known categories, SelectKBest, a log transform np.log1p?
Answer

The imputer (it learns medians) and SelectKBest (it learns which features to keep) must be fitted inside. np.log1p learns nothing from the data, so it cannot leak. get_dummies with a fixed, known category list learns nothing either, but OneHotEncoder in the pipeline is safer, because it also handles categories that appear only in new data.

Test yourself

In the lab's default case, why is the leaky estimate 0.94 on pure noise?

  1. The classifier is very good
  2. The 20 features were chosen using the validation rows too, so they fit those rows by chance
  3. The labels are not random
  4. Cross-validation was not used

Which step can be applied to all rows before splitting without leaking?

  1. Fitting a StandardScaler
  2. Choosing the top features by correlation with the label
  3. A fixed formula such as np.log1p(x) that learns nothing from the data
  4. Target encoding

A feature alone predicts the label with AUC 0.95. What should you do first?

  1. Celebrate
  2. Check when and how it is produced; it may only exist after the outcome
  3. Remove all other features
  4. Scale it

Which rule protects against learning from tomorrow's data?

  1. Stratify the split
  2. Train on earlier dates and test on later ones, with features known at prediction time
  3. Use more folds
  4. Oversample the test set