S30 Logo
S30 AI Labwww.thes30.com
Back
#25

Data Preprocessing Pipelines

Medium🧠 Deep LearningW6 D1

Before You Start

Required knowledge
Pandas, missing values, categorical encoding, and scikit-learn model evaluation.
Libraries used
NumPy, pandas, scikit-learn
Dataset and source
Local churn CSV when available, with synthetic churn data as a fallback.
Expected output
A leakage-aware preprocessing/model pipeline with cross-validation and held-out evaluation.

Data Preprocessing Pipelines β€” Theory & Concepts

Read this before attempting the exercises. Clean, well-structured preprocessing pipelines prevent data leakage and make models reproducible.

Pipeline lifecycle


1. Why Pipelines Matter

Without pipelines:

# BAD: leaky, fragile, hard to reproduce
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)  # fits on ALL data (leakage!)
X_train, X_test = train_test_split(X_scaled, ...)

Leakage vs safe flow

With pipelines:

# GOOD: no leakage, reproducible
from sklearn.pipeline import Pipeline
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('model', LogisticRegression())
])
pipe.fit(X_train, y_train)   # scaler fits only on X_train
pipe.predict(X_test)          # scaler transforms X_test using train stats

2. ColumnTransformer β€” Different Preprocessing per Feature Type

ColumnTransformer branches

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

preprocessor = ColumnTransformer([
    ('num', Pipeline([
        ('impute', SimpleImputer(strategy='median')),
        ('scale', StandardScaler()),
    ]), ['age', 'income', 'balance']),

    ('cat', Pipeline([
        ('impute', SimpleImputer(strategy='most_frequent')),
        ('encode', OneHotEncoder(handle_unknown='ignore', sparse_output=False)),
    ]), ['country', 'gender', 'education']),
])

3. Common Preprocessing Steps

StepWhenMethod
Missing valuesAlways check firstImpute: mean/median/mode, or flag
ScalingDistance-based models, NNsStandardScaler, MinMaxScaler
EncodingCategorical featuresOneHot, Ordinal, Target encoding
Outlier handlingExtreme values distort modelClip, Winsorize, or RobustScaler
Log transformRight-skewed distributionsnp.log1p(x)
Feature selectionToo many featuresMutual info, L1, tree importance

Feature scaling before and after

One-hot encoding expansion example


4. Avoiding Data Leakage

Rule: Any statistic computed from data (mean, std, vocabulary, etc.) must be computed only on training data.

Leakage sources:
βœ— fit_transform on full dataset before splitting
βœ— Target encoding using test labels
βœ— Feature selection using test data
βœ— Imputing with global statistics

Safe pattern:
βœ“ Pipeline.fit(X_train) > Pipeline.transform(X_test)
βœ“ Cross-validation handles this automatically

Cross-validation with pipelines


5. Custom Transformers

from sklearn.base import BaseEstimator, TransformerMixin

class LogTransformer(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return np.log1p(np.clip(X, 0, None))

6. Serialization & Reproducibility

import joblib

# Save entire pipeline (preprocessing + model)
joblib.dump(pipe, 'model_pipeline.pkl')

# Load and predict
loaded_pipe = joblib.load('model_pipeline.pkl')
loaded_pipe.predict(new_data)

Interview Tip: "How do you deploy an ML model?" β†’ Save the entire pipeline (not just the model), so preprocessing is guaranteed to match training.


Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 β€” Notebook
0/6 solvedSubstack Notes
1
Dataset & Setup

Data Preprocessing Pipelines β€” Student Lab (Customer Churn)

Focus: build leakage-safe preprocessing with ColumnTransformer + Pipeline.

Section 0 β€” Load churn dataset (with fallback)

Expected path: data/churn/churn.csv

Loading editor...
1

Robust target parsing

2
Create y in {0,1}
2

Section 1 β€” Robust target parsing

Task 1.1: Create y in {0,1}

Loading editor...
2

Build ColumnTransformer

3
Identify numeric vs categorical columns

Section 2 β€” Build ColumnTransformer

Task 2.1: Identify numeric vs categorical columns

Task 2.2: Create preprocess with two branches

Numeric: impute median + scale Categorical: impute most_frequent + one-hot (handle_unknown='ignore')

Loading editor...
3

Stratified holdout split

4
Create stratified train/holdout split
2

Section 3 β€” Stratified holdout split

Task 3.1

Create an explicit holdout split:

  • ●train: 80%
  • ●holdout: 20% with stratification on y.

Keep holdout untouched until the final check.

Loading editor...
4

CV on training split only

5
Run StratifiedKFold CV on X_train only
2

Section 4 β€” CV on training split only

Task 4.1

Run 5-fold StratifiedKFold CV on X_train, y_train using a Pipeline(preprocess -> model).

Task 4.2

(Leakage demo) show the wrong way by fitting preprocess on all X_train before CV.

Loading editor...
5

Final holdout evaluation

6
Fit on X_train and evaluate X_test
2

Section 5 β€” Final holdout evaluation

Task 5.1

Fit the pipeline on the full training split (X_train, y_train) and evaluate ROC-AUC on untouched holdout (X_test, y_test).

This is your final unbiased estimate after model development on training data.

Loading editor...

Need help? Share feedback