TATECHATLAS
◎ English
Artificial intelligence / Tip

Preventing Data Leakage with scikit-learn Pipeline

A Pipeline chains preprocessing and estimation so that fit statistics come only from training folds. This prevents leakage during cross-validation and keeps training and inference transformations consistent.

On this page

Split data before preprocessing, then chain transformers and the estimator in a Pipeline so fit and transform operate on the correct subsets automatically.

Preventing Data Leakage with Pipeline

A scikit-learn Pipeline chains transformers with a final estimator so that a single fit call fits every step in sequence, and predict or transform applies the fitted sequence to new data. Because the pipeline owns the ordering, statistics such as means, variances, imputation values, or feature-selection scores are learned only from the data passed to fit. This removes the common failure where a transformer is fitted once on the full dataset and then reused for evaluation, which lets test-set information influence the model.

The safety property matters most during cross-validation and hyper-parameter search. When a bare estimator is passed to cross_val_score or GridSearchCV, only that estimator is refit on each fold; any transformer fitted beforehand remains fitted on all data, including the held-out fold. Passing the pipeline instead causes the transformers to be refit inside each training fold, so the validation fold is transformed using statistics derived only from that fold's training portion.

Context: Fitting Transformations on Training Data Only

Every transformation that learns from data must see only the training subset. If a normalization step divides by an average, that average must be computed from the training rows, not from the combined train and test rows. Including held-out rows in the average lets their distribution influence the fitted model and produces optimistically biased evaluation scores.

The same rule applies to feature selection, imputation, and dimensionality reduction. Selecting features by their correlation with the target using all rows leaks label information from the test set into the chosen feature set, so the reported accuracy no longer reflects performance on unseen data. The practical discipline is to split first, then fit every data-dependent step on the training partition and apply it with transform to the test partition.

Implementation with Pipeline

The example above contrasts two approaches on a single-feature synthetic regression dataset. In the wrong path, StandardScaler is fitted on all rows (including the test partition) before the model trains; the test-set mean and variance leak into the scaling parameters, producing an artificially low error of 0.88. In the correct path, make_pipeline chains StandardScaler and LinearRegression so that fit sees only X_train and predict applies the train-derived parameters to X_test. The resulting MSE of 0.90 is the honest estimate. The printed values are illustrative output for this dataset and random seed, not a benchmark.

Prerequisites: Python 3.9 or later and scikit-learn 1.3 or later, installed with pip install scikit-learn. The example uses make_regression, train_test_split, StandardScaler, LinearRegression, and mean_squared_error. The random_state values fix the split and data generation so the shown output is reproducible in that environment.

from sklearn.datasets import make_regression  # scikit-learn >= 1.3, Python >= 3.9  # pip install scikit-learn
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_regression(n_features=1, noise=1, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.4, random_state=42
)

# Wrong: fit the scaler on ALL data, then train on the train subset
scaler_bad = StandardScaler()
X_all_scaled = scaler_bad.fit_transform(X)
model_bad = LinearRegression().fit(X_all_scaled[:len(X_train)], y_train)
mse_bad = mean_squared_error(y_test, model_bad.predict(X_all_scaled[len(X_train):]))
print(f"Leaky MSE (scaler fitted on all data): {mse_bad:.2f}")

# Right: fit the scaler only on the train subset via a Pipeline
pipeline = make_pipeline(StandardScaler(), LinearRegression())
pipeline.fit(X_train, y_train)
mse_good = mean_squared_error(y_test, pipeline.predict(X_test))
print(f"Pipeline MSE (scaler fitted on train only): {mse_good:.2f}")

# Illustrative output:
# Leaky MSE (scaler fitted on all data): 0.88
# Pipeline MSE (scaler fitted on train only): 0.90

Limitations and Best Practices

Every step except the last must expose transform; the final step may be a transformer, predictor, or clustering estimator. Split the data before any preprocessing, and never call fit or fit_transform on held-out rows. For heterogeneous columns, wrap per-column transformers in a ColumnTransformer and place that inside the Pipeline so column-specific statistics are also fit within each fold.

A Pipeline does not by itself guarantee a good model: it only enforces the fit/transform boundary. Custom transformations that learn state outside scikit-learn's transformer interface must be adapted or handled separately. Also confirm that the pipeline's final step provides the method you call, since Pipeline exposes the API of its last estimator.

Applicability

  • Is the train/test split performed before any transformer is fitted?
  • Does every non-final pipeline step implement transform?
  • Are cross-validation and tuning run with the pipeline rather than a pre-fitted transformer?
  • Does the final pipeline step expose the method being called, such as predict or transform?
  • Are custom stateful transformations wrapped as scikit-learn transformers inside the pipeline?

Pipeline enforces fit/transform boundaries for scikit-learn-compatible steps, but it does not prevent leakage introduced by custom code outside the pipeline, by target leakage in the features themselves, or by preprocessing performed before the split.

Sources

  1. scikit-learn: common pitfalls ↗
  2. scikit-learn: pipelines and composition ↗
Back to top ↑