Preventing Data Leakage in Preprocessing: Fit Only on Training Data
Fit preprocessing steps like feature selection and StandardScaler only on the training split; a scikit-learn Pipeline enforces the correct fit/transform sequence and prevents optimistic scores.
On this page
Key idea
Fit every data-driven transformation, including feature selection and StandardScaler, exclusively on the training subset, then apply the already-fitted transformer to the test subset with transform. A scikit-learn Pipeline chains transformers and an estimator so that fit is called only on training data and transform is applied consistently to any subsequent data, which prevents information from the test set from influencing the model and avoids optimistically biased evaluation.
Context and recommendation
Data leakage occurs when information from the test subset influences model training, most commonly through preprocessing steps that compute statistics from all data. If a normalization step divides by the average value, that average must come from the train subset only; including the test subset in the calculation means test information is influencing the model. The scikit-learn common pitfalls documentation states this directly: transformations must only be learnt from the training data, and using all the data, for example fit(X) on the full dataset, can result in overly optimistic scores.
The recommendation is procedural: always split the data into train and test subsets first, before any preprocessing. Use fit or fit_transform only on the train subset, and use transform on both subsets so the same preprocessing is applied everywhere. This applies to nearly all scikit-learn transformations, including StandardScaler, SimpleImputer, PCA, and feature selection methods such as SelectKBest. The scikit-learn Pipeline is the recommended way to enforce this discipline because it ensures the appropriate method is performed on the correct data subset, and it integrates cleanly with cross-validation and hyper-parameter tuning functions.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = make_pipeline(StandardScaler(), LogisticRegression())
pipeline.fit(X_train, y_train) # scaler statistics come from X_train only
y_pred = pipeline.predict(X_test) # X_test is transformed with training statisticsHow leakage happens and how Pipeline prevents it
Transformations like StandardScaler learn parameters (the mean and standard deviation of each feature) during fit. If those parameters are computed on data that includes the test set, the test features are no longer independent of the fitted model: the preprocessing has effectively peeked at the test distribution. The same logic applies to feature selection, where the selector decides which features look predictive; selecting features using test labels lets noise that happens to correlate with test labels influence which features the model sees.
A Pipeline solves this mechanically rather than by discipline. When you call pipeline.fit(X_train, y_train), each transformer's fit_transform runs on the training data in sequence, and the final estimator fits on the transformed training data. When you call pipeline.predict(X_test), each transformer's transform (not fit_transform) runs on the test data using parameters learned during fit. Because the pipeline is a single estimator, passing it to cross_val_score or GridSearchCV means each cross-validation fold refits the entire chain, including the preprocessing, on that fold's training portion only. This is why the documentation calls the pipeline ideal for cross-validation and hyper-parameter tuning: without it, a scaler fitted once on the full dataset would leak statistics into every fold.
There is a trade-off in convenience: fitting preprocessing inside each fold is slightly more expensive than fitting it once, and the pipeline adds a layer of indirection when inspecting intermediate values. The benefit is that the evaluation reflects what would happen in production, where a deployed model applies transformations fitted on historical data to new, unseen inputs.
from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score
pipeline = make_pipeline(SelectKBest(f_classif, k=25), HistGradientBoostingClassifier(random_state=1))
scores = cross_val_score(pipeline, X, y)
print(f'Mean accuracy: {scores.mean():.2f} +/- {scores.std():.2f}')Concrete example: inflated accuracy from leaked feature selection
The scikit-learn documentation demonstrates the effect with a binary classification problem containing 200 samples and 10,000 randomly generated features, where no feature carries real signal. When feature selection is performed on all data before splitting, the selector picks the 25 features that happen to correlate with the test labels by chance, and a HistGradientBoostingClassifier trained on them reaches an accuracy of 0.76. This number is pure leakage: the model appears far better than chance on data that is pure noise.
When the same procedure is done correctly, splitting first with train_test_split, calling select.fit_transform only on X_train, and applying select.transform to X_test, the accuracy drops to 0.5, which is what we expect for random data. Rebuilding the same steps as a Pipeline with make_pipeline(SelectKBest(k=25), HistGradientBoostingClassifier(random_state=1)) and calling pipeline.fit(X_train, y_train) followed by pipeline.predict(X_test) reproduces the honest 0.5 score. Feeding that pipeline into cross_val_score gives a mean accuracy of about 0.43 with a standard deviation of 0.05, again consistent with chance. The gap between 0.76 and 0.5 quantifies how severely leakage can distort evaluation, and the distorted number is the one that looks better, which is exactly why leakage is dangerous: it rewards the wrong workflow.
The documentation also shows the mirror-image pitfall for scaling: fitting StandardScaler on X_train but passing untransformed X_test to predict raises the mean squared error from about 0.90 to about 62.80 on a regression problem. Here the error is inflated not by leakage but by applying the model to a feature space it was never trained on, which is the consistency half of the same rule: transforms fitted during training must be applied to all subsequent data.
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X, y = make_regression(random_state=42, n_features=1, noise=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)
scaler = StandardScaler()
X_train_transformed = scaler.fit_transform(X_train)
model = LinearRegression().fit(X_train_transformed, y_train)
print(mean_squared_error(y_test, model.predict(scaler.transform(X_test)))) # about 0.90
print(mean_squared_error(y_test, model.predict(X_test))) # about 62.80, wrong feature spaceLimits and applicability
The split-first rule assumes the preprocessing statistics should be estimated from training data alone. Some workflows legitimately use statistics from a broader population, for example when a scaler is calibrated on a large historical corpus and frozen before new data arrives; in that case the frozen transformer is still fitted only on data available at training time, and the principle holds. What does not work is fitting a transformer on the full dataset and then evaluating on a subset of that same dataset, because the evaluation data contributed to the fitted parameters.
Cross-validation mitigates but does not by itself eliminate the problem if preprocessing is done outside the pipeline: fitting a scaler or selector once on all data before cross_val_score leaks into every fold. The pipeline must wrap the preprocessing so each fold refits it. Note also that the reported numbers, such as 0.76 versus 0.5 accuracy or the 62.80 versus 0.90 MSE, are illustrative outputs from the scikit-learn documentation for those specific synthetic datasets and library versions; they demonstrate the direction and magnitude of the bias, not a universal figure. Finally, leakage control addresses evaluation honesty; it does not fix other pitfalls such as inconsistent preprocessing between training and production, which requires applying the same fitted transformer to all subsequent data.
Applicability
- Is every fit or fit_transform call in your code applied only to the training subset?
- Are preprocessing steps wrapped in a Pipeline so cross-validation refits them per fold?
- Could any transformer statistic (mean, variance, selected features, imputation values) have been computed on data later used for evaluation?
- Is the same fitted transformer applied to production data, not refitted there?
Where this applies
The quoted accuracy and MSE figures come from the scikit-learn common pitfalls documentation for specific synthetic datasets and library versions; they illustrate the direction and scale of leakage bias, not guaranteed values for other datasets.