Bundle preprocessing and modeling with scikit-learn Pipeline to stop data leakage
Wrap scaling, encoding, and model fitting in one scikit-learn Pipeline so cross-validation stays honest and deployment needs only one saved artifact.
21 Nov 2025, 10:45 UTC

The leak happens before you split the data
You train a model, cross-validate it, and see strong scores. In production, predictions fall apart. A common cause is preprocessing the full dataset before splitting into train and test folds. When you scale numeric columns or encode categories using information from the entire dataset, the test data leaks into the training process. The model memorizes statistics it should not have seen.
Takeaway: fit preprocessing inside each cross-validation fold by bundling it with the estimator in a scikit-learn Pipeline. A fitted pipeline also serializes as a single artifact, so inference can start from raw rows without re-implementing scaling or encoding.
Where leakage usually enters
This pattern looks harmless but leaks target information:
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # fitted on every row
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2)
StandardScaler centers and scales features using the mean and standard deviation of the data it sees. Fitting it on the full dataset lets the test fold influence the training mean and variance. OneHotEncoder, which converts categorical columns into binary columns, has the same issue if it learns categories from all rows.
Bundle preprocessing with Pipeline and ColumnTransformer
A Pipeline chains transformers and a final estimator into one object. fit runs each step in order; predict applies the transforms and then the estimator. ColumnTransformer applies different transformers to different column groups inside that same pipeline.
Here is a worked example with mixed numeric and categorical data:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
# df is a raw DataFrame with mixed numeric and categorical columns
numeric_features = ["age", "fare"]
categorical_features = ["embarked", "class"]
preprocessor = ColumnTransformer(
transformers=[
("num", StandardScaler(), numeric_features),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
]
)
model = Pipeline(
steps=[
("preprocess", preprocessor),
("classifier", LogisticRegression(max_iter=1000)),
]
)
X = df.drop(columns=["target"])
y = df["target"]
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
Because preprocessing lives inside model, cross_val_score refits the scaler and encoder within each fold. The validation fold never contributes to the training-fold statistics, which keeps the leakage out of your scores. The column names in numeric_features and categorical_features must match the DataFrame exactly; a missing column raises an error before prediction.
Save one artifact and predict on raw data
A fitted pipeline serializes with joblib. You can load it later in a new process and call predict on rows that have not been preprocessed.
import joblib
joblib.dump(model, "model_pipeline.joblib")
# Fresh process:
loaded = joblib.load("model_pipeline.joblib")
predictions = loaded.predict(new_raw_df)
Run these commands in a Python interpreter or notebook. No special permissions are required, but the directory must be writable. joblib.dump overwrites an existing file with the same name, so use a versioned filename if you need to keep older artifacts. Rollback: delete the file or re-run dump with the corrected pipeline.
new_raw_df must contain the same column names and dtypes as the training data. The loader does not need separate preprocessing code, which reduces deployment drift when training and inference run on separate systems.
Trade-offs and how to verify
Pipelinedoes not catch a shape mismatch between transformer output and estimator input untilfitruns.OneHotEncoderraises an error on unseen categories at inference unlesshandle_unknown="ignore"is configured.- Steps run sequentially, so slow preprocessing can dominate training time regardless of estimator speed.
Practical check: compare cross_val_score results from the pipeline against a manual workflow that splits first and fits scalers only on training data. A large gap suggests leakage. For inference, load the saved pipeline in a fresh Python process and call predict on raw rows never used during training.
Closing
If your preprocessing happens before train_test_split, your validation scores are probably optimistic. Move the transforms into a Pipeline with ColumnTransformer, validate with cross-validation, and save the whole object with joblib. You get honest metrics and a deployable artifact in one step.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.