Sub topic 6
Fit on Training Data Only to Avoid Leakage
This chapter assumes you know the fit / transform API of scikit-learn scalers, the idea of a train/test split, and basic NumPy. Here you will see why a scaler must learn its statistics from the training split only, and how to do that correctly.
What leakage means for scaling
Data leakage happens when information from data the model should not have seen influences training. A test set exists to imitate future data. If the test rows affect any step before the model is scored, the score is optimistic.
A scaler learns numbers from data: StandardScaler learns a mean and standard deviation, and MinMaxScaler learns a minimum and maximum. If you call fit on the full dataset before splitting, those numbers include the test rows. The model then trains on features that were shaped by the test data.
The effect is usually small for one scaler on a large dataset. It can grow with small datasets, extreme values in the test set, or many preprocessing steps. The rule is cheap to follow, so follow it always.
The wrong way and the right way
The wrong order is: scale everything, then split.
# Leaky: statistics come from all rows, including future test rows
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test = train_test_split(X_scaled, test_size=0.2, random_state=0)The right order is: split, fit on the training split, then transform both splits with the same fitted scaler.
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(loc=[50, 1000], scale=[5, 300], size=(100, 2))
y = (X[:, 0] > 50).astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
scaler = StandardScaler().fit(X_train) # learn statistics from training data only
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # reuse the training statisticsNotice that the test split passes through transform only. It never reaches fit.
Test data will not look standardized
After the correct procedure, the scaled test columns usually do not have a mean of exactly 0 or a standard deviation of exactly 1. That is expected. The test rows are scaled with the training mean and standard deviation, which is what happens to new data in production.
With MinMaxScaler, a test value below the training minimum becomes negative, and one above the training maximum becomes greater than 1. This is not a bug. Chapter 11 covers clipping for cases where you need a bounded output.
Leakage also happens in cross-validation
A single train/test split is the simple case. Cross-validation repeats the split several times. If you scale the whole dataset first and then run cross_val_score, every validation fold has already influenced the scaler.
The fix is to put the scaler inside a Pipeline. The pipeline refits the scaler on the training part of each fold, then applies it to that fold's validation part.
from sklearn.datasets import load_breast_cancer
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_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())The next chapter covers pipelines and ColumnTransformer in more detail.
Common mistakes
| Mistake | Why it leaks or misleads | Fix |
|---|---|---|
| Scaling before `train_test_split` | Test rows influence the mean, standard deviation, min and max | Split first, then fit on the training split |
| Calling `fit_transform` on the test set | Test data gets its own scaler, so the scales differ | Call `transform` only |
| Scaling the full dataset before `cross_val_score` | Validation folds shape the scaler | Use a `Pipeline` |
| Refitting the scaler at prediction time | Predictions use different statistics than training | Save the fitted scaler and reuse it |
Exercise
You standardize a dataset with StandardScaler().fit_transform(X), then call train_test_split on the result and train a model. Name the problem, and give the corrected order of steps.
Show answer
The scaler's mean and standard deviation were computed from all rows, including the future test rows, so test information leaked into preprocessing and the test score may be optimistic. The correct order is: split into train and test, fit the scaler on the training split only, transform the training split, then transform the test split with that same fitted scaler. A Pipeline is the safest way to enforce this.
Exercise
After scaling correctly, the mean of a test column is 0.13 instead of 0. Is something wrong? Explain.
Show answer
No. The test column was scaled with the training mean and standard deviation, not its own. The test data can have a slightly different mean and spread, so its scaled mean need not be exactly 0. Forcing it to 0 would require fitting on the test set, which is the mistake this chapter warns against.