Building Leak-Free ML Pipelines with scikit-learn Pipeline and ColumnTransformer
Learn to combine preprocessing and modeling in a single scikit-learn pipeline, avoid data leakage, and verify the workflow with a minimal script.
14 Dec 2025, 04:35 UTC

Why a Single Pipeline Matters
When you preprocess numeric and categorical columns separately, it is easy to forget that the same scaling parameters must be reused on the test set. A forgotten fit on the full data leaks information and inflates performance estimates. scikit-learn’s Pipeline and ColumnTransformer solve this by locking preprocessing to the training split and reapplying it automatically.
Anatomy of a Heterogeneous Pipeline
A Pipeline chains steps sequentially. The first step can be a ColumnTransformer that routes each column group to its own transformer:
- Numeric columns →
StandardScaler - Categorical columns →
OneHotEncoder(handle_unknown='ignore')
The output of the column transformer feeds directly into the estimator, for example a HistGradientBoostingClassifier.
Worked Example: End-to-End Script
Save the following as train_pipeline.py and run it with a standard Python 3.11+ environment (no elevated permissions required).
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
import joblib
# 1. Synthetic data
df = pd.DataFrame({
'age': [25, 32, 47, 51, 23, 40, 60, 35],
'income': [50000, 80000, 120000, 95000, 30000, 110000, 150000, 70000],
'city': ['NY', 'LA', 'NY', 'SF', 'LA', 'SF', 'NY', 'LA'],
'target': [0, 1, 1, 0, 0, 1, 1, 0]
})
X = df.drop('target', axis=1)
y = df['target']
# 2. Split – fit only on train
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
# 3. Define transformers
numeric_features = ['age', 'income']
categorical_features = ['city']
preprocess = ColumnTransformer(
transformers=[
('num', StandardScaler(), numeric_features),
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)
],
remainder='drop' # columns not listed are discarded
)
# 4. Build pipeline
pipe = Pipeline([
('preprocess', preprocess),
('model', HistGradientBoostingClassifier(random_state=0))
])
# 5. Fit on training data only
pipe.fit(X_train, y_train)
# 6. Evaluate on hold-out set
proba = pipe.predict_proba(X_test)[:, 1]
print('ROC-AUC:', roc_auc_score(y_test, proba))
# 7. Persist the fitted pipeline
joblib.dump(pipe, 'pipeline.joblib')
print('Pipeline saved to pipeline.joblib')
Where to run: terminal or command prompt in the project directory.
Permissions: regular user write access to the working folder.
Placeholders: replace the synthetic DataFrame with your real data source.
Expected check: the printed ROC-AUC should be a float between 0 and 1; the file pipeline.joblib must exist and be loadable with joblib.load.
Risk: if remainder='drop' removes a column you later need, the model will train on fewer features than intended.
Verification Checklist
- Load the saved pipeline and call
predict_probaon a fresh test split; the scores must match the in-memory pipeline (within floating-point tolerance). - Compare the pipeline’s predictions against a manual preprocessing baseline (fit scaler/encoder on
X_trainonly, transform both splits, then fit the classifier). Identical results confirm no leakage. - Inspect
pipe.named_steps['preprocess'].transformers_to verify that each transformer was fitted on the training partition only.
Trade-offs and Limitations
ColumnTransformer drops any column not listed in transformers when remainder='drop' (the default). Forgetting a feature silently reduces model capacity. Large numbers of categorical levels expand the one-hot matrix, increasing memory consumption and training time. If memory becomes a bottleneck, consider OrdinalEncoder with a tree-based model or feature hashing.
Next Steps
Run the verification checklist on your own dataset. If the pipeline passes, promote pipeline.joblib to your model registry and use it for batch or online inference—no extra preprocessing code required. Monitor prediction latency; if the one-hot expansion is costly, experiment with TargetEncoder or embedding layers in a downstream framework.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.