Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 05 / Stage 2

Supervised learning with scikit-learn

Goal: Use scikit-learn's pipelines to train tabular models without leakage, and compare models fairly. Time: ~3 hours · Needs: Stage 1

What you will learn

  • The scikit-learn API: fit, predict, predict_proba, score
  • Pipelines and ColumnTransformer: preprocessing and model as one object
  • Encoding categorical data with one-hot encoding
  • Decision trees, and why they overfit
  • Random forests: bagging many trees
  • Gradient boosting, the tabular workhorse
  • Comparing models fairly

Topics in this part

Practice

Run from the repo root with PYTHONPATH=tools.

Exercise 1: Four verbs

On the digits dataset, train LogisticRegression(max_iter=2000) on an 80/20 stratified split. Print the predicted labels for the first three test images, the shape of their probabilities, and the test score.

Show the solution to Exercise 1
# Exercise 1: Four verbs
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

clf = LogisticRegression(max_iter=2000).fit(X_tr, y_tr)
print("predict:", clf.predict(X_te[:3]))
print("proba shape:", clf.predict_proba(X_te[:3]).shape)
print("score:", round(clf.score(X_te, y_te), 3))

Exercise 2: Pipeline from scratch

Rebuild the churn pipeline yourself (imputer + scaler for numerics, one-hot for contract, passthrough for the boolean) and print the test accuracy. Then prove there is no leakage: print the imputer's learned statistic and the train-only median — they must match.

Show the solution to Exercise 2
# Exercise 2: Pipeline from scratch
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"]
imputer = SimpleImputer(strategy="median")
prep = ColumnTransformer([
    ("num", make_pipeline(imputer, 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))

# No leakage: the imputer's learned value equals the train-only median.
# (Pipelines fit a CLONE of each step, so read it back from the fitted model.)
fitted_imputer = model.named_steps["prep"].named_transformers_["num"].steps[0][1]
charges_stat = fitted_imputer.statistics_[numeric.index("monthly_charges")]
print("imputer learned:  ", round(float(charges_stat), 3))
print("train-only median:", round(float(X_tr["monthly_charges"].median()), 3))

Exercise 3: Depth sweep

On digits, train decision trees with max_depth in [2, 4, 8, None] and print train and test accuracy for each. Where does overfitting start?

Show the solution to Exercise 3
# Exercise 3: Depth sweep
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

for depth in [2, 4, 8, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_tr, y_tr)
    print(f"max_depth={str(depth):4s} train={tree.score(X_tr, y_tr):.3f} test={tree.score(X_te, y_te):.3f}")
# The train-test gap opens as depth grows; unlimited depth hits train 1.0.

Exercise 4: Add a fourth model

Extend the bake-off with DecisionTreeClassifier(max_depth=8) inside the same preprocessing. Print all four ROC-AUCs. Does the single tree beat either ensemble?


Show the solution to Exercise 4
# Exercise 4: Add a fourth model
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.tree import DecisionTreeClassifier
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)
prep = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
     ["tenure_months", "monthly_charges", "support_calls"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["contract"]),
    ("bool", "passthrough", ["has_internet"]),
])
models = {
    "logistic regression": LogisticRegression(max_iter=1000),
    "decision tree (d=8)": DecisionTreeClassifier(max_depth=8, random_state=42),
    "random forest": RandomForestClassifier(n_estimators=200, random_state=42),
    "gradient boosting": HistGradientBoostingClassifier(random_state=42),
}
for name, clf in models.items():
    pipe = make_pipeline(prep, clf).fit(X_tr, y_tr)
    auc = roc_auc_score(y_te, pipe.predict_proba(X_te)[:, 1])
    print(f"{name:20s} ROC-AUC = {auc:.3f}")

Mini-project: Model bake-off

Compare four models on churn inside identical pipelines, report ROC-AUC for each, and write one sentence explaining why the winner won.

A complete version is in solutions/mini_model_bakeoff.py.

Stretch: add cross-validated confidence intervals and a short written recommendation.

Common mistakes

Mistake Why it is wrong Fix
Preprocessing outside the pipeline Refits on the full data and leaks into CV ColumnTransformer inside a Pipeline
OneHotEncoder without handle_unknown New category crashes production handle_unknown="ignore"
Unlimited tree depth Memorises training data Set max_depth or use an ensemble
Comparing models on different splits Differences reflect the split, not the model One split (or CV), fixed seed, same prep
Skipping the simple baseline You cannot tell if complexity paid for itself Logistic regression in every bake-off

Quick recap

  • Everything in scikit-learn speaks one API: fit, predict, predict_proba and score.
  • A Pipeline with a ColumnTransformer gives leak-free preprocessing in one deployable object.
  • One-hot encode categories; ignore unknowns in production.
  • Trees overfit alone; forests average them; boosting corrects them sequentially.
  • A fair comparison fixes the split, the preprocessing and the metric — and keeps a simple baseline in the race (it won here at 0.811).

Checklist

  • I trained and scored a model through the four-verb API.
  • I built a ColumnTransformer pipeline on churn.
  • I can explain what happens to unseen categories.
  • I can read train 1.0 / test 0.878 as overfitting.
  • I ran the bake-off and can explain why logistic regression won.

Read more: Pipelines and composite estimators · Common pitfalls

Search the guide