Sub topic 10
Avoiding data leakage
This chapter assumes you can split data with train_test_split, call fit and transform on a transformer, and read a basic scikit-learn script. It builds on the transformer methods from the previous chapter.
What leakage is
Data leakage happens when information from outside the training data influences the model during training. The model then looks better in evaluation than it will on new data. The test score no longer measures what you wanted it to measure.
The most common source in scikit-learn code is preprocessing. If you compute a mean, a variance, or a category list from all the rows, the test rows have already influenced the model. The test set is supposed to behave like data you have not seen yet.
The wrong way and the right way
A scaler learns two things in fit: the mean and the variance of each column. Those values belong to the training data. Fitting on the full dataset before splitting mixes test statistics into them.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
# Leaky: the scaler sees every row, including future test rows.
leaky_scaler = StandardScaler().fit(X)
# Correct: split first, then fit on the training rows only.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(scaler.mean_)The rule has two parts:
- Call
fitorfit_transformon training data only. - Call
transformon the test data, using the values learned from training.
Never call fit_transform on the test set. That would compute new statistics from test rows and apply them only there, so the two sets would be scaled differently.
Why a single split is not the only risk
Leakage also appears during cross-validation. Suppose you scale all of X once and then run cross_val_score on the scaled array. In each fold, the scaler has already seen the validation rows. The split is correct, but the preprocessing happened before it.
Other common sources include:
- Selecting features by looking at correlation with
yacross the whole dataset. - Filling missing values with a mean computed on all rows.
- Including a column that is only known after the outcome, such as a "refund issued" flag when predicting a purchase.
- Keeping duplicate or near-duplicate rows on both sides of the split.
The first three are fixed by the same principle: any step that learns from data must be fitted inside the training portion only. The last two need care in how you build the dataset.
The fix: put preprocessing inside a Pipeline
A Pipeline refits each step on the training portion every time it is fitted. Passing it to cross_val_score means the scaler is refitted on the training rows of each fold, and the validation rows are only transformed.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
scores = cross_val_score(pipe, X, y, cv=5)
print(scores.mean())You do not have to remember the order of fit and transform calls. The pipeline applies them correctly. The next chapter covers pipelines in more detail.
Quick checklist
- Split before any step that learns from data.
- Use
fiton training data only, andtransformeverywhere else. - Wrap preprocessing and the model in one
Pipeline. - Pass the pipeline, not pre-processed arrays, to cross-validation.
- Ask of each feature: would I know this value at prediction time?
Exercise
A colleague runs StandardScaler().fit_transform(X) on the whole dataset, then calls train_test_split and fits a model. What is wrong, and how would you fix it?
Show answer
The scaler computed its mean and variance using the test rows, so test information influenced training. Split first, fit the scaler on X_train only, and call transform on X_test. Better still, put the scaler and model in a Pipeline so the order is handled automatically.
Exercise
Why does passing a Pipeline to cross_val_score avoid leakage, while scaling X beforehand does not?
Show answer
The pipeline refits the scaler on the training rows of each fold, so validation rows never affect the learned mean and variance. Scaling beforehand fits the scaler on all rows, including every validation fold.