36. Classification — Mini-project
The retention team of the subscription business gets a monthly budget for a phone campaign. Each call comes with an offer that costs USD 50. A customer who churns costs about USD 300 in lost revenue. Today the team calls customers at random.
Build a churn early-warning model. It scores every customer, decides who to call from the costs, explains what drives churn, and reports honest numbers on customers it has never seen. Deliver a script, churn_warning.py, that prints a short report and writes the call list to output/call_list.csv.
The project uses every part of module 36: pipelines for several classifiers, cross-validated comparison, ranking and probability metrics, calibration, a cost-based threshold chosen on validation data, odds ratios and a confusion matrix.
Dataset
Section titled “Dataset”data/customers.csv: 5,000 subscription customers, one row each, with the target churned (1 = churned in the last month). The data dictionary describes every column.
| Group | Columns |
|---|---|
| id (not a feature) | customer_id |
| numbers | age, tenure_months, monthly_charges, total_charges, support_tickets, logins_last_30d, avg_session_minutes, has_autopay |
| text | region, plan, contract, payment_method |
| target | churned: 963 churners, 19.26% |
Two quirks matter. total_charges is blank for 10 brand-new customers, so you need an imputer or a model that accepts missing values. And signup_date is left out: it is the snapshot date minus the tenure, so it repeats tenure_months, and a model that learned dates would not carry over to a later snapshot.
Requirements
Section titled “Requirements”Your script must:
- Split the data 75/25 with
stratifyandrandom_state=42. Split a 25% validation set off the training part the same way. Do not touch the test set before the final report. - Compare at least three classifiers with 5-fold stratified cross-validation on the training part: logistic regression, a random forest and one gradient boosting library (XGBoost, LightGBM or
HistGradientBoostingClassifier). Report ROC-AUC, average precision and Brier score for each. - Pick one model and state the reason in one sentence.
- Fit the chosen model on the fitting part and check its calibration on the validation set: the Brier score and a 5-bin calibration table. Calibrate it if the table shows a clear gap.
- Choose the decision threshold that minimizes the campaign cost on the validation set: USD 50 per call plus USD 300 per missed churner. Compare it with the theoretical threshold 50 / 300.
- Keep the model fitted on the fitting part, so the threshold and the probabilities it was chosen for stay the same. On the test set, report the ROC-AUC, the average precision, the Brier score, the confusion matrix at your threshold and the campaign cost at your threshold, at 0.5 and with no campaign.
- Fit a logistic regression on the training part and print its strongest drivers as odds ratios. Rank numeric features (per standard deviation) and one-hot levels (per level switch) separately, because the two are not on the same scale.
- Write the flagged test customers to
output/call_list.csvwithcustomer_idandchurn_probability, highest risk first, and print the first five rows. - End with a three-line recommendation for the retention manager and at least two
assertchecks. - Run in under a minute on a laptop.
Step plan
Section titled “Step plan”-
Load and split. Read the CSV, define the feature lists and make the train/test split. Then split
X_trainintoX_fitandX_val. Print the sizes and the churn rate of each part. -
Build the preprocessing. Write
make_preprocess()(impute, scale, one-hot) for logistic regression. Cast the four text columns to aCategoricalDtypebuilt from the training data for the boosting model. Trees need no scaling. -
Compare models. Loop over a dict of models with
cross_validateandscoring=["roc_auc", "average_precision", "neg_brier_score"]. Put the means in a DataFrame sorted by ROC-AUC. -
Choose and check calibration. Fit the winner on
X_fit. Usecalibration_curve(..., n_bins=5, strategy="quantile")on the validation probabilities. If the predicted and observed rows are close, keep the model as it is. -
Choose the threshold. Write
campaign_cost(y_true, flagged)from the confusion matrix. Score thresholds from 0.05 to 0.80 on the validation set and keep the cheapest. -
Final test report. Predict the test set once with the model from step 4 and print every number from requirement 6.
-
Explain. Fit
make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))onX_train, exponentiate the coefficients, and sort each group (numeric, one-hot) by the size of the log-odds effect. -
Deliver. Build the call list with
customer_idfrom the original frame (customers.loc[X_test.index, "customer_id"]), sort, save and print the head. Print the recommendation and add the asserts.
A skeleton to start from:
# churn_warning.py: a churn early-warning model and a cost-based call list.from pathlib import Path
import numpy as npimport pandas as pd
COST_CALL, COST_LOSS = 50, 300
# --- 1. Load and split ---# TODO: train/test split, then fit/validation split
# --- 2. Preprocessing ---# TODO: make_preprocess() and category dtypes
# --- 3. Compare models with cross-validation ---# TODO: dict of models, cross_validate, comparison table
# --- 4. Calibration check on validation ---# TODO: Brier score and calibration table
# --- 5. Threshold by cost on validation ---# TODO: campaign_cost(), threshold search
# --- 6. Final test report ---# TODO: refit on X_train, metrics, confusion matrix, costs
# --- 7. Odds ratios ---# TODO: logistic regression drivers
# --- 8. Call list, recommendation, checks ---# TODO: output/call_list.csv, three-line recommendation, assertsRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Honest evaluation | 20 | the test set is used once, at the end; every choice uses cross-validation or the validation set |
| Model comparison | 15 | at least three models, the same folds, three metrics, a sorted table and a stated reason for the choice |
| Calibration | 10 | a Brier score and a calibration table on validation data, with a decision to calibrate or not |
| Threshold | 15 | a cost function from the confusion matrix, a threshold search on validation data and a comparison with 50 / 300 |
| Test report | 15 | ROC-AUC, average precision, Brier, confusion matrix and three campaign costs, all correct |
| Explanation | 10 | drivers as odds ratios, numeric and one-hot ranked separately, with the reference level named for one-hot features |
| Deliverable | 10 | output/call_list.csv sorted by risk, a three-line recommendation, asserts that would catch a broken pipeline |
| Code quality | 5 | functions for repeated steps, clear names, no warnings, under a minute |
Stretch goals
Section titled “Stretch goals”- Replace the manual threshold search with
TunedThresholdClassifierCVand compare the two thresholds and test costs. - The call center can make at most 300 calls. Pick the top 300 by risk and compare the cost with your threshold rule.
- Report recall and precision per
contracttype. Is the model as good for two-year customers as for month-to-month ones? - Add a gains table by decile (exercise M36-X06) and a calibration plot with
CalibrationDisplay. - Rank customers by expected saving instead of risk:
p × 300 − 50, orp × monthly_charges × 12 − 50with a revenue-based loss.
Reference solution
Section titled “Reference solution”Reference solution
The solution runs as one script. Each block below continues the previous one.
from pathlib import Path
import numpy as npimport pandas as pdfrom lightgbm import LGBMClassifierfrom sklearn.calibration import calibration_curvefrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import ( average_precision_score, brier_score_loss, confusion_matrix, roc_auc_score,)from sklearn.model_selection import StratifiedKFold, cross_validate, 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)
COST_CALL, COST_LOSS = 50, 300
# --- 1. Load and split ---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)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)for name, part in [("fit", y_fit), ("validation", y_val), ("test", y_test)]: print(f"{name:<10} {len(part):>5} rows, churn rate {part.mean():.3f}")fit 2812 rows, churn rate 0.192validation 938 rows, churn rate 0.193test 1250 rows, churn rate 0.193# --- 2. Preprocessing ---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, )
def make_tree_preprocess() -> ColumnTransformer: """One-hot encode the text columns, pass the numbers through.""" encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False) return ColumnTransformer([("cat", encoder, cat_cols)], remainder="passthrough")
cat_dtypes = { col: pd.CategoricalDtype(sorted(X_train[col].unique())) for col in cat_cols}
def as_categories(frame: pd.DataFrame) -> pd.DataFrame: """Apply the training categories to any split.""" return frame.astype(cat_dtypes)
# --- 3. Compare models with cross-validation ---models = { "logistic regression": make_pipeline( make_preprocess(), LogisticRegression(max_iter=1000) ), "random forest": make_pipeline( make_tree_preprocess(), RandomForestClassifier( n_estimators=300, min_samples_leaf=5, n_jobs=-1, 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, as_categories(X_train), y_train, cv=cv, scoring=["roc_auc", "average_precision", "neg_brier_score"], ) rows.append({ "model": name, "roc_auc": res["test_roc_auc"].mean(), "auc_std": res["test_roc_auc"].std(), "pr_auc": res["test_average_precision"].mean(), "brier": -res["test_neg_brier_score"].mean(), })comparison = pd.DataFrame(rows).set_index("model")comparison = comparison.sort_values("roc_auc", ascending=False)print(comparison.round(3)) roc_auc auc_std pr_auc briermodelrandom forest 0.838 0.011 0.600 0.113LightGBM 0.835 0.016 0.605 0.113logistic regression 0.813 0.012 0.553 0.119The random forest and LightGBM tie: their gaps on every metric are far smaller than the fold-to-fold spread auc_std. Logistic regression is clearly behind. Between the two tied models, the choice is practical: LightGBM reads the category columns and the missing values without any preprocessing, so the deployed pipeline has fewer parts.
# --- 4. Calibration check on validation ---chosen = LGBMClassifier( n_estimators=200, learning_rate=0.05, num_leaves=15, n_jobs=4, verbose=-1, random_state=42,)chosen.fit(as_categories(X_fit), y_fit)p_val = chosen.predict_proba(as_categories(X_val))[:, 1]observed, predicted = calibration_curve(y_val, p_val, n_bins=5, strategy="quantile")print(f"validation Brier {brier_score_loss(y_val, p_val):.3f}")print(pd.DataFrame({"predicted": predicted, "observed": observed}).round(3).T)validation Brier 0.109 0 1 2 3 4predicted 0.012 0.038 0.088 0.218 0.578observed 0.027 0.053 0.090 0.214 0.580The gaps are small. The model under-predicts slightly in the lowest bins (for example 0.012 predicted against 0.027 observed), but the differences are a point or two, too small to need calibration. The model is used as it is.
# --- 5. Threshold by cost on validation ---def campaign_cost(y_true, flagged) -> int: """USD 50 per call plus USD 300 per missed churner.""" tn, fp, fn, tp = confusion_matrix(y_true, flagged, labels=[0, 1]).ravel() return int(COST_CALL * (tp + fp) + COST_LOSS * fn)
thresholds = np.round(np.arange(0.05, 0.81, 0.01), 2)val_costs = np.array([campaign_cost(y_val, p_val >= t) for t in thresholds])threshold = float(thresholds[val_costs.argmin()])print(f"theoretical threshold {COST_CALL / COST_LOSS:.3f}")print(f"chosen threshold {threshold:.2f} (validation cost {val_costs.min():,})")theoretical threshold 0.167chosen threshold 0.14 (validation cost 27,600)# --- 6. Final test report (the model from step 4, fitted on X_fit) ---p_test = chosen.predict_proba(as_categories(X_test))[:, 1]flagged = (p_test >= threshold).astype(int)print(f"test ROC-AUC {roc_auc_score(y_test, p_test):.3f}")print(f"test PR-AUC {average_precision_score(y_test, p_test):.3f}")print(f"test Brier {brier_score_loss(y_test, p_test):.3f}")cm = confusion_matrix(y_test, flagged)print(pd.DataFrame(cm, index=["stayed", "churned"], columns=["no call", "call"]))costs = { f"threshold {threshold:.2f}": campaign_cost(y_test, flagged), "threshold 0.50": campaign_cost(y_test, p_test >= 0.5), "no campaign": campaign_cost(y_test, np.zeros(len(y_test), dtype=int)),}for label, cost in costs.items(): print(f"{label:<15} cost {cost:>7,}")test ROC-AUC 0.831test PR-AUC 0.582test Brier 0.116 no call callstayed 725 284churned 54 187threshold 0.14 cost 39,750threshold 0.50 cost 51,600no campaign cost 72,300# --- 7. Odds ratios ---logreg = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))logreg.fit(X_train, y_train)coefs = pd.Series(logreg[-1].coef_[0], index=logreg[:-1].get_feature_names_out())is_numeric = coefs.index.isin(num_cols)for label, group in [ ("numeric features, per standard deviation", coefs[is_numeric]), ("one-hot levels, against the reference level", coefs[~is_numeric]),]: top = group.reindex(group.abs().sort_values(ascending=False).index).head(3) print(label) print(pd.DataFrame({"coef": top, "odds_ratio": np.exp(top)}).round(3))numeric features, per standard deviation coef odds_ratiotenure_months -0.916 0.400support_tickets 0.543 1.721monthly_charges 0.454 1.574one-hot levels, against the reference level coef odds_ratiocontract_two-year -1.726 0.178contract_one-year -1.052 0.349payment_method_electronic_check 0.372 1.450# --- 8. Call list, recommendation, checks ---call_list = pd.DataFrame({ "customer_id": customers.loc[X_test.index, "customer_id"], "churn_probability": p_test.round(4),})call_list = call_list[flagged == 1].sort_values("churn_probability", ascending=False)Path("output").mkdir(exist_ok=True)call_list.to_csv("output/call_list.csv", index=False)print(f"{len(call_list)} customers to call, saved to output/call_list.csv")print(call_list.head().to_string(index=False))
saving = costs["no campaign"] - costs[f"threshold {threshold:.2f}"]recall = cm[1, 1] / cm[1].sum()print()share = len(call_list) / len(y_test)print(f"1. Call the {len(call_list)} highest-risk customers ({share:.0%} of the base);" f" this finds {recall:.0%} of churners.")print(f"2. Expected saving vs no campaign: USD {saving:,} " f"per {len(y_test):,} customers.")print("3. Push month-to-month customers with many tickets toward longer contracts.")
assert call_list["churn_probability"].is_monotonic_decreasingchosen_cost = costs[f"threshold {threshold:.2f}"]assert chosen_cost < costs["threshold 0.50"] < costs["no campaign"]assert roc_auc_score(y_test, p_test) > 0.8471 customers to call, saved to output/call_list.csvcustomer_id churn_probability C04816 0.978 C04821 0.970 C04720 0.967 C04795 0.965 C04825 0.965
1. Call the 471 highest-risk customers (38% of the base); this finds 78% of churners.2. Expected saving vs no campaign: USD 32,550 per 1,250 customers.3. Push month-to-month customers with many tickets toward longer contracts.How it works:
- Three splits do three jobs: the cross-validation folds choose the model, the validation set checks calibration and chooses the threshold, and the test set reports once.
- The validation threshold lands close to the theoretical 50 / 300, a second sign that the probabilities are well calibrated.
- The test report uses the same model that the threshold was chosen for (fitted on
X_fit). Refitting on all training rows would add 938 rows but change the probabilities that the threshold was tuned on; lesson Example 4 makes the same choice. - The odds ratios come from a separate logistic regression. Numeric and one-hot effects are ranked apart, because one standard deviation and one level switch are different units. The boosting model ranks better; the linear model explains better. Using both is common in practice.