Skip to main content

Lesson 4 of 9

Leak-Free End-to-End Preprocessing Pipelines with Scikit-Learn

The most robust defense against data leakage in production machine learning is enclosing the entire data transformation and modeling pipeline inside an atomic Scikit-Learn `Pipeline`. When enclosed in a Pipeline, cross-validation automatically fits transformers strictly on the training folds and evaluates them on untouched validation folds without writing manual loop boilerplate.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Constructing an Atomic Leak-Free Pipeline with Cross-Validation

Constructing an Atomic Leak-Free Pipeline with Cross-Validation
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# Synthetic transaction dataset
np.random.seed(42)
n = 2000
df = pd.DataFrame({
    'amount': np.random.exponential(scale=60, size=n),
    'device_trust_score': np.random.uniform(0, 100, size=n),
    'card_type': np.random.choice(['DEBIT', 'CREDIT', 'PREPAID'], size=n),
    'channel': np.random.choice(['WEB', 'APP', 'POS'], size=n),
})
# Ground truth risk
risk_score = 0.01 * df['amount'] - 0.03 * df['device_trust_score'] + (df['card_type'] == 'PREPAID') * 1.5
y = (1 / (1 + np.exp(-risk_score)) > np.random.uniform(0, 1, size=n)).astype(int)

# 1. SPLIT BEFORE ANY PROCESSING
X = df
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

# 2. DEFINE PREPROCESSOR
preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), ['amount', 'device_trust_score']),
        ('cat', OneHotEncoder(drop='first', handle_unknown='ignore'), ['card_type', 'channel'])
    ]
)

# 3. COMPOSE COMPLETE ATOMIC PIPELINE
full_pipeline = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42))
])

# 4. CROSS-VALIDATION (Guarantees zero leakage across folds)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(full_pipeline, X_train, y_train, cv=cv, scoring='roc_auc')

print(f"5-Fold CV ROC-AUC: {cv_scores.mean():.4f} (± {cv_scores.std():.4f})")

# 5. FIT ONCE ON FULL TRAINING SET & EVALUATE ON TEST SET
full_pipeline.fit(X_train, y_train)
y_pred = full_pipeline.predict(X_test)

print("\nTest Set Performance Report:")
print(classification_report(y_test, y_pred, digits=4))

Pro Tip: Accessing Nested Pipeline Steps

You can inspect or extract any fitted parameter inside a pipeline using named indexing: `full_pipeline.named_steps['preprocessor'].named_transformers_['num'].mean_` extracts the fitted StandardScaler means learned during training.

Diagram
Loading diagram…

MlDataPreprocessing Visual Representation

Hands-On Challenge: Build a Complete Pipeline with Hyperparameter Search

Combine `Pipeline`, `ColumnTransformer`, and `GridSearchCV` to jointly search the optimal `StandardScaler` vs `RobustScaler` choice alongside Random Forest `max_depth` (3, 5, 8).

Quick Quiz & Key Concept Checks

Common Pitfall: Custom Functions in Pipeline Without FunctionTransformer

Passing raw Python functions directly into a Pipeline will fail because they lack `.fit()` and `.transform()` methods. Wrap custom functions using `sklearn.preprocessing.FunctionTransformer(my_func)`.

Topics in This Module

0/9 done