Sub topic 9
Data leakage and how to avoid it
This chapter assumes you know train, validation, and test splits, k-fold cross-validation, and scikit-learn's fit and predict. Data leakage means information from outside the training data influences the model or the choices made about it. Your scores then look better than the model will perform on new data.
Why leakage is dangerous
A leaked score is not a noisy estimate. It is a biased one, and it is biased upward. The model looks good in development and fails in production. Nothing in the code raises an error, so you have to prevent leakage by design.
Common sources
- Preprocessing fitted on all data. Computing the mean and standard deviation for scaling on the full dataset lets the validation rows influence the transformation.
- Tuning on the test set. If you pick a regularisation strength by checking test error, the test set has become a validation set. Its score is now optimistic.
- Duplicates or related rows across splits. The same patient, customer, or near-identical record in both train and validation lets the model recall instead of generalise.
- Features that encode the label. A column recorded after the outcome, such as "refund issued" when predicting churn, gives the answer away.
- Time order ignored. Shuffling time series data lets the model train on the future to predict the past.
The scaling mistake
The leaky version fits the scaler before splitting:
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 3))
X_scaled = StandardScaler().fit_transform(X) # leaks: uses all rows
X_train, X_val = train_test_split(X_scaled, test_size=0.3, random_state=0)The scaler has seen the validation rows. The effect is often small for scaling, but the same pattern with feature selection or target-based encoding can inflate scores a lot.
The fix: keep preprocessing inside a pipeline
A pipeline refits every step on the training portion only. With cross-validation, each fold is scaled using only its own training rows.
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5))
y = 2 * X[:, 0] + rng.normal(0, 0.5, size=100)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
print(round(-scores.mean(), 3))A checklist
- Split first, before any step that learns from the data.
- Put every learned step (scaling, imputation, feature selection, encoding) in a pipeline.
- Tune only with validation data or cross-validation.
- Use the test set once, at the end.
- Group related rows together with
GroupKFold, and use time-ordered splits for time series. - Treat a suspiciously high score as a warning and inspect your features.
Exercise
A colleague standardises the full dataset, then runs 5-fold cross-validation to choose a ridge alpha. Which part is leaky, and how do you fix it?
Show answer
The scaler was fitted on all rows, so each validation fold influenced the mean and standard deviation used to scale its own training data. Fix it by putting StandardScaler and Ridge in one pipeline and passing the pipeline to crossvalscore, so scaling is refit on each fold's training part.