Sub topic 11
Fitting preprocessing on training data only
This chapter assumes you can split data with train_test_split, know what cross-validation does, and have used scikit-learn estimators with fit and predict.
Why preprocessing can leak
Many preprocessing steps learn something from data. A scaler learns a mean and a standard deviation. An imputer learns a median. A feature selector learns which columns look useful. These steps have a fit stage, so they are models too.
If you fit them on all rows before splitting, the test rows influence the numbers used to transform the training rows. The model never sees test labels, but it sees a summary of the test features. That is data leakage, and it makes scores look better than they will be on new data.
Leaky versus correct scaling
The rule is to split first, fit on the training split, and only apply (transform) to the test split.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
# Leaky: statistics from the test rows influence the training features.
X_scaled_leaky = StandardScaler().fit_transform(X)
X_train_l, X_test_l, y_train_l, y_test_l = train_test_split(
X_scaled_leaky, y, test_size=0.2, random_state=42
)
# Correct: split first, learn scaling statistics from the training set only.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)In the correct version the test data is scaled with the training mean and standard deviation. Its own scaled mean will not be exactly zero. That is expected, because at deployment you will also only have the training statistics.
The cross-validation trap
Fitting by hand works for one split. Cross-validation is harder. If you scale the training set once and then run cross-validation on the scaled data, every validation fold has already influenced the scaler. The leak is smaller than with the test set, but it still biases the scores you use to pick models.
Use a pipeline
A pipeline chains preprocessing and the model into one estimator. When you call fit on it, every step is fit on the data you give it. Cross-validation then refits the whole chain on the training folds of each round and applies it to the held-out fold.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv)
print("CV accuracy:", scores.mean())
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))Only X_train enters cross-validation. The test set is scored once, at the end.
Common errors
- Calling
fit_transformon the test set. Usetransformonly. - Scaling or imputing before
train_test_split. - Running feature selection on all rows, then cross-validating. Put the selector in the pipeline.
- Fitting a scaler on the training and validation sets together. The validation set must be treated like test data.
- Fitting the scaler separately on each split. This makes features mean different things in train and test.
Exercise
A colleague standardizes the full dataset, then runs 5-fold cross-validation on it and reports 97% accuracy. What is wrong, and how do you fix it?
Show answer
The scaler was fit on every row, so each validation fold influenced the mean and standard deviation used to transform the training folds. The scores are slightly optimistic. Fix it by putting the scaler and the model in a pipeline (for example with makepipeline) and passing the pipeline to crossval_score, so the scaler is refit on the training folds of each round.
Exercise
Why must you call transform, not fit_transform, on the test set?
Show answer
fit_transform would learn new statistics from the test rows. The test features would then be scaled differently from the training features, and the evaluation would no longer reflect how the model will see new data at deployment, where only the training statistics are available.