الانتقال إلى المحتوى
Machine Learningscikit-learn· 6 دقائق للقراءة

Scaling Before Splitting Leaks the Test Set: Why Pipelines Matter

Every preprocessing step learns from the rows it is fitted on. Fit it before the split and the test rows help train the model.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

A research team predicts a disease from 5,000 gene readings per patient, with 300 patients. Following a tutorial, they standardize the data, keep the 20 genes most associated with the diagnosis, and cross-validate a logistic regression: 0.777 accuracy. A reviewer asks for the code, moves the same two steps inside the cross-validation, and gets 0.503. The model was never better than a coin flip. Every step was standard; the order was the bug.

The common misconception

Many developers believe preprocessing on the full dataset is harmless, as long as the model itself is trained only on the training split. It's an easy belief to hold:

  • Preprocessing feels like cleaning, not learning. A column's mean and standard deviation don't look like a model.
  • Tutorials often call fit_transform on all of X in 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.

The half-truth: for a scaler on hundreds of rows, the leaked statistics are close to what the training rows alone would give. But "preprocess everything, then split" is a code structure, and not every step that goes through it is a scaler.

What actually happens

scikit-learn's guide to common pitfalls defines as using information that wouldn't be available at prediction time while building the model. Its rule is short: never call fit on the test data.

Every fit learns something

A transformer's 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

Unsupervised steps, such as scalers, imputers and PCA, read the test rows' features but not their labels. The effect is usually small, but Moscovich and Rosset show it's a real bias in cross-validation that can push the estimate up or down, depending on the data, the transformation, the model and the sample sizes. You can't even tell which way you're wrong.

Supervised steps read the labels: , target encoding, and oversampling the minority class. Fit them on all rows and the labels of every validation fold help choose what the model sees. That leak is large, and it always flatters the model. The script reproduces the opening story with random labels, so the honest answer is 0.5:

Python
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.777

In the wrong version, SelectKBest 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.

The right version reports 0.503. Its last two lines also show why the habit survives: with only the scaler fitted on all rows, the score is identical, 0.503. The scaler alone looked harmless here, so nobody questioned the structure that let the selector leak.

A pipeline makes each fold refit everything

A chains the steps into one estimator. Pass it to 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.

You get two more things for free. 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

Kapoor and Narayanan surveyed leakage across fields that adopted machine learning and found errors in 17 fields, affecting 329 papers. Preprocessing on training and test data together, and feature selection on both, are two of the eight leakage types in their taxonomy. In their civil war prediction case study, one paper imputed its training and out-of-sample test data together while more than 95% of the test values were missing. Corrected, its random forest did no better than logistic regression.

StepWhat fit learnsIf fitted before the split
StandardScalerEach column's mean and spreadSmall bias in either direction; 0.503 both ways here
SimpleImputerFill values from other rowsGrows with missingness; it overturned a published civil war result
PCADirections of largest varianceUnsupervised, but still a bias in the estimate
SelectKBestColumns most related to yReads validation labels: 0.777 on coin flips
OversamplingCopies or blends of minority rowsCopies of test rows land in training

How to apply it in your project

  1. Split before you lookHold out the test set before plotting, cleaning or selecting anything.
  2. Put every learned step in the pipelineImputers, scalers, encoders, selectors and resamplers all go into one Pipeline; use ColumnTransformer for different column types.
  3. Give cross-validation the raw dataPass the pipeline and the untransformed X to cross_val_score or GridSearchCV, never a pre-transformed copy.
  4. Test for leaksRun the shuffled-label check whenever the preprocessing changes.
  5. Ship the fitted pipelineSave and deploy the whole fitted pipeline, so production rows get the training-time transformation.

Key takeaways

  • Every fit learns 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.

📚 المصادر

  1. Common pitfalls and recommended practices — scikit-learn User Guide
  2. Pipelines and composite estimators — scikit-learn User Guide
  3. Kapoor and Narayanan, Leakage and the Reproducibility Crisis in ML-based Science (2022)
  4. Moscovich and Rosset, On the cross-validation bias due to unsupervised pre-processing (2022)

التعليقات (0)