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:
- Copy the setup block below into the top of your script. Every exercise assumes it ran first.
- Copy the starter code under it and replace each to-do comment with your code.
- Run the script and compare your output with the expected output.
- 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 npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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, )Warm-up
Section titled “Warm-up”M36-W01 · Metrics from a confusion matrix
Section titled “M36-W01 · Metrics from a confusion matrix”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.
accuracy: 0.900precision: 0.455recall: 0.556F1: 0.500specificity: 0.934tn, fp, fn, tp = 850, 60, 40, 50# TODO: compute accuracy, precision, recall, f1 and specificity# TODO: print each as "name: value" with 3 decimalsHint 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, 50accuracy = (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.9assert round(precision, 3) == 0.455 and round(recall, 3) == 0.556accuracy: 0.900precision: 0.455recall: 0.556F1: 0.500specificity: 0.934How it works:
- Accuracy counts the correct cells (TN and TP) over all 1,000 payments.
- 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.
- 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}")0.455 0.556 0.500M36-W02 · Probabilities, odds and log-odds
Section titled “M36-W02 · Probabilities, odds and log-odds”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.
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 . 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])[0.5 0.75 0.2 ][1. 3. 0.25]How it works:
- The sigmoid maps log-odds 0 to 0.5: churn and stay are equally likely.
- Log-odds means odds of 3 to 1, so .
- Log-odds means odds of 1 to 4, so , 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))0.75 -1.386 -1.386M36-W03 · The accuracy trap
Section titled “M36-W03 · The accuracy trap”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.
accuracy 0.807, recall 0.000, ROC-AUC 0.500from sklearn.dummy import DummyClassifierfrom 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 setHint 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 DummyClassifierfrom 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.5accuracy 0.807, recall 0.000, ROC-AUC 0.500How it works:
- “Most frequent” predicts “stays” for everyone. 80.7% of test customers stay, so that is the accuracy.
- It never flags a churner, so recall is 0.
- 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”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.
from labels: 0.633ROC-AUC 0.813from sklearn.linear_model import LogisticRegressionfrom 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 LogisticRegressionfrom 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.65from labels: 0.633ROC-AUC 0.813How it works:
predictreturns 0/1 labels at the 0.5 threshold. ROC-AUC on labels sees only two scores and one point on the curve.- Its value equals the mean of recall and specificity at 0.5, a threshold metric, not a ranking metric.
- Column 1 of
predict_probakeeps 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”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.
by hand: precision 0.600, recall 0.750sklearn: precision 0.600, recall 0.750from 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)by hand: precision 0.600, recall 0.750sklearn: precision 0.600, recall 0.750How it works:
confusion_matrix(y_true, y_pred)puts the true classes in rows. The swapped call put them in columns.- 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.
- 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).
M36-W06 · Apply a custom threshold
Section titled “M36-W06 · Apply a custom threshold”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.
[0 1 0 1 1 0 1 0]calls: 4ids: ['C00203', 'C01022', 'C01980', 'C03007']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 idsHint 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][0 1 0 1 1 0 1 0]calls: 4ids: ['C00203', 'C01022', 'C01980', 'C03007']How it works:
>=includes the boundary, so the customer at exactly 0.30 gets a call; 0.29 does not.- scikit-learn’s
FixedThresholdClassifieruses the same “at or above” rule. Plainpredictis slightly different: it needs a probability strictly above 0.5, so an exact tie goes to class 0. With continuous probabilities, ties are rare. - 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.
M36-W07 · Read odds ratios
Section titled “M36-W07 · Read odds ratios”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.
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%)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 tenureHint 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: , which equals .
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.50assert round(year, 3) == round(odds_ratios["tenure_months"] ** 12, 3)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:
- Autopay halves the churn odds (odds ratio 0.50, −49.8%) compared with an otherwise identical customer without autopay.
- Each support ticket raises the odds by 60%.
- 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”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.
log loss: 0.5403 (sklearn 0.5403)Brier: 0.1925 (sklearn 0.1925)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 valuesHint 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))log loss: 0.5403 (sklearn 0.5403)Brier: 0.1925 (sklearn 0.1925)How it works:
- The terms are , , and . The two wrong-side predictions (0.4 for a churner, 0.6 for a stayer) cost most.
- The Brier terms are 0.01, 0.04, 0.36 and 0.36; their mean is 0.1925.
- 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”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.
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))macro F1 0.552weighted F1 0.754micro F1 0.800accuracy 0.800How it works:
- Per class:
billinghas precision 6/8 and recall 1, so F1 0.857;bughas F1 0.8;loginhas F1 0. - Macro = (0.857 + 0.8 + 0) / 3 = 0.552: the missed rare class costs a third.
- Weighted = (6 × 0.857 + 3 × 0.8 + 1 × 0) / 10 = 0.754. Micro pools all decisions, so it equals the accuracy, 0.8.
- No ticket is predicted as
login, yetf1_scoregives 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 ofloginis 0/0; passzero_division=0there.
M36-C01 · A logistic regression churn model
Section titled “M36-C01 · A logistic regression churn model”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.
ROC-AUC 0.813, average precision 0.557[[972 37] [168 73]]from sklearn.linear_model import LogisticRegressionfrom 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 matrixHint 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 LogisticRegressionfrom 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)ROC-AUC 0.813, average precision 0.557[[972 37] [168 73]]How it works:
- The pipeline imputes, scales and encodes inside
fit, using training rows only. - 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.
- 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?”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?
payment_method_electronic_check 1.450payment_method_paypal 0.846payment_method_credit_card 0.812contract_one-year 0.349contract_two-year 0.178dtype: float64contract reference: month-to-monthpayment_method reference: bank_transferfrom 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_methodHint 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"] < 1payment_method_electronic_check 1.450payment_method_paypal 0.846payment_method_credit_card 0.812contract_one-year 0.349contract_two-year 0.178dtype: float64contract reference: month-to-monthpayment_method reference: bank_transferHow it works:
str.startswithaccepts a tuple of prefixes, so one mask keeps both groups.- 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.
- 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”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.
k=5 validation ROC-AUC 0.692k=15 validation ROC-AUC 0.760k=50 validation ROC-AUC 0.785k=150 validation ROC-AUC 0.791best k=150, test ROC-AUC 0.794from sklearn.metrics import roc_auc_scorefrom 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-AUCHint 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_scorefrom 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]k=5 validation ROC-AUC 0.692k=15 validation ROC-AUC 0.760k=50 validation ROC-AUC 0.785k=150 validation ROC-AUC 0.791best k=150, test ROC-AUC 0.794How it works:
k=5votes with very few neighbors, so its probabilities jump in steps of 0.2 and follow noise. The score rises withkand then levels off.- The choice uses the validation part only. The test set is opened once, for the final number.
- 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?”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.
naive Bayes CV ROC-AUC 0.986 CV Brier 0.058logistic CV ROC-AUC 0.991 CV Brier 0.022chosen: logistic, test Brier 0.022from sklearn.datasets import load_breast_cancerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import brier_score_loss, roc_auc_scorefrom 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 onceHint 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_cancerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import brier_score_lossfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom sklearn.naive_bayes import GaussianNB
cancer = load_breast_cancer(as_frame=True)yb = (cancer.target == 0).astype(int) # 1 = malignantXb_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"naive Bayes CV ROC-AUC 0.986 CV Brier 0.058logistic CV ROC-AUC 0.991 CV Brier 0.022chosen: logistic, test Brier 0.022How it works:
- Both models rank almost perfectly in cross-validation. The Brier score of naive Bayes is far higher.
- 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.
- For a percentage that a person reads, choose logistic regression: its probabilities are closer to the truth. Naive Bayes would need calibration first.
- 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”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.
max_depth=2 train 0.743 validation 0.729max_depth=4 train 0.816 validation 0.778max_depth=6 train 0.865 validation 0.795max_depth=10 train 0.953 validation 0.665max_depth=None train 1.000 validation 0.654best depth: 6from sklearn.model_selection import StratifiedKFold, cross_validatefrom 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 depthHint 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 clonefrom sklearn.model_selection import StratifiedKFold, cross_validatefrom 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]max_depth=2 train 0.743 validation 0.729max_depth=4 train 0.816 validation 0.778max_depth=6 train 0.865 validation 0.795max_depth=10 train 0.953 validation 0.665max_depth=None train 1.000 validation 0.654best depth: 6How it works:
- The train score climbs with depth to 1.000 for the unlimited tree: it memorizes every training customer.
- The validation score peaks at a middle depth and then falls. The widening gap between the two columns is the sign of overfitting.
- 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?”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.
native categories: ROC-AUC 0.830, 12 columnsone-hot encoded: ROC-AUC 0.827, 22 columnsfrom sklearn.ensemble import HistGradientBoostingClassifierfrom 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 eachHint 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 HistGradientBoostingClassifierfrom 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.02native categories: ROC-AUC 0.830, 12 columnsone-hot encoded: ROC-AUC 0.827, 22 columnsHow it works:
- With
categorycolumns, the defaultcategorical_features="from_dtype"treats them as categories. A split can then group any set of levels, such as “month-to-month or one-year”. - With one-hot columns, each split tests one level against all others, so the model needs more splits for the same rule.
- 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”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.
XGBoost kept 107 trees, validation ROC-AUC 0.848LightGBM kept 73 trees, validation ROC-AUC 0.847import lightgbmfrom lightgbm import LGBMClassifierfrom sklearn.metrics import roc_auc_scorefrom 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-AUCHint 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 lightgbmfrom lightgbm import LGBMClassifierfrom sklearn.metrics import roc_auc_scorefrom 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_ < 500XGBoost kept 107 trees, validation ROC-AUC 0.848LightGBM kept 73 trees, validation ROC-AUC 0.847How it works:
- Both libraries score the validation set after each tree. When 30 trees in a row bring no improvement in log loss, training stops.
predict_probathen uses only the best number of trees.- 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.
M36-C08 · Precision in the top 10%
Section titled “M36-C08 · Precision in the top 10%”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.
calls 125, churners found 81precision 0.648, recall 0.336, lift 3.36from 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 listHint 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_callsrecall_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 > 3calls 125, churners found 81precision 0.648, recall 0.336, lift 3.36How it works:
- When capacity is fixed, the threshold is “whatever lets 125 customers through”. Only the ranking matters.
- 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.
- 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”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.
threshold 0.190test precision 0.371, recall 0.776from sklearn.linear_model import LogisticRegressionfrom 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 thresholdHint 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 LogisticRegressionfrom 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] >= thresholdtest_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.7threshold 0.190test precision 0.371, recall 0.776How it works:
- Recall can only fall as the threshold rises, so the highest threshold that still meets the target gives the best precision for that recall.
- The validation set picks the threshold. The test set only checks it.
- 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”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.
raw: Brier 0.179 0 1 2 3 4predicted 0.000 0.026 0.244 0.570 0.884observed 0.024 0.056 0.144 0.236 0.504calibrated: Brier 0.125 0 1 2 3 4predicted 0.050 0.055 0.112 0.266 0.506observed 0.024 0.056 0.144 0.236 0.504from sklearn.calibration import CalibratedClassifierCV, calibration_curvefrom sklearn.metrics import brier_score_lossfrom 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, BrierHint 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_curvefrom sklearn.metrics import brier_score_lossfrom 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"]raw: Brier 0.179 0 1 2 3 4predicted 0.000 0.026 0.244 0.570 0.884observed 0.024 0.056 0.144 0.236 0.504calibrated: Brier 0.125 0 1 2 3 4predicted 0.050 0.055 0.112 0.266 0.506observed 0.024 0.056 0.144 0.236 0.504How it works:
- In the raw table, the top bins predict far more churn than they observe: the model is overconfident.
- After sigmoid calibration, the two rows nearly match in every bin.
- The Brier score drops by about a third. The
observedrow 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”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?
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 45weighted avg 0.733 0.733 0.733 45from sklearn.datasets import load_irisfrom sklearn.linear_model import LogisticRegressionfrom 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_irisfrom sklearn.linear_model import LogisticRegressionfrom 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] 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 45weighted avg 0.733 0.733 0.733 45How it works:
- Setosa has short, wide sepals, so the two features separate it perfectly.
- Versicolor and virginica overlap in sepal size, so most errors are between them.
- 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”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.
69 grid thresholds, 1250 curve thresholdssame precision: Truesame recall: Truefrom sklearn.linear_model import LogisticRegressionfrom 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 LogisticRegressionfrom 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)69 grid thresholds, 1250 curve thresholdssame precision: Truesame recall: TrueHow it works:
precision_recall_curvesorts the scores once and computes every point in one pass. The loop recomputes the confusion matrix for each threshold.- The precision and recall only change at observed scores. Between two scores, they stay constant, so the next curve threshold at or above
tgives exactly the loop’s values. - 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”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.
ranking (ROC-AUC) logistic 0.814 naive Bayes 0.796 -> logisticforecast error logistic 11.590 naive Bayes 124.829 -> logistictop-100 precision logistic 0.590 naive Bayes 0.650 -> naive Bayesfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom 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 winnerHint 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 LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom 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"ranking (ROC-AUC) logistic 0.814 naive Bayes 0.796 -> logisticforecast error logistic 11.590 naive Bayes 124.829 -> logistictop-100 precision logistic 0.590 naive Bayes 0.650 -> naive BayesHow it works:
- The comparison uses validation rows only, so the test set stays untouched for the final report of whichever model each decision picks.
- Logistic regression wins the ranking by a small margin: both models order customers almost equally well.
- The forecast shows the real gap. Naive Bayes predicts far more churners than there are, because its probabilities are too large.
- 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.
Challenge
Section titled “Challenge”M36-X01 · Compare four models with cross-validation
Section titled “M36-X01 · Compare four models with cross-validation”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.
roc_auc pr_auc briermodelXGBoost 0.840 0.604 0.112random forest 0.838 0.600 0.113LightGBM 0.835 0.605 0.113logistic 0.813 0.553 0.119XGBoost test ROC-AUC 0.838from lightgbm import LGBMClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom 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-AUCHint 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 LGBMClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, cross_validatefrom 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 roc_auc pr_auc briermodelXGBoost 0.840 0.604 0.112random forest 0.838 0.600 0.113LightGBM 0.835 0.605 0.113logistic 0.813 0.553 0.119XGBoost test ROC-AUC 0.838How it works:
- Every model sees the same five folds, so the comparison is fair.
- The table reports three views: ranking (ROC-AUC), the rare class (PR-AUC) and probability quality (Brier).
- 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”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.
default threshold 0.500 test cost 39,360tuned threshold 0.101 test cost 25,920theory threshold 0.125 test cost 26,400from lightgbm import LGBMClassifierfrom sklearn.metrics import confusion_matrix, make_scorerfrom 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 costsHint 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 LGBMClassifierfrom sklearn.base import clonefrom sklearn.metrics import confusion_matrix, make_scorerfrom 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"]default threshold 0.500 test cost 39,360tuned threshold 0.101 test cost 25,920theory threshold 0.125 test cost 26,400How it works:
- The cost function counts what each decision costs.
make_scorer(..., greater_is_better=False)tells scikit-learn to minimize it. TunedThresholdClassifierCVscores many thresholds on each validation fold, picks the one with the lowest mean cost, then refits on the whole training set. Pass a shuffledStratifiedKFoldfor reproducible folds; its ownrandom_stateonly matters whencvis a float (a single validation fraction).- The theoretical threshold 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.
M36-X03 · Probabilities from an SVM
Section titled “M36-X03 · Probabilities from an SVM”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.
ROC-AUC decision_function 0.9966, calibrated 0.9966log loss 0.073, Brier 0.019predict vs proba disagreements: 0from sklearn.calibration import CalibratedClassifierCVfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import brier_score_loss, log_loss, roc_auc_scorefrom 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 numbersHint 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 CalibratedClassifierCVfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import brier_score_loss, log_loss, roc_auc_scorefrom 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 == 0ROC-AUC decision_function 0.9966, calibrated 0.9966log loss 0.073, Brier 0.019predict vs proba disagreements: 0How it works:
ensemble=Falsefits 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.- The sigmoid is increasing, so the ranking, and the ROC-AUC, does not change.
- Unlike
SVC(probability=True),predictandpredict_probaagree: 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?”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.
macro_f1 log_lossmodelmultinomial 0.983 0.061one-vs-rest 0.983 0.080one-vs-one 0.989 NaNSVC (ovo inside) 0.983 NaNone-vs-rest: 3 binary modelsone-vs-one: 3 binary modelsfrom sklearn.datasets import load_winefrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifierfrom 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_winefrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifierfrom 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 macro_f1 log_lossmodelmultinomial 0.983 0.061one-vs-rest 0.983 0.080one-vs-one 0.989 NaNSVC (ovo inside) 0.983 NaNone-vs-rest: 3 binary modelsone-vs-one: 3 binary modelsHow it works:
- 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.
- The log loss still differs: it shows how confident and how right the probabilities are. One-vs-one and
SVCgive none. - For 3 classes, OvR and OvO both train 3 binary models ( and ). For 10 classes, OvO would train 45.
- 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”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.
flagged: 404 | identical: Truefrom sklearn.base import clonefrom sklearn.linear_model import LogisticRegressionfrom 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, predictHint 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, clonefrom sklearn.linear_model import LogisticRegressionfrom 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)flagged: 404 | identical: TrueHow it works:
clonecopies the hyperparameters but not the fitted state, as scikit-learn’s own meta-estimators do.fitreturnsself, soThresholdedClassifier(...).fit(...)chains like any estimator.Self(Python 3.11+) types that return value.- The threshold check in
__init__fails fast on a bad value instead of silently flagging everyone. - 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.
M36-X06 · Decile lift and gains table
Section titled “M36-X06 · Decile lift and gains table”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?
customers churners churn_rate lift captureddecile1 125 81 0.648 3.361 0.3362 125 54 0.432 2.241 0.5603 125 34 0.272 1.411 0.7014 125 19 0.152 0.788 0.7805 125 19 0.152 0.788 0.8596 125 15 0.120 0.622 0.9217 125 6 0.048 0.249 0.9468 125 7 0.056 0.290 0.9759 125 4 0.032 0.166 0.99210 125 2 0.016 0.083 1.000top 3 deciles catch 70.1% of churnersfrom 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 captureHint 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 customers churners churn_rate lift captureddecile1 125 81 0.648 3.361 0.3362 125 54 0.432 2.241 0.5603 125 34 0.272 1.411 0.7014 125 19 0.152 0.788 0.7805 125 19 0.152 0.788 0.8596 125 15 0.120 0.622 0.9217 125 6 0.048 0.249 0.9468 125 7 0.056 0.290 0.9759 125 4 0.032 0.166 0.99210 125 2 0.016 0.083 1.000top 3 deciles catch 70.1% of churnersHow it works:
- Ranking with
method="first"gives every customer a unique rank, soqcutmakes 10 groups of exactly 125. The minus sign puts the highest probabilities in decile 1. - The churn rate falls from decile to decile: the model ranks well. Lift above 1 means the decile is richer in churners than average.
- 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.