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

Part 08 / Stage 2

Practical ML

Goal: The details that decide real projects: features, imbalance, tuning, importance, leakage, reproducibility, fairness. Time: ~3 hours · Needs: Parts 5–7

What you will learn

  • Feature engineering, measured not assumed
  • Class imbalance: weights and the right metrics
  • Hyperparameter tuning with cross-validation
  • Feature importance, and its pitfalls
  • Leakage case studies
  • Reproducibility
  • Fairness and bias checks before shipping

Topics in this part

Practice

Run from the repo root with PYTHONPATH=tools.

Exercise 1: Measure a feature

Add calls_per_year = support_calls / (tenure_months / 12) to the churn data (dropna first). Print its correlation with churn next to support_calls's. Keep or drop?

Show the solution to Exercise 1
# Exercise 1: Measure a feature
from ailab import make_churn

df = make_churn().dropna()
df = df.assign(calls_per_year=df.support_calls / (df.tenure_months / 12))
print("corr with churn:")
print("  support_calls :", round(float(df.support_calls.corr(df.churned)), 3))
print("  calls_per_year:", round(float(df.calls_per_year.corr(df.churned)), 3))
# calls_per_year mixes the support-calls signal with tenure's (inverted) one,
# so judge it against BOTH parents before keeping it.

Exercise 2: Imbalance levers

On the 95/5 synthetic dataset from the lesson, produce three rows: no weighting, class_weight="balanced", and no weighting with threshold 0.25. Print precision and recall for each. Which lever would you pick if a miss costs 20x a false alarm?

Show the solution to Exercise 2
# Exercise 2: Imbalance levers
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=5000, weights=[0.95, 0.05], flip_y=0.01, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=3)

plain = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
balanced = LogisticRegression(class_weight="balanced", max_iter=1000).fit(X_tr, y_tr)

rows = [
    ("no weighting", plain.predict(X_te)),
    ("balanced", balanced.predict(X_te)),
    ("threshold 0.25", (plain.predict_proba(X_te)[:, 1] >= 0.25).astype(int)),
]
for name, pred in rows:
    print(f"{name:15s} precision={precision_score(y_te, pred):.3f} recall={recall_score(y_te, pred):.3f}")
# A miss costing 20x a false alarm pushes you to the highest-recall row.

Exercise 3: Random vs grid

Tune a random forest on digits with RandomizedSearchCV (n_iter=4, same parameter ranges as the lesson's grid). Print the best parameters and score, and compare with the lesson's grid result (0.944).

Show the solution to Exercise 3
# Exercise 3: Random vs grid
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV

X, y = load_digits(return_X_y=True)
search = RandomizedSearchCV(
    RandomForestClassifier(random_state=0),
    param_distributions={"n_estimators": [50, 100, 200, 400], "max_depth": [5, 10, None]},
    n_iter=4, cv=3, scoring="accuracy", random_state=0,
)
search.fit(X, y)
print("best params:", search.best_params_)
print("best score :", round(search.best_score_, 3), "(lesson's full grid best: 0.944)")
# Four random draws usually land near the grid's best at a fraction of the fits.

Exercise 4: Importance under correlation

Duplicate the churn tenure_months column as tenure_copy, retrain, and print permutation importances for both. What happened to tenure's credit?


Show the solution to Exercise 4
# Exercise 4: Importance under correlation
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from ailab import make_churn

df = make_churn()
df = df.assign(tenure_copy=df.tenure_months)          # perfectly correlated twin
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", "tenure_copy", "monthly_charges", "support_calls"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["contract"]),
    ("bool", "passthrough", ["has_internet"]),
])
pipe = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
imp = permutation_importance(pipe, X_te, y_te, scoring="roc_auc", n_repeats=10, random_state=0)
for name, mean in sorted(zip(X_te.columns, imp.importances_mean), key=lambda t: -t[1]):
    print(f"{name:16s} {mean:+.3f}")
# Shuffle tenure_months and tenure_copy still carries the signal (and vice
# versa), so each alone looks far less important than tenure really is.

Mini-project: Fraud-style imbalance lab

On a 95/5 dataset, compare: no weighting, class weights, and threshold tuning (pick the threshold that maximises F1 on a validation split). Report precision, recall and F1 for each on a held-out test set.

A complete version is in solutions/mini_imbalance_lab.py.

Stretch: add CalibratedClassifierCV and check whether predicted probabilities match observed rates per bucket.

Common mistakes

Mistake Why it is wrong Fix
Keeping engineered features by intuition This part's ratio was worse than the raw column Measure, then keep
Accuracy on imbalanced data Majority-guessing scores 95% PR-AUC, F1, per-class recall
Grid-searching on the test set Optimistic final number CV on train; test once
Trusting importance under correlation Credit splits between twins Check correlations; drop one of a pair
One overall metric at ship time Hides failing subgroups Per-group error rates

Quick recap

  • Engineer features freely, keep them only on measured merit.
  • Against imbalance, class weights and thresholds trade precision for recall (recall rose from 0.761 to 0.821 here).
  • Tune with GridSearchCV or RandomizedSearchCV, always inside cross-validation.
  • Permutation importance showed contract dominating churn (+0.173); correlation and leakage distort such rankings.
  • Leakage wears four costumes: target, time, preprocessing, duplicates.
  • Seeds, pinned versions and recorded runs add up to reproducibility.
  • Check per-group error rates before shipping: this model's false-negative rate runs 0.44 / 0.81 / 1.00 across the three contract types.

Checklist

  • I measured an engineered feature against its raw parts.
  • I can name both imbalance levers and their cost.
  • I ran a grid search and read cv_results_.
  • I can explain two ways importance misleads.
  • I can spot all four leakage patterns in a scenario.
  • I checked a model's error rate per group.

Read more: Tuning hyper-parameters · Permutation importance · Calibration

Search the guide