Part 05 / Topic 2 of 7
Pipelines and ColumnTransformer
Part 3's rule — fit preprocessing on training data only — is easy to break by hand. A Pipeline makes it automatic: preprocessing and model become one object, and whatever fits, fits on training folds only.
ColumnTransformer routes different columns through different steps: scale the numeric ones, one-hot encode the categorical ones, pass booleans through.
# examples/01_a_scikit_learn_pipeline_preprocessing_and.py
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from ailab import make_churn
df = make_churn()
X, y = df.drop(columns=["customer_id", "churned"]), df["churned"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
numeric = ["tenure_months", "monthly_charges", "support_calls"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), ["contract"]),
("bool", "passthrough", ["has_internet"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X_tr, y_tr)
print("test accuracy:", round(model.score(X_te, y_te), 3))
# test accuracy: 0.76
Note what disappeared: no manual median, no manual scaling, no chance of fitting them on the wrong rows. The whole object also serializes as one file for deployment (Track B).
🧪 Quick quiz
- Why put preprocessing inside a Pipeline rather than doing it before the split?
Show the answer
Preprocessing is then fitted only on the training folds — during cross-validation the pipeline refits the imputer and scaler inside each fold — preventing leakage. And the whole thing deploys as one object.
Done here? The practice set for Part 5 — 4 exercises with solutions — is on the part page.