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.
Lesson Videos
Data Preprocessing Pipelines β Theory & Concepts
Read this before attempting the exercises. Clean, well-structured preprocessing pipelines prevent data leakage and make models reproducible.
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, ...)
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
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
| Step | When | Method |
|---|---|---|
| Missing values | Always check first | Impute: mean/median/mode, or flag |
| Scaling | Distance-based models, NNs | StandardScaler, MinMaxScaler |
| Encoding | Categorical features | OneHot, Ordinal, Target encoding |
| Outlier handling | Extreme values distort model | Clip, Winsorize, or RobustScaler |
| Log transform | Right-skewed distributions | np.log1p(x) |
| Feature selection | Too many features | Mutual info, L1, tree importance |
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
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?
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
Robust target parsing
Section 1 β Robust target parsing
Task 1.1: Create y in {0,1}
Build ColumnTransformer
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')
Stratified holdout split
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.
CV on training split only
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.
Final holdout evaluation
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.