
Scaling Before Splitting Leaks the Test Set: Why Pipelines Matter
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
The common misconception
Preprocessing feels like cleaning, not learning. A column's mean and standard deviation don't look like a model. Tutorials often call fit_transformon all ofXin the first cell and split later, and the code is shorter.Often the score really doesn't move. In the script below, scaling the whole dataset first changes nothing at all.
What actually happens
fit on the test data.
Every fit learns something
fit estimates numbers from the rows it sees. StandardScaler learns each column's mean and spread, SimpleImputer learns fill values, PCA learns directions, and SelectKBest learns which columns are most related to y. In production, none of those numbers can come from tomorrow's requests. If they come from your test rows during evaluation, the evaluation describes a model you can't deploy.
What leaks depends on what the step reads
import numpy as npfrom sklearn.feature_selection import SelectKBestfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.preprocessing import StandardScalerrng = np.random.default_rng(3)X = rng.normal(size=(300, 5000)) # 300 patients, 5,000 gene readingsy = rng.integers(0, 2, size=300) # coin-flip labels: nothing to learnX_all = StandardScaler().fit_transform(X) # fitted on every rowX_all = SelectKBest(k=20).fit_transform(X_all, y) # reads every labelscores = cross_val_score(LogisticRegression(), X_all, y, cv=5)print(f"accuracy {scores.mean():.3f}")# accuracy 0.777import numpy as npfrom sklearn.feature_selection import SelectKBestfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerrng = np.random.default_rng(3)X = rng.normal(size=(300, 5000))y = rng.integers(0, 2, size=300)pipe = make_pipeline(StandardScaler(), SelectKBest(k=20), LogisticRegression())scores = cross_val_score(pipe, X, y, cv=5) # every step refit per foldprint(f"all steps in the pipeline: accuracy {scores.mean():.3f}")X_scaled = StandardScaler().fit_transform(X) # only the scaler outsidepipe = make_pipeline(SelectKBest(k=20), LogisticRegression())scores = cross_val_score(pipe, X_scaled, y, cv=5)print(f"scaler fitted on all rows: accuracy {scores.mean():.3f}")# all steps in the pipeline: accuracy 0.503# scaler fitted on all rows: accuracy 0.503SelectKBest ranked 5,000 random columns by how well they matched all 300 labels. Out of 5,000, some 20 match by pure chance, including on the rows each fold later uses for validation. The model then "predicts" labels that picked its own features, and reports 0.777 for nothing. scikit-learn's pitfalls guide shows the same effect with 10,000 random features: 0.76 instead of 0.5.
A pipeline makes each fold refit everything
cross_val_score or GridSearchCV with the raw data, and every fold fits a fresh copy: each transformer learns from that fold's training rows only, then transforms the validation rows with what it learned. The scikit-learn guide lists this as the pipeline's safety purpose: it avoids leaking test statistics into the trained model by training the transformers and the predictor on the same samples.
GridSearchCV can tune preprocessing and model together, with names like selectkbest__k. And the fitted pipeline carries its scaler and imputer into production, so new rows get exactly the training-time transformation.
It isn't only a beginner's mistake
fit learns | ||
|---|---|---|
StandardScaler | ||
SimpleImputer | ||
PCA | ||
SelectKBest | y | |
How to apply it in your project
Split before you look Hold out the test set before plotting, cleaning or selecting anything. Put every learned step in the pipeline Imputers, scalers, encoders, selectors and resamplers all go into one Pipeline; useColumnTransformerfor different column types.Give cross-validation the raw data Pass the pipeline and the untransformed Xtocross_val_scoreorGridSearchCV, never a pre-transformed copy.Test for leaks Run the shuffled-label check whenever the preprocessing changes. Ship the fitted pipeline Save and deploy the whole fitted pipeline, so production rows get the training-time transformation.
Key takeaways
Every fitlearns from the rows it sees; fitting before the split lets test rows shape the model.A scaler fitted on all rows often changes little, 0.503 both ways here, which is why the habit survives. Steps that read labels leak badly: feature selection on all rows scored 0.777 on coin-flip labels. Put every step that learns from data in a Pipeline, and cross-validate the pipeline on raw data.
📚 المصادر
Common pitfalls and recommended practices — scikit-learn User Guide Pipelines and composite estimators — scikit-learn User Guide Kapoor and Narayanan, Leakage and the Reproducibility Crisis in ML-based Science (2022) Moscovich and Rosset, On the cross-validation bias due to unsupervised pre-processing (2022)
التعليقات (0)