Skip to content

36. Classification — Exercises

These exercises practice every idea of the classification lesson. Most of them use the churn data in data/customers.csv; a few use the breast cancer, wine and iris datasets bundled with scikit-learn.

How to work:

  1. Copy the setup block below into the top of your script. Every exercise assumes it ran first.
  2. Copy the starter code under it and replace each to-do comment with your code.
  3. Run the script and compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code.

The setup loads the churn data, makes the stratified 75/25 split of the lesson and defines make_preprocess(): median imputation and scaling for the numbers, one-hot encoding with a reference level for the text columns. cat_dtypes holds one CategoricalDtype per text column, built from the training rows. Apply it to every split (X_test.astype(cat_dtypes)) when a boosting model reads category columns, so all splits share the same level list.

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
num_cols = [
"age", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay",
]
cat_cols = ["region", "plan", "contract", "payment_method"]
X = customers[num_cols + cat_cols]
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cat_dtypes = { # one category list per text column, learned from training rows
col: pd.CategoricalDtype(sorted(X_train[col].unique())) for col in cat_cols
}
def make_preprocess() -> ColumnTransformer:
"""Impute and scale the numbers, one-hot encode the text columns."""
numeric = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
categorical = OneHotEncoder(
drop="first", handle_unknown="ignore", sparse_output=False
)
return ColumnTransformer(
[("num", numeric, num_cols), ("cat", categorical, cat_cols)],
verbose_feature_names_out=False,
)

M36-W01 · Metrics from a confusion matrix

Section titled “M36-W01 · Metrics from a confusion matrix”
Warm-up

A fraud screen checked 1,000 card payments. Its confusion matrix is TN = 850, FP = 60, FN = 40, TP = 50. Compute the accuracy, precision, recall, F1 and specificity from the four counts, and print each with 3 decimals.

Expected output
accuracy: 0.900
precision: 0.455
recall: 0.556
F1: 0.500
specificity: 0.934
Starter
tn, fp, fn, tp = 850, 60, 40, 50
# TODO: compute accuracy, precision, recall, f1 and specificity
# TODO: print each as "name: value" with 3 decimals
Hint 1

Precision divides by everything the model flagged (TP + FP). Recall divides by everything that really is fraud (TP + FN).

Hint 2

F1 is 2 * precision * recall / (precision + recall). Specificity is the recall of the negative class: tn / (tn + fp).

Solution
tn, fp, fn, tp = 850, 60, 40, 50
accuracy = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
specificity = tn / (tn + fp)
for name, value in [
("accuracy", accuracy), ("precision", precision), ("recall", recall),
("F1", f1), ("specificity", specificity),
]:
print(f"{name}: {value:.3f}")
assert round(accuracy, 3) == 0.9
assert round(precision, 3) == 0.455 and round(recall, 3) == 0.556
Output
accuracy: 0.900
precision: 0.455
recall: 0.556
F1: 0.500
specificity: 0.934

How it works:

  1. Accuracy counts the correct cells (TN and TP) over all 1,000 payments.
  2. Precision 0.455: fewer than half of the flagged payments are fraud. Recall 0.556: the screen finds a bit more than half of the fraud.
  3. Accuracy 0.900 looks strong only because 910 of 1,000 payments are not fraud. A screen that flags nothing would score 0.910.

Alternative: rebuild label arrays from the counts and let scikit-learn compute the metrics.

from sklearn.metrics import f1_score, precision_score, recall_score
y_true = np.array([0] * 850 + [0] * 60 + [1] * 40 + [1] * 50)
y_pred = np.array([0] * 850 + [1] * 60 + [0] * 40 + [1] * 50)
print(f"{precision_score(y_true, y_pred):.3f} {recall_score(y_true, y_pred):.3f}"
f" {f1_score(y_true, y_pred):.3f}")
Output
0.455 0.556 0.500

M36-W02 · Probabilities, odds and log-odds

Section titled “M36-W02 · Probabilities, odds and log-odds”
Warm-up

Predict the output: a logistic model gives three customers the log-odds 0, log(3) and -log(4). What probability and what odds does each get? Write your answers first, then run the code.

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Starter
log_odds = np.array([0.0, np.log(3), -np.log(4)])
p = 1 / (1 + np.exp(-log_odds))
odds = p / (1 - p)
print(p.round(3))
print(odds.round(3))
Hint 1

The odds are eze^{z}. So log-odds 0 means odds 1: an even chance.

Hint 2

Odds 3 means 3 to 1, a probability of 3/4. Odds 1/4 means 1 to 4, a probability of 1/5.

Solution
log_odds = np.array([0.0, np.log(3), -np.log(4)])
p = 1 / (1 + np.exp(-log_odds))
odds = p / (1 - p)
print(p.round(3))
print(odds.round(3))
assert np.allclose(p, [0.5, 0.75, 0.2])
assert np.allclose(odds, [1, 3, 0.25])
Output
[0.5 0.75 0.2 ]
[1. 3. 0.25]

How it works:

  1. The sigmoid maps log-odds 0 to 0.5: churn and stay are equally likely.
  2. Log-odds log⁡3\log 3 means odds of 3 to 1, so p=3/(3+1)=0.75p = 3/(3+1) = 0.75.
  3. Log-odds −log⁡4-\log 4 means odds of 1 to 4, so p=1/(1+4)=0.2p = 1/(1+4) = 0.2, the churn rate of the course data.

Alternative: scipy.special.expit is the sigmoid and scipy.special.logit is its inverse.

from scipy.special import expit, logit
print(expit(np.log(3)).round(3), logit(0.2).round(3), (-np.log(4)).round(3))
Output
0.75 -1.386 -1.386
Warm-up

Fit a DummyClassifier(strategy="most_frequent") on the churn training set. Print its test accuracy, its recall for churners and its ROC-AUC from predict_proba.

Expected output
accuracy 0.807, recall 0.000, ROC-AUC 0.500
Starter
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score, roc_auc_score
# TODO: fit the dummy on X_train, y_train
# TODO: print accuracy, recall and ROC-AUC on the test set
Hint 1

The dummy ignores the features, so it works on the raw X_train with text columns.

Hint 2

dummy.predict_proba(X_test)[:, 1] is the same number for every customer. A constant score cannot rank anyone above anyone else.

Solution
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score, roc_auc_score
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = dummy.predict(X_test)
acc = accuracy_score(y_test, pred)
rec = recall_score(y_test, pred)
auc = roc_auc_score(y_test, dummy.predict_proba(X_test)[:, 1])
print(f"accuracy {acc:.3f}, recall {rec:.3f}, ROC-AUC {auc:.3f}")
assert round(acc, 3) == 0.807 and rec == 0 and auc == 0.5
Output
accuracy 0.807, recall 0.000, ROC-AUC 0.500

How it works:

  1. “Most frequent” predicts “stays” for everyone. 80.7% of test customers stay, so that is the accuracy.
  2. It never flags a churner, so recall is 0.
  3. Its probability is constant, so every churner–stayer pair is a tie: ROC-AUC 0.5.

Alternative: strategy="stratified" predicts random labels at the class rates. Its accuracy is lower, but its recall is not 0. Neither carries any information; both are baselines.

M36-W04 · Fix the bug: ROC-AUC from labels

Section titled “M36-W04 · Fix the bug: ROC-AUC from labels”
Warm-up

Fix the bug: this code reports a ROC-AUC far below the 0.813 of the lesson for the same model. Find the cause and fix it.

Expected output
from labels: 0.633
ROC-AUC 0.813
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
auc = roc_auc_score(y_test, model.predict(X_test))
print(f"ROC-AUC {auc:.3f}")
Hint 1

Print model.predict(X_test)[:10]. How many different values can ROC-AUC rank?

Hint 2

ROC-AUC needs a score per customer: predict_proba(X)[:, 1].

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
auc_labels = roc_auc_score(y_test, model.predict(X_test))
auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
print(f"from labels: {auc_labels:.3f}")
print(f"ROC-AUC {auc:.3f}")
assert round(auc, 3) == 0.813 and auc_labels < 0.65
Output
from labels: 0.633
ROC-AUC 0.813

How it works:

  1. predict returns 0/1 labels at the 0.5 threshold. ROC-AUC on labels sees only two scores and one point on the curve.
  2. Its value equals the mean of recall and specificity at 0.5, a threshold metric, not a ranking metric.
  3. Column 1 of predict_proba keeps the full ranking, so the ROC-AUC is the real 0.813.

M36-W05 · Fix the bug: swapped confusion matrix

Section titled “M36-W05 · Fix the bug: swapped confusion matrix”
Warm-up

Fix the bug: an analyst computes precision and recall for ten customers from a confusion matrix, but the numbers do not match precision_score and recall_score. Fix the code so that both lines agree.

Expected output
by hand: precision 0.600, recall 0.750
sklearn: precision 0.600, recall 0.750
Starter
from sklearn.metrics import confusion_matrix, precision_score, recall_score
y_true = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])
y_pred = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0])
tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel()
print(f"by hand: precision {tp / (tp + fp):.3f}, recall {tp / (tp + fn):.3f}")
print(f"sklearn: precision {precision_score(y_true, y_pred):.3f}, "
f"recall {recall_score(y_true, y_pred):.3f}")
Hint 1

Check the order of the arguments in the scikit-learn documentation of confusion_matrix.

Hint 2

The true labels come first. Swapping them transposes the matrix, so FP and FN trade places.

Solution
from sklearn.metrics import confusion_matrix, precision_score, recall_score
y_true = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])
y_pred = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0])
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(f"by hand: precision {tp / (tp + fp):.3f}, recall {tp / (tp + fn):.3f}")
print(f"sklearn: precision {precision_score(y_true, y_pred):.3f}, "
f"recall {recall_score(y_true, y_pred):.3f}")
assert (tn, fp, fn, tp) == (4, 2, 1, 3)
Output
by hand: precision 0.600, recall 0.750
sklearn: precision 0.600, recall 0.750

How it works:

  1. confusion_matrix(y_true, y_pred) puts the true classes in rows. The swapped call put them in columns.
  2. The transposed matrix turned 2 false positives into 2 false negatives and the 1 false negative into a false positive, so precision and recall traded places.
  3. With the right order, .ravel() gives TN, FP, FN, TP and both lines agree.

Alternative: pass keywords so the order cannot go wrong: confusion_matrix(y_true=y_true, y_pred=y_pred).

Warm-up

The retention team gives you churn probabilities for eight customers and wants to call everyone at 0.3 or above. Build the 0/1 call list, then print it, the number of calls and the ids to call.

Expected output
[0 1 0 1 1 0 1 0]
calls: 4
ids: ['C00203', 'C01022', 'C01980', 'C03007']
Starter
ids = np.array(["C00017", "C00203", "C00415", "C01022", "C01980", "C02311", "C03007",
"C04150"])
proba = np.array([0.12, 0.31, 0.08, 0.55, 0.30, 0.29, 0.71, 0.05])
# TODO: build the call list with threshold 0.3 (0.3 itself is a call)
# TODO: print the list, the number of calls and the ids
Hint 1

A comparison on an array gives a boolean array: proba >= 0.3.

Hint 2

.astype(int) turns booleans into 0/1. A boolean array also selects from another array: ids[mask].

Solution
ids = np.array(["C00017", "C00203", "C00415", "C01022", "C01980", "C02311", "C03007",
"C04150"])
proba = np.array([0.12, 0.31, 0.08, 0.55, 0.30, 0.29, 0.71, 0.05])
call = (proba >= 0.3).astype(int)
print(call)
print("calls:", call.sum())
print("ids:", ids[call == 1].tolist())
assert call.sum() == 4 and "C01980" in ids[call == 1]
Output
[0 1 0 1 1 0 1 0]
calls: 4
ids: ['C00203', 'C01022', 'C01980', 'C03007']

How it works:

  1. >= includes the boundary, so the customer at exactly 0.30 gets a call; 0.29 does not.
  2. scikit-learn’s FixedThresholdClassifier uses the same “at or above” rule. Plain predict is slightly different: it needs a probability strictly above 0.5, so an exact tie goes to class 0. With continuous probabilities, ties are rare.
  3. Boolean indexing picks the ids where the mask is true.

Alternative: scikit-learn wraps a fitted or unfitted model with a fixed threshold: FixedThresholdClassifier(model, threshold=0.3). Its predict then applies 0.3 for you.

Warm-up

Interpret a result: a churn model fitted on unscaled features has these coefficients: has_autopay −0.69 (0 or 1), support_tickets 0.47 (per ticket) and tenure_months −0.046 (per month). Turn each coefficient into an odds ratio and print a sentence with the percent change in the odds. For tenure, also give the effect of 12 months.

Expected output
has_autopay: odds ratio 0.502, odds change -49.8%
support_tickets: odds ratio 1.600, odds change +60.0%
tenure_months: odds ratio 0.955, odds change -4.5%
12 more months of tenure: odds x 0.576 (-42.4%)
Starter
coefs = {"has_autopay": -0.69, "support_tickets": 0.47, "tenure_months": -0.046}
# TODO: odds ratio = exp(coefficient); percent change = (odds ratio - 1) * 100
# TODO: one line per feature, then the 12-month effect of tenure
Hint 1

np.exp(coef) is the odds ratio for a one-unit increase.

Hint 2

For 12 months, multiply the coefficient by 12 before you take the exponential: e12we^{12w}, which equals (ew)12(e^{w})^{12}.

Solution
coefs = {"has_autopay": -0.69, "support_tickets": 0.47, "tenure_months": -0.046}
odds_ratios = {}
for name, coef in coefs.items():
odds_ratios[name] = np.exp(coef)
change = (odds_ratios[name] - 1) * 100
print(f"{name}: odds ratio {odds_ratios[name]:.3f}, odds change {change:+.1f}%")
year = np.exp(12 * coefs["tenure_months"])
print(f"12 more months of tenure: odds x {year:.3f} ({(year - 1) * 100:+.1f}%)")
assert round(odds_ratios["has_autopay"], 2) == 0.50
assert round(year, 3) == round(odds_ratios["tenure_months"] ** 12, 3)
Output
has_autopay: odds ratio 0.502, odds change -49.8%
support_tickets: odds ratio 1.600, odds change +60.0%
tenure_months: odds ratio 0.955, odds change -4.5%
12 more months of tenure: odds x 0.576 (-42.4%)

How it works:

  1. Autopay halves the churn odds (odds ratio 0.50, −49.8%) compared with an otherwise identical customer without autopay.
  2. Each support ticket raises the odds by 60%.
  3. One month changes the odds by only −4.5%, but the effect compounds: 12 months multiply the odds by 0.576.

Alternative: report the effect for a meaningful step size directly: np.exp(coef * step) with step = 12 months, 1 ticket, 1 standard deviation. Readers understand “per year” better than “per month”.

M36-W08 · Log loss and Brier score by hand

Section titled “M36-W08 · Log loss and Brier score by hand”
Warm-up

Four customers have the labels [1, 0, 1, 0] and the predicted churn probabilities [0.9, 0.2, 0.4, 0.6]. Compute the log loss and the Brier score with NumPy, then check both with scikit-learn.

Expected output
log loss: 0.5403 (sklearn 0.5403)
Brier: 0.1925 (sklearn 0.1925)
Starter
from sklearn.metrics import brier_score_loss, log_loss
y_true = np.array([1, 0, 1, 0])
p = np.array([0.9, 0.2, 0.4, 0.6])
# TODO: log loss = -mean(y log p + (1 - y) log(1 - p))
# TODO: Brier = mean((p - y) ** 2)
# TODO: print both, next to the scikit-learn values
Hint 1

For a churner (y = 1) only the log p term counts; for a stayer only log(1 - p) counts.

Hint 2

np.log and np.mean work element by element on the whole arrays.

Solution
from sklearn.metrics import brier_score_loss, log_loss
y_true = np.array([1, 0, 1, 0])
p = np.array([0.9, 0.2, 0.4, 0.6])
ll = -np.mean(y_true * np.log(p) + (1 - y_true) * np.log(1 - p))
brier = np.mean((p - y_true) ** 2)
print(f"log loss: {ll:.4f} (sklearn {log_loss(y_true, p):.4f})")
print(f"Brier: {brier:.4f} (sklearn {brier_score_loss(y_true, p):.4f})")
assert np.isclose(ll, log_loss(y_true, p))
assert np.isclose(brier, brier_score_loss(y_true, p))
Output
log loss: 0.5403 (sklearn 0.5403)
Brier: 0.1925 (sklearn 0.1925)

How it works:

  1. The terms are −log⁡0.9-\log 0.9, −log⁡0.8-\log 0.8, −log⁡0.4-\log 0.4 and −log⁡0.4-\log 0.4. The two wrong-side predictions (0.4 for a churner, 0.6 for a stayer) cost most.
  2. The Brier terms are 0.01, 0.04, 0.36 and 0.36; their mean is 0.1925.
  3. Both metrics agree with scikit-learn to 4 decimals.

M36-W09 · Macro, weighted and micro averages

Section titled “M36-W09 · Macro, weighted and micro averages”
Warm-up

Predict the output: a support-ticket classifier sorts 10 tickets into billing, bug and login. Before you run the code, predict which F1 average is the lowest and whether the micro F1 equals the accuracy.

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Starter
from sklearn.metrics import accuracy_score, f1_score
y_true = ["billing"] * 6 + ["bug"] * 3 + ["login"]
y_pred = ["billing"] * 6 + ["bug", "bug", "billing"] + ["billing"]
for average in ["macro", "weighted", "micro"]:
print(f"{average:<8} F1 {f1_score(y_true, y_pred, average=average):.3f}")
print(f"accuracy {accuracy_score(y_true, y_pred):.3f}")
Hint 1

The single login ticket is predicted wrong, so the F1 of login is 0.

Hint 2

The macro average counts that 0 as one third of the result. The weighted average counts it as one tenth.

Solution
from sklearn.metrics import accuracy_score, f1_score
y_true = ["billing"] * 6 + ["bug"] * 3 + ["login"]
y_pred = ["billing"] * 6 + ["bug", "bug", "billing"] + ["billing"]
scores = {}
for average in ["macro", "weighted", "micro"]:
scores[average] = f1_score(y_true, y_pred, average=average)
print(f"{average:<8} F1 {scores[average]:.3f}")
print(f"accuracy {accuracy_score(y_true, y_pred):.3f}")
assert scores["macro"] < scores["weighted"] < scores["micro"]
assert np.isclose(scores["micro"], accuracy_score(y_true, y_pred))
Output
macro F1 0.552
weighted F1 0.754
micro F1 0.800
accuracy 0.800

How it works:

  1. Per class: billing has precision 6/8 and recall 1, so F1 0.857; bug has F1 0.8; login has F1 0.
  2. Macro = (0.857 + 0.8 + 0) / 3 = 0.552: the missed rare class costs a third.
  3. Weighted = (6 × 0.857 + 3 × 0.8 + 1 × 0) / 10 = 0.754. Micro pools all decisions, so it equals the accuracy, 0.8.
  4. No ticket is predicted as login, yet f1_score gives no warning: scikit-learn computes F1 as 2TP / (2TP + FP + FN), which is 0 / 1 = 0 here. precision_score(y_true, y_pred, average="macro") on the same labels does warn, because the precision of login is 0/0; pass zero_division=0 there.

M36-C01 · A logistic regression churn model

Section titled “M36-C01 · A logistic regression churn model”
Core

Fit a logistic regression pipeline (make_preprocess() + LogisticRegression(max_iter=1000)) on the churn training set. On the test set, print the ROC-AUC, the average precision, and the confusion matrix at the default threshold.

Expected output
ROC-AUC 0.813, average precision 0.557
[[972 37]
[168 73]]
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, confusion_matrix, roc_auc_score
# TODO: build and fit the pipeline
# TODO: compute the churn probabilities on X_test
# TODO: print ROC-AUC, average precision and the confusion matrix
Hint 1

make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000)) is the whole model.

Hint 2

The ranking metrics take predict_proba(X_test)[:, 1]; the confusion matrix takes predict(X_test).

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, confusion_matrix, roc_auc_score
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
auc = roc_auc_score(y_test, proba)
ap = average_precision_score(y_test, proba)
cm = confusion_matrix(y_test, model.predict(X_test))
print(f"ROC-AUC {auc:.3f}, average precision {ap:.3f}")
print(cm)
assert round(auc, 3) == 0.813 and cm.sum() == len(y_test)
Output
ROC-AUC 0.813, average precision 0.557
[[972 37]
[168 73]]

How it works:

  1. The pipeline imputes, scales and encodes inside fit, using training rows only.
  2. ROC-AUC 0.813 matches the reference score in the data dictionary. The average precision of 0.557 is almost three times the 0.193 base rate.
  3. The confusion matrix shows the weakness of the 0.5 threshold: 168 missed churners against 73 found.

M36-C02 · Which contract and payment method are riskiest?

Section titled “M36-C02 · Which contract and payment method are riskiest?”
Core

Interpret a result: using the C01 model, print the odds ratios of the contract_* and payment_method_* one-hot columns, sorted from highest to lowest. Then print the reference level of each of the two columns. Which payment method has the highest churn odds, and compared with what?

Expected output
payment_method_electronic_check 1.450
payment_method_paypal 0.846
payment_method_credit_card 0.812
contract_one-year 0.349
contract_two-year 0.178
dtype: float64
contract reference: month-to-month
payment_method reference: bank_transfer
Starter
from sklearn.linear_model import LogisticRegression
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
# TODO: pair model[-1].coef_[0] with model[:-1].get_feature_names_out()
# TODO: keep the contract_ and payment_method_ rows, exponentiate, sort
# TODO: print the reference level of contract and payment_method
Hint 1

A pd.Series(coefs, index=names) lets you filter with names.str.startswith(...).

Hint 2

The fitted encoder is model[0].named_transformers_["cat"]. Its categories_[i][drop_idx_[i]] is the dropped level of column i.

Solution
from sklearn.linear_model import LogisticRegression
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
coefs = pd.Series(model[-1].coef_[0], index=model[:-1].get_feature_names_out())
keep = coefs.index.str.startswith(("contract_", "payment_method_"))
odds_ratios = np.exp(coefs[keep]).sort_values(ascending=False)
print(odds_ratios.round(3))
encoder = model[0].named_transformers_["cat"]
for i, col in enumerate(cat_cols):
if col in ("contract", "payment_method"):
print(f"{col} reference: {encoder.categories_[i][encoder.drop_idx_[i]]}")
assert odds_ratios.index[0] == "payment_method_electronic_check"
assert odds_ratios["contract_two-year"] < odds_ratios["contract_one-year"] < 1
Output
payment_method_electronic_check 1.450
payment_method_paypal 0.846
payment_method_credit_card 0.812
contract_one-year 0.349
contract_two-year 0.178
dtype: float64
contract reference: month-to-month
payment_method reference: bank_transfer

How it works:

  1. str.startswith accepts a tuple of prefixes, so one mask keeps both groups.
  2. Electronic check is the only payment method with an odds ratio above 1: 1.45 times the churn odds of bank transfer, the reference level, all else equal.
  3. Both longer contracts are far below 1. A two-year contract has 0.18 times the odds of month-to-month. Contract length is the strongest lever for retention offers.

M36-C03 · Choose k for KNN on a validation split

Section titled “M36-C03 · Choose k for KNN on a validation split”
Core

Split the churn training set again into a fitting part and a validation part (25%, stratified, random_state=42). Fit a KNN pipeline for k in 5, 15, 50 and 150 on the fitting part and print the validation ROC-AUC of each. Refit the best k on the whole training set and print its test ROC-AUC once.

Expected output
k=5 validation ROC-AUC 0.692
k=15 validation ROC-AUC 0.760
k=50 validation ROC-AUC 0.785
k=150 validation ROC-AUC 0.791
best k=150, test ROC-AUC 0.794
Starter
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import KNeighborsClassifier
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
# TODO: loop over k, fit on X_fit, score ROC-AUC on X_val
# TODO: pick the best k, refit on X_train, print the test ROC-AUC
Hint 1

Store the validation scores in a dict {k: auc}, then max(scores, key=scores.get) returns the best k.

Hint 2

Each k needs a new pipeline with its own make_preprocess().

Solution
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import KNeighborsClassifier
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
scores = {}
for k in [5, 15, 50, 150]:
knn = make_pipeline(make_preprocess(), KNeighborsClassifier(n_neighbors=k))
knn.fit(X_fit, y_fit)
scores[k] = roc_auc_score(y_val, knn.predict_proba(X_val)[:, 1])
print(f"k={k:<3} validation ROC-AUC {scores[k]:.3f}")
best_k = max(scores, key=scores.get)
final = make_pipeline(make_preprocess(), KNeighborsClassifier(n_neighbors=best_k))
final.fit(X_train, y_train)
test_auc = roc_auc_score(y_test, final.predict_proba(X_test)[:, 1])
print(f"best k={best_k}, test ROC-AUC {test_auc:.3f}")
assert best_k in (50, 150) and scores[5] < scores[best_k]
Output
k=5 validation ROC-AUC 0.692
k=15 validation ROC-AUC 0.760
k=50 validation ROC-AUC 0.785
k=150 validation ROC-AUC 0.791
best k=150, test ROC-AUC 0.794

How it works:

  1. k=5 votes with very few neighbors, so its probabilities jump in steps of 0.2 and follow noise. The score rises with k and then levels off.
  2. The choice uses the validation part only. The test set is opened once, for the final number.
  3. The final model trains on all 3,750 training rows, so it has more neighbors to choose from than the validation models had.

Alternative: cross-validation on the whole training set gives a steadier choice than one validation split: cross_val_score(knn, X_train, y_train, cv=5, scoring="roc_auc").mean() per k. Module 37 automates this with GridSearchCV.

M36-C04 · Naive Bayes or logistic regression for biopsies?

Section titled “M36-C04 · Naive Bayes or logistic regression for biopsies?”
Core

Choose a method and justify it: on the breast cancer data, make malignant the positive class (target == 0). Split 75/25 with stratification and random_state=42. Compare GaussianNB and a scaled logistic regression with 5-fold stratified cross-validation on the training part (mean ROC-AUC and Brier score). Which one would you put behind a risk score that a doctor reads as a percentage? Choose by the cross-validated Brier score, then report the chosen model’s test Brier score once.

Expected output
naive Bayes CV ROC-AUC 0.986 CV Brier 0.058
logistic CV ROC-AUC 0.991 CV Brier 0.022
chosen: logistic, test Brier 0.022
Starter
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.naive_bayes import GaussianNB
cancer = load_breast_cancer(as_frame=True)
yb = (cancer.target == 0).astype(int) # 1 = malignant
# TODO: split; cross_validate both models on the training part
# TODO: choose by mean Brier; fit the winner on the training part; test once
Hint 1

Naive Bayes needs no scaling. Logistic regression does: use make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).

Hint 2

A doctor reads the number as a probability, so its size must be right. Which metric checks the size? cross_validate(..., scoring=["roc_auc", "neg_brier_score"]) gives both; flip the sign of the Brier scorer.

Solution
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.naive_bayes import GaussianNB
cancer = load_breast_cancer(as_frame=True)
yb = (cancer.target == 0).astype(int) # 1 = malignant
Xb_train, Xb_test, yb_train, yb_test = train_test_split(
cancer.data, yb, test_size=0.25, stratify=yb, random_state=42
)
models = {
"naive Bayes": GaussianNB(),
"logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_brier = {}
for name, model in models.items():
res = cross_validate(model, Xb_train, yb_train, cv=cv,
scoring=["roc_auc", "neg_brier_score"])
cv_brier[name] = -res["test_neg_brier_score"].mean()
print(f"{name:<12} CV ROC-AUC {res['test_roc_auc'].mean():.3f}"
f" CV Brier {cv_brier[name]:.3f}")
chosen = min(cv_brier, key=cv_brier.get)
proba = models[chosen].fit(Xb_train, yb_train).predict_proba(Xb_test)[:, 1]
print(f"chosen: {chosen}, test Brier {brier_score_loss(yb_test, proba):.3f}")
assert chosen == "logistic"
Output
naive Bayes CV ROC-AUC 0.986 CV Brier 0.058
logistic CV ROC-AUC 0.991 CV Brier 0.022
chosen: logistic, test Brier 0.022

How it works:

  1. Both models rank almost perfectly in cross-validation. The Brier score of naive Bayes is far higher.
  2. The 30 cancer features are strongly correlated (radius, perimeter and area measure the same size). Naive Bayes counts that evidence many times, so its probabilities sit near 0 and 1 and are too confident.
  3. For a percentage that a person reads, choose logistic regression: its probabilities are closer to the truth. Naive Bayes would need calibration first.
  4. The choice uses the training folds only. The test set is read once, for the chosen model, and confirms the cross-validated Brier score.

M36-C05 · Watch a tree overfit with cross-validation

Section titled “M36-C05 · Watch a tree overfit with cross-validation”
Core

For a DecisionTreeClassifier(random_state=42) with max_depth 2, 4, 6, 10 and None, run 5-fold stratified cross-validation on the churn training set with return_train_score=True. Print the mean train and validation ROC-AUC for each depth, and the depth with the best validation score. Trees need no scaling: use the given tree_prep.

Expected output
max_depth=2 train 0.743 validation 0.729
max_depth=4 train 0.816 validation 0.778
max_depth=6 train 0.865 validation 0.795
max_depth=10 train 0.953 validation 0.665
max_depth=None train 1.000 validation 0.654
best depth: 6
Starter
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.tree import DecisionTreeClassifier
tree_prep = ColumnTransformer(
[("num", "passthrough", num_cols),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cat_cols)]
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# TODO: for each depth, cross_validate a pipeline with scoring="roc_auc"
# TODO: print mean train and validation scores; find the best depth
Hint 1

cross_validate(..., return_train_score=True) returns a dict with train_score and test_score arrays. With one metric, the keys have no suffix.

Hint 2

Each depth needs a fresh pipeline. sklearn.base.clone(tree_prep) gives an unfitted copy of the preprocessor.

Solution
from sklearn.base import clone
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.tree import DecisionTreeClassifier
tree_prep = ColumnTransformer(
[("num", "passthrough", num_cols),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cat_cols)]
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
val_scores = {}
for depth in [2, 4, 6, 10, None]:
tree = make_pipeline(
clone(tree_prep), DecisionTreeClassifier(max_depth=depth, random_state=42)
)
res = cross_validate(tree, X_train, y_train, cv=cv, scoring="roc_auc",
return_train_score=True)
val_scores[depth] = res["test_score"].mean()
print(f"max_depth={depth!s:<4} train {res['train_score'].mean():.3f}"
f" validation {val_scores[depth]:.3f}")
best_depth = max(val_scores, key=val_scores.get)
print("best depth:", best_depth)
assert val_scores[None] < val_scores[best_depth]
Output
max_depth=2 train 0.743 validation 0.729
max_depth=4 train 0.816 validation 0.778
max_depth=6 train 0.865 validation 0.795
max_depth=10 train 0.953 validation 0.665
max_depth=None train 1.000 validation 0.654
best depth: 6

How it works:

  1. The train score climbs with depth to 1.000 for the unlimited tree: it memorizes every training customer.
  2. The validation score peaks at a middle depth and then falls. The widening gap between the two columns is the sign of overfitting.
  3. The validation folds, not the test set, pick the depth.

Alternative: module 37 draws this table as a validation curve with ValidationCurveDisplay.

M36-C06 · Native categories or one-hot for HistGradientBoosting?

Section titled “M36-C06 · Native categories or one-hot for HistGradientBoosting?”
Core

Compare two ways to feed the text columns to HistGradientBoostingClassifier(random_state=42) on a validation split of the training set (25%, stratified, random_state=42): (a) cast the four text columns to category and let the model handle them, (b) one-hot encode them in a pipeline. Print the validation ROC-AUC of both and the number of input columns each model sees.

Expected output
native categories: ROC-AUC 0.830, 12 columns
one-hot encoded: ROC-AUC 0.827, 22 columns
Starter
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
# TODO: (a) category dtypes, HistGradientBoostingClassifier
# TODO: (b) a pipeline: one-hot encoder for cat_cols, numbers passed through
# TODO: print the validation ROC-AUC and the number of input columns of each
Hint 1

X_fit.astype(cat_dtypes) makes the categorical version, with the level lists from the setup.

Hint 2

For (b), the encoder must return a dense array: OneHotEncoder(handle_unknown="ignore", sparse_output=False). Gradient boosting needs no scaling and handles the missing total_charges itself.

Solution
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
native = HistGradientBoostingClassifier(random_state=42)
native.fit(X_fit.astype(cat_dtypes), y_fit)
auc_native = roc_auc_score(
y_val, native.predict_proba(X_val.astype(cat_dtypes))[:, 1]
)
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
onehot = make_pipeline(
ColumnTransformer([("cat", encoder, cat_cols)], remainder="passthrough"),
HistGradientBoostingClassifier(random_state=42),
).fit(X_fit, y_fit)
auc_onehot = roc_auc_score(y_val, onehot.predict_proba(X_val)[:, 1])
print(f"native categories: ROC-AUC {auc_native:.3f}, {native.n_features_in_} columns")
n_onehot = onehot[-1].n_features_in_
print(f"one-hot encoded: ROC-AUC {auc_onehot:.3f}, {n_onehot} columns")
assert abs(auc_native - auc_onehot) < 0.02
Output
native categories: ROC-AUC 0.830, 12 columns
one-hot encoded: ROC-AUC 0.827, 22 columns

How it works:

  1. With category columns, the default categorical_features="from_dtype" treats them as categories. A split can then group any set of levels, such as “month-to-month or one-year”.
  2. With one-hot columns, each split tests one level against all others, so the model needs more splits for the same rule.
  3. On four low-cardinality columns, both reach about the same score. Native handling keeps 12 columns instead of 22, and it matters more for columns with many levels, where one-hot encoding would add hundreds of sparse columns.

Alternative: for a steadier comparison, run cross_val_score(..., cv=StratifiedKFold(5, shuffle=True, random_state=42), scoring="roc_auc") on both models. It costs five fits per model instead of one.

M36-C07 · Early stopping for XGBoost and LightGBM

Section titled “M36-C07 · Early stopping for XGBoost and LightGBM”
Core

Split a validation set off the training set (25%, stratified, random_state=42) and cast the text columns to category. Train XGBClassifier and LGBMClassifier with up to 500 trees and a learning rate of 0.05, and stop when the validation log loss has not improved for 30 rounds. Print the number of trees each one keeps and its validation ROC-AUC.

Expected output
XGBoost kept 107 trees, validation ROC-AUC 0.848
LightGBM kept 73 trees, validation ROC-AUC 0.847
Starter
import lightgbm
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score
from xgboost import XGBClassifier
X_cat = X_train.astype(cat_dtypes)
X_fit, X_val, y_fit, y_val = train_test_split(
X_cat, y_train, test_size=0.25, stratify=y_train, random_state=42
)
# TODO: XGBClassifier(..., early_stopping_rounds=30), fit with eval_set
# TODO: LGBMClassifier(..., verbose=-1), fit with eval_X, eval_y
# and an early_stopping callback
# TODO: print best iterations and validation ROC-AUC
Hint 1

XGBoost: pass early_stopping_rounds=30, eval_metric="logloss" and enable_categorical=True to the constructor, then fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False). The kept size is best_iteration + 1.

Hint 2

LightGBM 4.7: fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val, callbacks=[lightgbm.early_stopping(30, verbose=False)]). Its older eval_set argument is deprecated. The kept size is best_iteration_.

Solution
import lightgbm
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score
from xgboost import XGBClassifier
X_cat = X_train.astype(cat_dtypes)
X_fit, X_val, y_fit, y_val = train_test_split(
X_cat, y_train, test_size=0.25, stratify=y_train, random_state=42
)
xgb = XGBClassifier(
n_estimators=500, learning_rate=0.05, max_depth=4, enable_categorical=True,
early_stopping_rounds=30, eval_metric="logloss", n_jobs=4, random_state=42,
)
xgb.fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
lgbm = LGBMClassifier(
n_estimators=500, learning_rate=0.05, num_leaves=15, n_jobs=4, verbose=-1,
random_state=42,
)
lgbm.fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val,
callbacks=[lightgbm.early_stopping(30, verbose=False)])
for name, model, n_trees in [
("XGBoost", xgb, xgb.best_iteration + 1),
("LightGBM", lgbm, lgbm.best_iteration_),
]:
auc = roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])
print(f"{name:<8} kept {n_trees:>3} trees, validation ROC-AUC {auc:.3f}")
assert xgb.best_iteration + 1 < 500 and lgbm.best_iteration_ < 500
Output
XGBoost kept 107 trees, validation ROC-AUC 0.848
LightGBM kept 73 trees, validation ROC-AUC 0.847

How it works:

  1. Both libraries score the validation set after each tree. When 30 trees in a row bring no improvement in log loss, training stops.
  2. predict_proba then uses only the best number of trees.
  3. The validation set now chose the model size, so it is no longer an unbiased judge. Report the final score on the untouched test set.

Alternative: HistGradientBoostingClassifier(early_stopping=True, validation_fraction=0.1) splits its own validation set inside fit.

Core

The call center can phone only 10% of the test customers (125 people). Rank the test customers by the churn probability of a logistic regression pipeline and take the top 125. Print the precision and recall of this call list, and the lift: the precision divided by the churn rate.

Expected output
calls 125, churners found 81
precision 0.648, recall 0.336, lift 3.36
Starter
from sklearn.linear_model import LogisticRegression
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
n_calls = int(0.10 * len(X_test))
# TODO: take the n_calls customers with the highest probability
# TODO: print precision, recall and lift of the call list
Hint 1

np.argsort(proba)[::-1][:n_calls] gives the positions of the highest probabilities.

Hint 2

Precision is the churn rate inside the list. Recall is the number of churners in the list over all test churners.

Solution
from sklearn.linear_model import LogisticRegression
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
n_calls = int(0.10 * len(X_test))
top = np.argsort(proba)[::-1][:n_calls]
y_arr = y_test.to_numpy()
found = y_arr[top].sum()
precision_at_k = found / n_calls
recall_at_k = found / y_arr.sum()
lift = precision_at_k / y_arr.mean()
print(f"calls {n_calls}, churners found {found}")
print(f"precision {precision_at_k:.3f}, recall {recall_at_k:.3f}, lift {lift:.2f}")
assert lift > 3
Output
calls 125, churners found 81
precision 0.648, recall 0.336, lift 3.36

How it works:

  1. When capacity is fixed, the threshold is “whatever lets 125 customers through”. Only the ranking matters.
  2. A random list of 125 would hold about 24 churners (19.3%). The model’s list holds far more, so the lift is above 3.
  3. Precision at a fixed list size is the metric to report for capacity-limited campaigns.

M36-C09 · A threshold for a recall target

Section titled “M36-C09 · A threshold for a recall target”
Core

The team wants to find at least 75% of churners. On a validation split of the training set, find the highest threshold of a logistic regression whose validation recall is at least 0.75. Then fit the same model on the fitting part only, apply the threshold to the test set, and print the test precision and recall.

Expected output
threshold 0.190
test precision 0.371, recall 0.776
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_fit, y_fit)
# TODO: precision_recall_curve on the validation probabilities
# TODO: highest threshold with recall >= 0.75
# TODO: test precision and recall at that threshold
Hint 1

precision_recall_curve returns precision, recall and thresholds; the first two have one extra final point. Use recall[:-1] to line them up with thresholds.

Hint 2

thresholds[recall[:-1] >= 0.75].max() is the highest threshold that meets the target.

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
model.fit(X_fit, y_fit)
prec, rec, thr = precision_recall_curve(y_val, model.predict_proba(X_val)[:, 1])
threshold = thr[rec[:-1] >= 0.75].max()
flag = model.predict_proba(X_test)[:, 1] >= threshold
test_recall = recall_score(y_test, flag)
print(f"threshold {threshold:.3f}")
print(f"test precision {precision_score(y_test, flag):.3f}, recall {test_recall:.3f}")
assert 0.1 < threshold < 0.3 and test_recall > 0.7
Output
threshold 0.190
test precision 0.371, recall 0.776

How it works:

  1. Recall can only fall as the threshold rises, so the highest threshold that still meets the target gives the best precision for that recall.
  2. The validation set picks the threshold. The test set only checks it.
  3. The test recall lands near the target, not exactly on it: a different set of customers gives slightly different results.

M36-C10 · Check and fix naive Bayes calibration

Section titled “M36-C10 · Check and fix naive Bayes calibration”
Core

Fit Gaussian naive Bayes in a pipeline on the churn training set, and a CalibratedClassifierCV version with method="sigmoid" and cv=5. For both, print a 5-bin calibration table on the test set (calibration_curve with strategy="quantile") and the Brier score.

Expected output
raw: Brier 0.179
0 1 2 3 4
predicted 0.000 0.026 0.244 0.570 0.884
observed 0.024 0.056 0.144 0.236 0.504
calibrated: Brier 0.125
0 1 2 3 4
predicted 0.050 0.055 0.112 0.266 0.506
observed 0.024 0.056 0.144 0.236 0.504
Starter
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.metrics import brier_score_loss
from sklearn.naive_bayes import GaussianNB
# TODO: raw = make_pipeline(make_preprocess(), GaussianNB())
# TODO: calibrated = CalibratedClassifierCV(<a fresh NB pipeline>,
# method="sigmoid", cv=5)
# TODO: for each: calibration_curve(..., n_bins=5, strategy="quantile"), print, Brier
Hint 1

calibration_curve(y_true, proba, n_bins=5, strategy="quantile") returns (prob_true, prob_pred): the observed rate first, the mean prediction second.

Hint 2

Put the two arrays in a small DataFrame with columns predicted and observed to print them side by side.

Solution
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.metrics import brier_score_loss
from sklearn.naive_bayes import GaussianNB
models = {
"raw": make_pipeline(make_preprocess(), GaussianNB()),
"calibrated": CalibratedClassifierCV(
make_pipeline(make_preprocess(), GaussianNB()), method="sigmoid", cv=5
),
}
briers = {}
for name, model in models.items():
proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
observed, predicted = calibration_curve(
y_test, proba, n_bins=5, strategy="quantile"
)
briers[name] = brier_score_loss(y_test, proba)
print(f"{name}: Brier {briers[name]:.3f}")
print(pd.DataFrame({"predicted": predicted, "observed": observed}).round(3).T)
assert briers["calibrated"] < briers["raw"]
Output
raw: Brier 0.179
0 1 2 3 4
predicted 0.000 0.026 0.244 0.570 0.884
observed 0.024 0.056 0.144 0.236 0.504
calibrated: Brier 0.125
0 1 2 3 4
predicted 0.050 0.055 0.112 0.266 0.506
observed 0.024 0.056 0.144 0.236 0.504

How it works:

  1. In the raw table, the top bins predict far more churn than they observe: the model is overconfident.
  2. After sigmoid calibration, the two rows nearly match in every bin.
  3. The Brier score drops by about a third. The observed row is the same in both tables: calibration keeps the order of the customers, so the quantile bins hold the same customers and the ROC-AUC barely changes.

M36-C11 · Multiclass iris with two features

Section titled “M36-C11 · Multiclass iris with two features”
Core

Use only sepal length (cm) and sepal width (cm) of the iris data. Split 70/30 with stratification and random_state=42, fit a scaled logistic regression, and print the classification report with the species names. Which species is hardest to tell apart?

Expected output
precision recall f1-score support
setosa 1.000 1.000 1.000 15
versicolor 0.600 0.600 0.600 15
virginica 0.600 0.600 0.600 15
accuracy 0.733 45
macro avg 0.733 0.733 0.733 45
weighted avg 0.733 0.733 0.733 45
Starter
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
iris = load_iris(as_frame=True)
Xi = iris.data[["sepal length (cm)", "sepal width (cm)"]]
# TODO: split, fit, print classification_report(..., target_names=iris.target_names)
Hint 1

LogisticRegression handles three classes on its own with a multinomial model.

Hint 2

Pass digits=3 to the report for three decimals.

Solution
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, f1_score
iris = load_iris(as_frame=True)
Xi = iris.data[["sepal length (cm)", "sepal width (cm)"]]
Xi_train, Xi_test, yi_train, yi_test = train_test_split(
Xi, iris.target, test_size=0.3, stratify=iris.target, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pred = model.fit(Xi_train, yi_train).predict(Xi_test)
print(classification_report(yi_test, pred, target_names=iris.target_names, digits=3))
per_class = f1_score(yi_test, pred, average=None)
assert per_class[0] > per_class[1] and per_class[0] > per_class[2]
Output
precision recall f1-score support
setosa 1.000 1.000 1.000 15
versicolor 0.600 0.600 0.600 15
virginica 0.600 0.600 0.600 15
accuracy 0.733 45
macro avg 0.733 0.733 0.733 45
weighted avg 0.733 0.733 0.733 45

How it works:

  1. Setosa has short, wide sepals, so the two features separate it perfectly.
  2. Versicolor and virginica overlap in sepal size, so most errors are between them.
  3. The classes are balanced (15 each in the test set), so macro and weighted averages are equal.

Alternative: add the petal features. With all four features the same model separates the species almost perfectly. The weak result comes from the input, not from the algorithm.

M36-C12 · Refactor: threshold loop to precision_recall_curve

Section titled “M36-C12 · Refactor: threshold loop to precision_recall_curve”
Core

Refactor: the code below loops over 69 thresholds and computes precision and recall one by one. Replace the loop with one call to precision_recall_curve, then interpolate: for each threshold of the loop, take the curve point of the smallest curve threshold that is at or above it. Check that both give the same numbers.

Expected output
69 grid thresholds, 1250 curve thresholds
same precision: True
same recall: True
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
grid = np.round(np.arange(0.01, 0.70, 0.01), 2)
loop_p, loop_r = [], []
for t in grid:
flag = proba >= t
loop_p.append(precision_score(y_test, flag, zero_division=0))
loop_r.append(recall_score(y_test, flag))
# TODO: prec, rec, thr = precision_recall_curve(...)
# TODO: for each grid value, find the index with np.searchsorted(thr, grid)
Hint 1

The thresholds returned by precision_recall_curve are sorted from low to high, and point i flags everyone with proba >= thr[i].

Hint 2

np.searchsorted(thr, grid, side="left") gives, for each grid value, the index of the first curve threshold that is at or above it.

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
grid = np.round(np.arange(0.01, 0.70, 0.01), 2)
loop_p, loop_r = [], []
for t in grid:
flag = proba >= t
loop_p.append(precision_score(y_test, flag, zero_division=0))
loop_r.append(recall_score(y_test, flag))
prec, rec, thr = precision_recall_curve(y_test, proba)
idx = np.searchsorted(thr, grid, side="left")
vec_p, vec_r = prec[idx], rec[idx]
print(f"{len(grid)} grid thresholds, {len(thr)} curve thresholds")
print("same precision:", np.allclose(loop_p, vec_p))
print("same recall: ", np.allclose(loop_r, vec_r))
assert np.allclose(loop_p, vec_p) and np.allclose(loop_r, vec_r)
Output
69 grid thresholds, 1250 curve thresholds
same precision: True
same recall: True

How it works:

  1. precision_recall_curve sorts the scores once and computes every point in one pass. The loop recomputes the confusion matrix for each threshold.
  2. The precision and recall only change at observed scores. Between two scores, they stay constant, so the next curve threshold at or above t gives exactly the loop’s values.
  3. On this data the grid tops out at 0.69, below the largest probability, so every grid value finds a curve point.

M36-C13 · Choose the right metric for each decision

Section titled “M36-C13 · Choose the right metric for each decision”
Core

Choose a method and justify it: compare logistic regression and Gaussian naive Bayes (both in pipelines, fitted on X_fit) on a validation split of the training set (25%, stratified, random_state=42) for three decisions: (a) rank customers for a long campaign (ROC-AUC), (b) forecast how many customers churn next month (the sum of probabilities against the true count), (c) a call list of the top 100 customers (precision in the top 100). Print the metric for each model and the winner of each decision.

Expected output
ranking (ROC-AUC) logistic 0.814 naive Bayes 0.796 -> logistic
forecast error logistic 11.590 naive Bayes 124.829 -> logistic
top-100 precision logistic 0.590 naive Bayes 0.650 -> naive Bayes
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.naive_bayes import GaussianNB
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
# TODO: fit both pipelines on X_fit, get the validation probabilities
# TODO: (a) ROC-AUC (b) |sum(proba) - true churners| (c) churners among the top 100
# TODO: print one line per decision with both values and the winner
Hint 1

For (b), a smaller error wins; for (a) and (c), a larger value wins.

Hint 2

Write a small helper top_k_precision(y, proba, k) with np.argsort(proba)[::-1][:k].

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.naive_bayes import GaussianNB
def top_k_precision(y_true: np.ndarray, proba: np.ndarray, k: int) -> float:
return float(y_true[np.argsort(proba)[::-1][:k]].mean())
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
y_arr = y_val.to_numpy()
probas = {
name: make_pipeline(make_preprocess(), est).fit(X_fit, y_fit)
.predict_proba(X_val)[:, 1]
for name, est in [("logistic", LogisticRegression(max_iter=1000)),
("naive Bayes", GaussianNB())]
}
decisions = {
"ranking (ROC-AUC)": (lambda p: roc_auc_score(y_arr, p), max),
"forecast error": (lambda p: abs(p.sum() - y_arr.sum()), min),
"top-100 precision": (lambda p: top_k_precision(y_arr, p, 100), max),
}
winners = {}
for decision, (metric, better) in decisions.items():
values = {name: metric(p) for name, p in probas.items()}
winners[decision] = better(values, key=values.get)
shown = " ".join(f"{name} {v:.3f}" for name, v in values.items())
print(f"{decision:<18} {shown} -> {winners[decision]}")
assert winners["forecast error"] == "logistic"
Output
ranking (ROC-AUC) logistic 0.814 naive Bayes 0.796 -> logistic
forecast error logistic 11.590 naive Bayes 124.829 -> logistic
top-100 precision logistic 0.590 naive Bayes 0.650 -> naive Bayes

How it works:

  1. The comparison uses validation rows only, so the test set stays untouched for the final report of whichever model each decision picks.
  2. Logistic regression wins the ranking by a small margin: both models order customers almost equally well.
  3. The forecast shows the real gap. Naive Bayes predicts far more churners than there are, because its probabilities are too large.
  4. The winner depends on the decision. Logistic regression ranks better overall and forecasts far better, but naive Bayes puts more churners into this particular top 100 (65 against 59). Pick the metric from the decision, then compare models on it.

M36-X01 · Compare four models with cross-validation

Section titled “M36-X01 · Compare four models with cross-validation”
Challenge

Build a model-comparison table for logistic regression, a random forest (300 trees, min_samples_leaf=5), XGBoost and LightGBM (200 trees, learning rate 0.05 each). Use 5-fold stratified cross-validation on the training set with ROC-AUC, average precision and Brier score. Sort by ROC-AUC, then score the winner once on the test set.

Expected output
roc_auc pr_auc brier
model
XGBoost 0.840 0.604 0.112
random forest 0.838 0.600 0.113
LightGBM 0.835 0.605 0.113
logistic 0.813 0.553 0.119
XGBoost test ROC-AUC 0.838
Starter
from lightgbm import LGBMClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from xgboost import XGBClassifier
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
# TODO: a dict of four models; the forest needs one-hot columns
# TODO: cross_validate each with scoring roc_auc, average_precision, neg_brier_score
# TODO: a sorted DataFrame; refit the winner and print its test ROC-AUC
Hint 1

All models can read X_train_cat: the pipelines one-hot encode the category columns, and the two boosting libraries use them directly (XGBoost needs enable_categorical=True).

Hint 2

The forest needs no scaling: a ColumnTransformer with the one-hot encoder for cat_cols and remainder="passthrough" is enough. The Brier scorer is negated; flip its sign.

Solution
from lightgbm import LGBMClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_validate
from xgboost import XGBClassifier
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
onehot = ColumnTransformer(
[("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cat_cols)],
remainder="passthrough",
)
models = {
"logistic": make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000)),
"random forest": make_pipeline(onehot, RandomForestClassifier(
n_estimators=300, min_samples_leaf=5, n_jobs=-1, random_state=42)),
"XGBoost": XGBClassifier(n_estimators=200, learning_rate=0.05, max_depth=4,
enable_categorical=True, n_jobs=4, random_state=42),
"LightGBM": LGBMClassifier(n_estimators=200, learning_rate=0.05, num_leaves=15,
n_jobs=4, verbose=-1, random_state=42),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
rows = []
for name, model in models.items():
res = cross_validate(model, X_train_cat, y_train, cv=cv,
scoring=["roc_auc", "average_precision", "neg_brier_score"])
rows.append({"model": name, "roc_auc": res["test_roc_auc"].mean(),
"pr_auc": res["test_average_precision"].mean(),
"brier": -res["test_neg_brier_score"].mean()})
table = pd.DataFrame(rows).set_index("model").sort_values("roc_auc", ascending=False)
print(table.round(3))
winner = table.index[0]
best = models[winner].fit(X_train_cat, y_train)
test_auc = roc_auc_score(y_test, best.predict_proba(X_test_cat)[:, 1])
print(f"{winner} test ROC-AUC {test_auc:.3f}")
assert table["roc_auc"].min() > 0.8 and abs(test_auc - table["roc_auc"].iloc[0]) < 0.02
Output
roc_auc pr_auc brier
model
XGBoost 0.840 0.604 0.112
random forest 0.838 0.600 0.113
LightGBM 0.835 0.605 0.113
logistic 0.813 0.553 0.119
XGBoost test ROC-AUC 0.838

How it works:

  1. Every model sees the same five folds, so the comparison is fair.
  2. The table reports three views: ranking (ROC-AUC), the rare class (PR-AUC) and probability quality (Brier).
  3. The test set is used once, for the winner. Its score is close to the cross-validation mean, as it should be.

Alternative: add return_estimator=True to keep the fitted fold models, or n_jobs=-1 in cross_validate to run the folds in parallel on a larger machine.

M36-X02 · A cost-optimal threshold with TunedThresholdClassifierCV

Section titled “M36-X02 · A cost-optimal threshold with TunedThresholdClassifierCV”
Challenge

A cheaper offer costs USD 30 per contact, and a lost churner costs USD 240. Write the cost function, tune the threshold of an LGBMClassifier(n_estimators=200, learning_rate=0.05, num_leaves=15, n_jobs=4, verbose=-1, random_state=42) with TunedThresholdClassifierCV (5 folds, minimize the cost) on the training set, and compare three test costs: the default threshold 0.5, the tuned threshold, and the theoretical threshold 30 / 240 applied with FixedThresholdClassifier.

Expected output
default threshold 0.500 test cost 39,360
tuned threshold 0.101 test cost 25,920
theory threshold 0.125 test cost 26,400
Starter
from lightgbm import LGBMClassifier
from sklearn.metrics import confusion_matrix, make_scorer
from sklearn.model_selection import FixedThresholdClassifier, TunedThresholdClassifierCV
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
def campaign_cost(y_true, flagged) -> int:
# TODO: 30 per flagged customer, 240 per missed churner
...
# TODO: tuned = TunedThresholdClassifierCV(
# ..., scoring=make_scorer(..., greater_is_better=False))
# TODO: print the three thresholds and their test costs
Hint 1

confusion_matrix(y_true, flagged, labels=[0, 1]).ravel() gives TN, FP, FN, TP. Flagged customers are TP + FP.

Hint 2

FixedThresholdClassifier(model, threshold=0.125) fits the model inside its own fit, then thresholds predict_proba at 0.125.

Solution
from lightgbm import LGBMClassifier
from sklearn.base import clone
from sklearn.metrics import confusion_matrix, make_scorer
from sklearn.model_selection import (
FixedThresholdClassifier,
StratifiedKFold,
TunedThresholdClassifierCV,
)
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
def campaign_cost(y_true, flagged) -> int:
tn, fp, fn, tp = confusion_matrix(y_true, flagged, labels=[0, 1]).ravel()
return int(30 * (tp + fp) + 240 * fn)
lgbm = LGBMClassifier(n_estimators=200, learning_rate=0.05, num_leaves=15,
n_jobs=4, verbose=-1, random_state=42)
tuned = TunedThresholdClassifierCV(
lgbm,
scoring=make_scorer(campaign_cost, greater_is_better=False),
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),
).fit(X_train_cat, y_train)
fixed = FixedThresholdClassifier(lgbm, threshold=30 / 240).fit(X_train_cat, y_train)
default = clone(lgbm).fit(X_train_cat, y_train)
costs = {}
for name, threshold, model in [
("default", 0.5, default),
("tuned", tuned.best_threshold_, tuned),
("theory", 30 / 240, fixed),
]:
costs[name] = campaign_cost(y_test, model.predict(X_test_cat))
print(f"{name:<8} threshold {threshold:.3f} test cost {costs[name]:,}")
assert costs["tuned"] < costs["default"] and costs["theory"] < costs["default"]
Output
default threshold 0.500 test cost 39,360
tuned threshold 0.101 test cost 25,920
theory threshold 0.125 test cost 26,400

How it works:

  1. The cost function counts what each decision costs. make_scorer(..., greater_is_better=False) tells scikit-learn to minimize it.
  2. TunedThresholdClassifierCV scores many thresholds on each validation fold, picks the one with the lowest mean cost, then refits on the whole training set. Pass a shuffled StratifiedKFold for reproducible folds; its own random_state only matters when cv is a float (a single validation fraction).
  3. The theoretical threshold 30/240=0.12530/240 = 0.125 needs no tuning, but it trusts the probabilities. Both beat the default by about a third. The tuned threshold (0.101) and the theory (0.125) are close, and their costs differ by less than 2%: the cost curve is flat near its minimum. The closeness of the two thresholds suggests that the LightGBM probabilities are roughly calibrated; a calibration curve on validation data would confirm it.
Challenge

On the breast cancer data (malignant = 1, 75/25 stratified split, random_state=42), fit a scaled SVC and get probabilities without probability=True: wrap the pipeline in CalibratedClassifierCV with ensemble=False and 5 folds. Print the test ROC-AUC from decision_function and from the calibrated probabilities, the log loss and Brier score of the probabilities, and how often predict disagrees with predict_proba >= 0.5.

Expected output
ROC-AUC decision_function 0.9966, calibrated 0.9966
log loss 0.073, Brier 0.019
predict vs proba disagreements: 0
Starter
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.svm import SVC
cancer = load_breast_cancer(as_frame=True)
yb = (cancer.target == 0).astype(int)
# TODO: split; svm = make_pipeline(StandardScaler(), SVC())
# TODO: calibrated = CalibratedClassifierCV(<fresh svm pipeline>, ensemble=False, cv=5)
# TODO: print the five numbers
Hint 1

Fit the plain pipeline for decision_function, and a separate calibrated wrapper for predict_proba.

Hint 2

CalibratedClassifierCV.predict returns the class with the highest calibrated probability, so compare it with proba >= 0.5.

Solution
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.svm import SVC
cancer = load_breast_cancer(as_frame=True)
yb = (cancer.target == 0).astype(int)
Xb_train, Xb_test, yb_train, yb_test = train_test_split(
cancer.data, yb, test_size=0.25, stratify=yb, random_state=42
)
svm = make_pipeline(StandardScaler(), SVC()).fit(Xb_train, yb_train)
calibrated = CalibratedClassifierCV(
make_pipeline(StandardScaler(), SVC()), ensemble=False, cv=5
).fit(Xb_train, yb_train)
proba = calibrated.predict_proba(Xb_test)[:, 1]
auc_scores = roc_auc_score(yb_test, svm.decision_function(Xb_test))
auc_proba = roc_auc_score(yb_test, proba)
disagree = int((calibrated.predict(Xb_test) != (proba >= 0.5)).sum())
print(f"ROC-AUC decision_function {auc_scores:.4f}, calibrated {auc_proba:.4f}")
print(f"log loss {log_loss(yb_test, proba):.3f}, "
f"Brier {brier_score_loss(yb_test, proba):.3f}")
print("predict vs proba disagreements:", disagree)
assert np.isclose(auc_scores, auc_proba) and disagree == 0
Output
ROC-AUC decision_function 0.9966, calibrated 0.9966
log loss 0.073, Brier 0.019
predict vs proba disagreements: 0

How it works:

  1. ensemble=False fits one SVM on all training rows for the final model. The calibrator, a sigmoid on the SVM score, learns from out-of-fold scores of 5 cross-validation fits.
  2. The sigmoid is increasing, so the ranking, and the ROC-AUC, does not change.
  3. Unlike SVC(probability=True), predict and predict_proba agree: both come from the same calibrated probabilities.

Alternative: if only a ranking is needed (a review queue sorted by risk), skip calibration and sort by decision_function.

M36-X04 · One-vs-rest, one-vs-one or multinomial on wine?

Section titled “M36-X04 · One-vs-rest, one-vs-one or multinomial on wine?”
Challenge

Choose a method and justify it: on all 13 wine features, compare four scaled models with 5-fold stratified cross-validation (macro F1 and multiclass log loss): multinomial LogisticRegression, OneVsRestClassifier(LogisticRegression), OneVsOneClassifier(LogisticRegression) and SVC. Print a table and the number of binary models that OvR and OvO train for 3 classes.

Expected output
macro_f1 log_loss
model
multinomial 0.983 0.061
one-vs-rest 0.983 0.080
one-vs-one 0.989 NaN
SVC (ovo inside) 0.983 NaN
one-vs-rest: 3 binary models
one-vs-one: 3 binary models
Starter
from sklearn.datasets import load_wine
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.svm import SVC
wine = load_wine(as_frame=True)
# TODO: four pipelines with StandardScaler
# TODO: scoring=["f1_macro", "neg_log_loss"] where predict_proba exists
# TODO: table; then fit OvR and OvO once and count estimators_
Hint 1

OneVsOneClassifier and SVC have no predict_proba, so use f1_macro only for them.

Hint 2

After fitting, len(pipeline[-1].estimators_) counts the binary models inside the wrapper.

Solution
from sklearn.datasets import load_wine
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.svm import SVC
wine = load_wine(as_frame=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
lr = LogisticRegression(max_iter=1000)
models = {
"multinomial": make_pipeline(StandardScaler(), lr),
"one-vs-rest": make_pipeline(StandardScaler(), OneVsRestClassifier(lr)),
"one-vs-one": make_pipeline(StandardScaler(), OneVsOneClassifier(lr)),
"SVC (ovo inside)": make_pipeline(StandardScaler(), SVC()),
}
rows = []
for name, model in models.items():
scoring = ["f1_macro"]
if hasattr(model, "predict_proba"):
scoring.append("neg_log_loss")
res = cross_validate(model, wine.data, wine.target, cv=cv, scoring=scoring)
loss = -res["test_neg_log_loss"].mean() if "test_neg_log_loss" in res else np.nan
rows.append({"model": name, "macro_f1": res["test_f1_macro"].mean(),
"log_loss": loss})
print(pd.DataFrame(rows).set_index("model").round(3))
for name in ["one-vs-rest", "one-vs-one"]:
fitted = models[name].fit(wine.data, wine.target)
print(f"{name}: {len(fitted[-1].estimators_)} binary models")
assert min(r["macro_f1"] for r in rows) > 0.95
Output
macro_f1 log_loss
model
multinomial 0.983 0.061
one-vs-rest 0.983 0.080
one-vs-one 0.989 NaN
SVC (ovo inside) 0.983 NaN
one-vs-rest: 3 binary models
one-vs-one: 3 binary models

How it works:

  1. With 13 informative features, all four strategies separate the cultivars almost perfectly. The macro F1 differences are one or two wines out of 178, too few to rank the strategies.
  2. The log loss still differs: it shows how confident and how right the probabilities are. One-vs-one and SVC give none.
  3. For 3 classes, OvR and OvO both train 3 binary models (K=3K = 3 and K(K−1)/2=3K(K-1)/2 = 3). For 10 classes, OvO would train 45.
  4. Choose multinomial logistic regression: one model, good probabilities, the default. Reach for OvR or OvO only to make a binary-only model multiclass.

M36-X05 · Refactor: a reusable thresholded classifier class

Section titled “M36-X05 · Refactor: a reusable thresholded classifier class”
Challenge

Refactor procedural code into a class: write ThresholdedClassifier with __init__(self, model, threshold), fit(X, y) (returns self), predict_proba(X) and predict(X) that flags rows whose churn probability is at or above the threshold. Use type hints. Check that it gives the same predictions as scikit-learn’s FixedThresholdClassifier for a logistic regression at 0.25, and print the number of flagged test customers.

Expected output
flagged: 404 | identical: True
Starter
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import FixedThresholdClassifier
class ThresholdedClassifier:
"""Wrap a probabilistic classifier and apply a custom decision threshold."""
def __init__(self, model, threshold: float = 0.5) -> None:
# TODO: store a clone of the model and the threshold
...
# TODO: fit, predict_proba, predict
Hint 1

Store clone(model) so that fitting the wrapper never changes the model object that the caller passed in.

Hint 2

predict is (self.predict_proba(X)[:, 1] >= self.threshold).astype(int).

Solution
from typing import Self
from sklearn.base import ClassifierMixin, clone
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import FixedThresholdClassifier
class ThresholdedClassifier:
"""Wrap a probabilistic classifier and apply a custom decision threshold."""
def __init__(self, model: ClassifierMixin, threshold: float = 0.5) -> None:
if not 0 < threshold < 1:
raise ValueError("threshold must be between 0 and 1")
self.model = clone(model)
self.threshold = threshold
def fit(self, X: pd.DataFrame, y: pd.Series) -> Self:
self.model.fit(X, y)
return self
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
return self.model.predict_proba(X)
def predict(self, X: pd.DataFrame) -> np.ndarray:
return (self.predict_proba(X)[:, 1] >= self.threshold).astype(int)
base = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))
mine = ThresholdedClassifier(base, threshold=0.25).fit(X_train, y_train)
theirs = FixedThresholdClassifier(base, threshold=0.25).fit(X_train, y_train)
ours, ref = mine.predict(X_test), theirs.predict(X_test)
print("flagged:", ours.sum(), "| identical:", np.array_equal(ours, ref))
assert np.array_equal(ours, ref)
Output
flagged: 404 | identical: True

How it works:

  1. clone copies the hyperparameters but not the fitted state, as scikit-learn’s own meta-estimators do.
  2. fit returns self, so ThresholdedClassifier(...).fit(...) chains like any estimator. Self (Python 3.11+) types that return value.
  3. The threshold check in __init__ fails fast on a bad value instead of silently flagging everyone.
  4. Both wrappers apply “at or above the threshold” to the same probabilities, so the predictions match row for row.

Alternative: in production, use FixedThresholdClassifier itself. It is a full scikit-learn estimator: it works with clone, pipelines, GridSearchCV and joblib persistence.

Challenge

Marketing teams read a model through a gains table. Score the test customers with HistGradientBoostingClassifier(random_state=42) (category columns), sort them into 10 equal groups (deciles) by predicted churn, highest risk first, and print per decile: the number of customers, the churn rate, the lift (churn rate over the overall rate) and the cumulative share of all churners captured. How many churners do the top 3 deciles catch?

Expected output
customers churners churn_rate lift captured
decile
1 125 81 0.648 3.361 0.336
2 125 54 0.432 2.241 0.560
3 125 34 0.272 1.411 0.701
4 125 19 0.152 0.788 0.780
5 125 19 0.152 0.788 0.859
6 125 15 0.120 0.622 0.921
7 125 6 0.048 0.249 0.946
8 125 7 0.056 0.290 0.975
9 125 4 0.032 0.166 0.992
10 125 2 0.016 0.083 1.000
top 3 deciles catch 70.1% of churners
Starter
from sklearn.ensemble import HistGradientBoostingClassifier
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
# TODO: fit, predict the churn probability for the test set
# TODO: decile 1 = highest 10% of probabilities (pd.qcut on the rank)
# TODO: groupby decile: count, churn rate; then lift and cumulative capture
Hint 1

Rank first to break ties: pd.qcut(-proba_series.rank(method="first"), 10, labels=range(1, 11)) puts the highest probabilities in decile 1.

Hint 2

Cumulative capture is churners.cumsum() / churners.sum() after sorting by decile.

Solution
from sklearn.ensemble import HistGradientBoostingClassifier
X_train_cat = X_train.astype(cat_dtypes)
X_test_cat = X_test.astype(cat_dtypes)
hgb = HistGradientBoostingClassifier(random_state=42).fit(X_train_cat, y_train)
scored = pd.DataFrame({
"proba": hgb.predict_proba(X_test_cat)[:, 1],
"churned": y_test.to_numpy(),
})
scored["decile"] = pd.qcut(
-scored["proba"].rank(method="first"), 10, labels=range(1, 11)
)
gains = scored.groupby("decile", observed=True).agg(
customers=("churned", "size"),
churners=("churned", "sum"),
churn_rate=("churned", "mean"),
)
gains["lift"] = gains["churn_rate"] / scored["churned"].mean()
gains["captured"] = gains["churners"].cumsum() / gains["churners"].sum()
print(gains.round(3))
top3 = gains["captured"].iloc[2]
print(f"top 3 deciles catch {top3:.1%} of churners")
assert gains["lift"].iloc[0] > 3 and gains["captured"].iloc[-1] == 1.0
Output
customers churners churn_rate lift captured
decile
1 125 81 0.648 3.361 0.336
2 125 54 0.432 2.241 0.560
3 125 34 0.272 1.411 0.701
4 125 19 0.152 0.788 0.780
5 125 19 0.152 0.788 0.859
6 125 15 0.120 0.622 0.921
7 125 6 0.048 0.249 0.946
8 125 7 0.056 0.290 0.975
9 125 4 0.032 0.166 0.992
10 125 2 0.016 0.083 1.000
top 3 deciles catch 70.1% of churners

How it works:

  1. Ranking with method="first" gives every customer a unique rank, so qcut makes 10 groups of exactly 125. The minus sign puts the highest probabilities in decile 1.
  2. The churn rate falls from decile to decile: the model ranks well. Lift above 1 means the decile is richer in churners than average.
  3. The cumulative capture answers the budget question directly: calling 30% of customers reaches the share of churners shown in the last line.

Alternative: the same table drives a gains chart: plot captured against the share of customers called. The diagonal is a random call list.