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

Part 06 / Stage 2

Evaluating models

Goal: Know whether a model is actually good: the right metric, the right threshold, and an honest estimate. Time: ~3 hours · Needs: Part 5

What you will learn

  • The confusion matrix
  • Precision, recall and F1 — which mistakes cost more
  • ROC-AUC and PR-AUC
  • Choosing a decision threshold
  • Cross-validation
  • Overfitting and underfitting
  • Regularization

Topics in this part

Practice

Run from the repo root with PYTHONPATH=tools.

Exercise 1: By hand

A fraud model flags 50 transactions; 30 are really fraud. There were 80 frauds in total. Compute precision, recall and F1 by hand in code (no sklearn), then check with precision_score-style formulas printed side by side.

Show the solution to Exercise 1
# Exercise 1: By hand
flagged = 50
true_positives = 30
total_fraud = 80

precision = true_positives / flagged
recall = true_positives / total_fraud
f1 = 2 * precision * recall / (precision + recall)

print(f"precision = 30/50 = {precision:.3f}")
print(f"recall    = 30/80 = {recall:.3f}")
print(f"F1        =        {f1:.3f}")

Exercise 2: The imbalance trap

Build a "model" that always predicts 0 for the churn test split. Print its accuracy, precision and recall for class 1. One line: why does accuracy look respectable?

Show the solution to Exercise 2
# Exercise 2: The imbalance trap
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from ailab import make_churn

df = make_churn()
_, test = train_test_split(df, test_size=0.2, random_state=42, stratify=df["churned"])
y = test["churned"].to_numpy()
pred = np.zeros_like(y)

print("accuracy :", round(accuracy_score(y, pred), 3))
print("precision:", round(precision_score(y, pred, zero_division=0), 3))
print("recall   :", round(recall_score(y, pred), 3))
# Accuracy matches the majority share (70%) while catching zero churners.

Exercise 3: Capacity threshold

The retention team can call exactly 60 customers from the 400-row churn test set. Find the probability threshold that flags the top 60, and print it with the precision and recall it achieves.

Show the solution to Exercise 3
# Exercise 3: Capacity threshold
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
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()
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"]),
])
proba = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_tr, y_tr).predict_proba(X_te)[:, 1]

CAPACITY = 60
threshold = float(np.sort(proba)[::-1][CAPACITY - 1])   # 60th highest probability
pred = (proba >= threshold).astype(int)
print(f"threshold for top {CAPACITY}: {threshold:.3f} (flags {int(pred.sum())})")
print(f"precision: {precision_score(y_te, pred):.3f}")
print(f"recall   : {recall_score(y_te, pred):.3f}")

Exercise 4: CV spread

Run 5-fold cross-validated ROC-AUC for logistic regression and gradient boosting on churn (same pipeline prep). Print mean ± std for both. Is the difference bigger than the stds?


Show the solution to Exercise 4
# Exercise 4: CV spread
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import 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"]
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"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for name, clf in [("logistic regression", LogisticRegression(max_iter=1000)),
                  ("gradient boosting", HistGradientBoostingClassifier(random_state=42))]:
    scores = cross_val_score(make_pipeline(prep, clf), X, y, cv=cv, scoring="roc_auc")
    print(f"{name:20s} mean={scores.mean():.3f} std={scores.std():.3f}")
# If the gap between means is within one std, call it a tie, not a win.

Mini-project: Threshold memo

Pick a churn threshold for a retention team that can call 100 customers a month (data: the 400-customer test split, scaled to a month). Justify it with precision and recall in a printed three-line memo.

A complete version is in solutions/mini_threshold_memo.py.

Stretch: make it cost-based — assign each false positive a call cost and each false negative a lost-customer cost, and pick the threshold minimising total cost.

Common mistakes

Mistake Why it is wrong Fix
Accuracy on imbalanced data 95% accuracy can mean "predicts majority always" Precision/recall/F1, PR-AUC
Reading only accuracy Hides which mistakes happen Confusion matrix first
Shipping threshold 0.5 unexamined It is a default, not a decision Choose from capacity/cost
One lucky split as "the score" Could be noise Cross-validation, mean ± std
Tuning on the test set The final number becomes optimistic Tune in CV; test once at the end

Quick recap

  • The confusion matrix shows the four outcomes that accuracy compresses away.
  • Precision measures how much the flags can be trusted; recall measures how many of the real cases were found.
  • ROC-AUC suits balanced problems; PR-AUC stays honest when positives are rare.
  • A threshold is a business decision: here 0.3, 0.5 and 0.7 gave recall of 0.742, 0.475 and 0.200.
  • Cross-validate so you can report a mean and a spread instead of one lucky number.
  • An overfit model memorised the data, an underfit one is too simple, and regularization (a small C) trades training fit for generalisation.

Checklist

  • I can fill in a confusion matrix from a scenario.
  • I can compute precision and recall by hand.
  • I can say when PR-AUC beats ROC-AUC.
  • I picked a threshold for a stated constraint.
  • I ran 5-fold CV and can read mean ± std.
  • I can explain what C does in LogisticRegression.

Read more: Model evaluation · Cross-validation

Search the guide