Sub topic 4
Preprocessing leakage: fitting transforms on all the data
This chapter assumes you know how to split data into training and test sets, and that you have used scikit-learn estimators with fit, transform, and predict. It also assumes you understand why held-out evaluation exists.
What goes wrong
Many preprocessing steps learn something from data. A StandardScaler learns a mean and a standard deviation for each column. An imputer learns a median. A PCA learns directions of variance. Each of these steps has a fit stage that computes statistics, and a transform stage that applies them.
Preprocessing leakage happens when you call fit on rows that later end up in the test set. The test rows then influence the statistics used to build the training features. The model has not seen test labels, but it has seen information about the test distribution. Evaluation is no longer a fair simulation of new data.
The rule is simple: fit on training data only, then transform both the training and test data with those fitted values.
The classic mistake
The most common form is scaling the whole dataset before splitting.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=500, n_features=10, random_state=0)
# Leaky: the scaler learns the mean and variance of the test rows too
X_scaled = StandardScaler().fit_transform(X)
X_train_bad, X_test_bad, y_train_bad, y_test_bad = train_test_split(
X_scaled, y, random_state=0
)
# Correct: split first, fit the scaler on training rows only
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)In the leaky version, the mean and variance come from all 500 rows. In the correct version, they come from the 375 training rows. The test rows are scaled with numbers they did not help create, which is what happens in production.
You can see the difference directly. After the correct version, the training features have a mean of exactly zero, but the test features do not:
print(X_train_s.mean(axis=0).round(2))
print(X_test_s.mean(axis=0).round(2))A nonzero test mean is expected and healthy. It shows the test set was not used to center itself.
Which steps can leak
Any step with a fit stage can leak if you fit it on everything:
| Step | What it learns | Leak if fitted on all data |
|---|---|---|
| `StandardScaler`, `MinMaxScaler` | Mean, variance, min, max | Test range shapes the scale |
| `SimpleImputer` | Median, mean, most frequent value | Test values fill training gaps |
| `PCA` | Variance directions | Test rows shape the components |
| `SelectKBest` | Which features correlate with the label | Test labels pick the features |
| `OneHotEncoder` | Category list | Unseen test categories look known |
Supervised steps such as SelectKBest are the most dangerous. They use labels, so fitting them on all rows hands test labels to the model. The effect can be large when there are many features and few rows.
Why the effect is often small, and why you should still care
Scaling leakage often changes scores only slightly. With many rows, the training mean is close to the full-data mean. This tempts people to ignore it. There are two reasons not to.
- The effect grows with small datasets, heavy-tailed features, and rare categories.
- A habit of fitting on everything carries over to steps where the damage is large, such as feature selection.
Common errors
- Calling
fit_transformon the test set. Usetransformonly. - Fitting a scaler separately on train and on test. This gives the two sets different scales, so the model sees inconsistent inputs.
- Preprocessing before cross-validation. Each fold then has leaked statistics. The next chapters show how pipelines fix this.
- Imputing missing values on the full table, then splitting.
Exercise
A colleague writes X_imputed = SimpleImputer(strategy="median").fit_transform(X) and then calls train_test_split(X_imputed, y). What is wrong, and how do you fix it?
Show answer
The imputer computes medians from all rows, including the future test rows, so test data influences the training features. Split first, call fit on the imputer with the training rows only, then call transform on both the training and test rows.
Exercise
After correct scaling, the mean of each test feature is not exactly zero. Is this a bug?
Show answer
No. The scaler used the training mean and standard deviation, so only the training features are centered exactly. A small nonzero test mean is expected. Forcing it to zero would mean fitting on the test set.