Sub topic 9
Data leakage and how to avoid it
This chapter assumes you can use scikit-learn's fit, predict and Pipeline. It also assumes you know the train, validation and test split from earlier chapters, and that you know what k-fold cross-validation does. Data leakage is a common reason a model scores well in development and badly in production.
What leakage is
Data leakage means information that would not be available at prediction time influences training, tuning or model selection. The validation or test score is then measured on data the model has already "seen" in some indirect way. The score looks good, but it no longer estimates how the model will do on new data.
Leakage looks like a generalisation success. It is the opposite: the evaluation has failed, so you cannot tell whether the model overfits.
Common forms of leakage
| Form | How it happens | Remedy |
|---|---|---|
| Preprocessing leakage | A scaler, imputer or feature selector is fitted on all rows before splitting | Fit every step on training data only, using a `Pipeline` |
| Test-set tuning | Hyperparameters or model choice are adjusted after looking at test scores | Tune with validation data or cross-validation, and use the test set once |
| Duplicate or near-duplicate rows | The same example lands in both train and validation | Deduplicate before splitting |
| Group leakage | Rows from one patient, user or device appear on both sides | Split by group with `GroupKFold` |
| Temporal leakage | Future rows are used to predict the past | Split in time order with `TimeSeriesSplit` |
| Target leakage | A feature is computed from the label or only exists after the outcome | Remove the feature, or check when each feature becomes available |
Preprocessing leakage in practice
Fitting a StandardScaler on the full dataset lets the means and variances of the validation rows shape the training inputs. The effect is small for scaling and can be large for supervised steps such as feature selection.
The example below uses features that are pure noise and labels that are random. No model can truly predict them, so an honest accuracy is about 0.5.
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
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 1000))
y = rng.integers(0, 2, size=100)
# Wrong: the 20 "best" features are chosen using every label,
# including the labels of the rows that cross-validation later holds out.
X_leaky = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_leaky, y, cv=5).mean()
# Right: selection is refitted inside each fold, on that fold's training rows.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
clean = cross_val_score(pipe, X, y, cv=5).mean()
print("leaky accuracy:", round(leaky, 3))
print("clean accuracy:", round(clean, 3))The leaky score is well above 0.5, which is impossible for random labels. The pipeline score stays near 0.5. With 1000 features and only 100 rows, some features correlate with the labels by chance. Selecting them with the labels in view bakes that chance into the "model".
The rule is that anything that learns from data must be fitted inside the training portion of each split. That covers scalers, imputers, encoders, PCA, feature selectors and target encoders.
Tuning leaks too
Each time you look at a test score and change something, the test set becomes part of your tuning data. After enough rounds, the test score is optimistic. Two habits prevent this:
- Choose models and hyperparameters with cross-validation on the development set, as in the previous chapters.
- Keep the test set for a single final measurement. If it disappoints, accept the number or collect new data. Do not tune against it.
Cross-validation scores used for tuning are also slightly optimistic, because you pick the best of many candidates. This is another reason to keep a separate test set.
Splits that respect the data's structure
A random split assumes rows are independent. If they are not, validation rows can be near-copies of training rows, and the model looks better than it is.
import numpy as np
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 3))
y = rng.normal(size=100)
# 20 patients, 5 rows each. No patient may appear on both sides.
groups = np.repeat(np.arange(20), 5)
for train_idx, val_idx in GroupKFold(n_splits=4).split(X, y, groups):
assert set(groups[train_idx]).isdisjoint(groups[val_idx])
print("GroupKFold: no patient shared between train and validation")
# Rows are ordered by time. Validation must come after training.
for train_idx, val_idx in TimeSeriesSplit(n_splits=4).split(X):
assert train_idx.max() < val_idx.min()
print("train up to", train_idx.max(), "-> validate", val_idx.min(), "to", val_idx.max())GroupKFold keeps every group on one side of each split. TimeSeriesSplit always trains on the past and validates on the future, which matches how the model will be used.
Target leakage
Target leakage is harder to catch in code because the split is correct. The problem is a feature that encodes the answer. Examples include a "refund issued" column when predicting fraud, or a "discharge medication" field when predicting whether a patient will be admitted. Such features are available in the historical table but not when the real prediction is made.
For each feature, ask: at the moment of prediction, would I know this value? If not, remove it.
A checklist for avoiding leakage
- Split off the test set first, before any exploration that uses labels.
- Put every fitted preprocessing step inside a
Pipelineand pass the whole pipeline tocross_val_scoreorGridSearchCV. - Deduplicate, then split by group or by time when rows are not independent.
- Audit each feature for availability at prediction time.
- Use the test set once.
Exercise
A colleague standardises all 10,000 rows with StandardScaler().fit_transform(X), then runs 5-fold cross-validation and reports the score. Explain what leaks and how to fix it.
Show answer
The scaler computed its means and standard deviations using the rows that each fold later holds out for validation, so validation information shaped the training inputs. The effect is usually small for scaling but the evaluation is no longer clean. Fix it by building make_pipeline(StandardScaler(), model) and passing the pipeline to cross_val_score, so the scaler is refitted on each fold's training rows only.
Exercise
You are predicting customer churn from monthly records, with several rows per customer across 24 months. Which splitting strategy would you use, and why is a plain random split risky?
Show answer
Use a time-aware split such as TimeSeriesSplit so the model trains on earlier months and validates on later ones, and consider grouping by customer (for example with GroupKFold) so one customer's rows do not appear on both sides. A random split puts a customer's rows from adjacent months in both train and validation. The model can then recognise the customer instead of learning a general pattern, and it may also use future information to predict the past, so the score will be too high.