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. It also assumes you know the scikit-learn fit, transform and predict methods. You do not need pipelines yet. The next chapter introduces them as the structural fix for the problem described here.
What preprocessing leakage is
Many preprocessing steps learn something from data. A StandardScaler learns a mean and a standard deviation per column. A SimpleImputer learns a median. A PCA learns directions of variance. A TfidfVectorizer learns a vocabulary and word frequencies. Each of these steps has a fit stage, where it learns, and a transform stage, where it applies what it learned.
Preprocessing leakage happens when fit sees rows that belong to the test set. The test rows then influence the features the model trains on, and the test set is no longer a clean simulation of unseen data.
The usual mistake is a single line:
X_scaled = StandardScaler().fit_transform(X) # fit sees every rowfollowed by a train/test split of X_scaled. The order of operations is wrong, even though each line looks harmless.
The leaky order and the correct order
Here is the mistake and its fix side by side.
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 correct version, the test rows are only ever passed to transform. The scaler subtracts the training mean and divides by the training standard deviation. The test features will therefore not have exactly zero mean and unit variance, and that is expected.
Seeing what the transform learned
A fitted transformer stores what it learned in attributes that end with an underscore. You can compare them to see exactly what leaked.
import numpy as np
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)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler_all = StandardScaler().fit(X)
scaler_train = StandardScaler().fit(X_train)
print("max mean difference:", np.abs(scaler_all.mean_ - scaler_train.mean_).max())
print("max scale difference:", np.abs(scaler_all.scale_ - scaler_train.scale_).max())The differences are small but not zero. Those differences are the footprint of the test rows on the training features.
Why the leak is usually small, and why you should still avoid it
For plain scaling on a large random split, the inflation in the test score is often tiny. That does not make the habit acceptable, for three reasons.
- The size of the effect depends on the data. With few rows, heavy-tailed features, or extreme outliers in the test set, one row can shift a mean or a maximum noticeably.
- Some transforms leak far more than scaling. PCA, supervised feature selection, target encoding and oversampling can each carry much more information from the test rows into the training features.
- A habit that is harmless on one dataset becomes a serious error on another, and the metric will not warn you.
The rule is simple, so apply it always: any object with a fit method is fitted on training data only.
Which transforms learn from data
Use this table as a review list when you read your own code.
| Transform | What `fit` learns | What leaks if fitted on all rows |
|---|---|---|
| `StandardScaler` | Column mean and standard deviation | Test location and spread |
| `MinMaxScaler` | Column minimum and maximum | Test extremes |
| `SimpleImputer` | Mean, median or most frequent value | Test central values filling gaps |
| `OneHotEncoder` | The set of categories | Categories that exist only in the test set |
| `TfidfVectorizer` | Vocabulary and inverse document frequencies | Test word counts and terms |
| `PCA` | Principal directions | Test variance structure |
| `SelectKBest` | Which columns score highest against `y` | Test labels (a much worse leak) |
| `KBinsDiscretizer` | Bin edges | Test quantiles |
Stateless transforms, such as taking a logarithm of each value or dividing two columns of the same row, learn nothing. They are safe to apply before the split because each output depends only on its own row.
Imputation
Missing values are a common place for this error, because imputing "so the data is clean" feels like a data-preparation step, not a modeling step. It is a modeling step. The median it computes is learned from data.
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
X[rng.random(X.shape) < 0.1] = np.nan # about 10 percent missing
y = rng.integers(0, 2, size=200)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
imputer = SimpleImputer(strategy="median").fit(X_train)
X_train_i = imputer.transform(X_train)
X_test_i = imputer.transform(X_test)
print(np.isnan(X_test_i).sum()) # 0: gaps are filled with training mediansA test row with a missing value receives the training median. That matches production, where a new row with a gap would be filled using values stored when the model was built.
Text and categories
Text vectorizers learn a vocabulary, so a test document can contain words the model has never seen.
from sklearn.feature_extraction.text import TfidfVectorizer
docs_train = ["the cat sat", "the dog barked", "a cat and a dog"]
docs_test = ["the bird sang", "a cat sang"]
vec = TfidfVectorizer().fit(docs_train)
X_test_tfidf = vec.transform(docs_test)
print(sorted(vec.vocabulary_)) # words from training documents only
print("bird" in vec.vocabulary_) # False: unseen words are ignoredIf you had fitted the vectorizer on all five documents, "bird" and "sang" would become features. Their idf weights would also reflect test frequencies. In production, a new word cannot become a feature without retraining, so the honest evaluation ignores it.
For categorical columns, a similar problem appears. A category that occurs only in the test set should not be known at fit time. Set handle_unknown="ignore" on OneHotEncoder so that unseen categories produce all zeros instead of an error, and do not "fix" the error by fitting the encoder on all rows.
Validation sets and the final refit
With three splits, the same principle extends in a straightforward way.
- Fit the preprocessing on the training set.
- Transform the validation set with the fitted object, and use it to compare models.
- Transform the test set with the same fitted object, once, at the very end.
After you have chosen a model, you may refit the preprocessing and the model on training plus validation rows before deployment. This is not leakage as long as the test set stays untouched. It also means the final model is fitted on slightly different statistics than the one you evaluated. This is normal and expected.
Mistakes that look like the fix but are not
- Fitting a separate scaler on the test set. Calling
StandardScaler().fit_transform(X_test)avoids leaking test information into training. It creates a different problem: the train and test features are now on different scales, so the model sees inconsistent inputs. In production, a single incoming row cannot even be standardized this way, because one row has no meaningful standard deviation. - Fitting on training plus test "because the labels are not used." Unsupervised fitting on test features is sometimes called transductive learning. It is only valid if your real deployment also has the full unlabeled batch at fit time. Most deployments do not, so the evaluation then overstates what you will achieve.
- Oversampling before the split. Methods such as random oversampling or SMOTE create copies or interpolations of rows. If you apply them first, near-copies of one row can land on both sides of the split, and the model is tested on rows it has effectively memorized. Split first and resample only the training part.
- Dropping rows or columns using full-data statistics. Removing outliers beyond three standard deviations, or dropping features with high correlation to each other, uses statistics from every row. Compute the rule on training data and apply it as a fitted step.
- Reusing
X_scaledfrom an earlier notebook cell. A cached scaled array hides where it came from. Name arrays by their stage, such asX_train_s, so a reader can see what was fitted on what.
A quick audit for your own code
Read the script top to bottom and mark each call that has a fit or fit_transform. For each one, answer two questions.
- Which rows does the call see?
- Is the train/test split performed before that line?
If a fit call precedes the split, or sees an array that contains test rows, it is a leak. Moving the split to the top of the script, directly after loading the data, removes most of these mistakes in one edit.
This manual discipline works, but it relies on you remembering the rule in every cell and every refactor. It also becomes harder inside cross-validation, where the "training part" changes five times per run. The next chapter shows how a scikit-learn Pipeline makes the correct behavior automatic, so you cannot forget it.
Exercise
A colleague writes X_imp = SimpleImputer(strategy="mean").fit_transform(X) and then calls train_test_split(X_imp, y). Which statistic leaks, and how do you correct the code?
Show answer
The column means computed from all rows, including the future test rows, are used to fill gaps in the training rows. Split first with train_test_split(X, y), then fit the imputer on X_train only (SimpleImputer(strategy="mean").fit(X_train)), and call transform on both X_train and X_test.
Exercise
Why is StandardScaler().fit_transform(X_test) not an acceptable way to avoid leaking test data?
Show answer
It does stop test statistics from reaching the training features, but it standardizes the test rows with their own mean and standard deviation. The model was trained on features scaled with training statistics, so it receives inputs on a different scale at evaluation time. A single production row also has no usable standard deviation. Fit the scaler on the training rows and call only transform on the test rows.
Exercise
Which of these steps can safely run before the train/test split: (a) np.log1p applied to every value, (b) MinMaxScaler, (c) PCA, (d) dividing column total by column count in each row?
Show answer
(a) and (d) are safe because they are stateless and each output depends only on its own row. (b) learns minimums and maximums, and (c) learns principal directions, so both must be fitted on training rows only.