Capstone 4 — Customer churn classification
The head of retention at the subscription business runs a team of agents who phone customers and offer them a deal to stay. The team can make 1,000 calls per month. The business has 5,000 customers, so the agents can reach 20% of them. Right now nobody chooses whom to call with data. The head of retention asks: “Which customers should we call, is every call worth it, and do we have the right number of agents?” A web service will score the customers every month, so the model must also be shipped.
The finance team gives you three numbers:
| Setting | Value | Source |
|---|---|---|
Cost of one call X |
USD 40 | agent time plus the cost of the retention offer |
Save rate p |
0.30 | in a pilot, 30% of the called churners stayed |
Value of a saved churner V |
6 months of a churner’s charges | a saved customer pays for about 6 more months |
If the model says that a customer churns with probability , the expected profit of a call (its average result over many such calls) is . The call pays off when , the break-even probability of module 37. Modules 36 and 37 stopped there. This capstone adds what a real campaign needs:
- The budget is a capacity constraint: never call more than 20% of the customers. When more customers qualify, call the highest scores first.
- The threshold comes with an error bar, and the theory threshold competes with the one that the data prefer.
- The profit on the test set comes with a confidence interval, not one number.
- The model is shipped as a pipeline plus metadata, with a defined behavior for bad inputs. Capstone 8 serves it with FastAPI.
Deliverables:
- A reference analysis that runs top to bottom: model comparison, imbalance study, calibration check, threshold choice with uncertainty, budget scenarios, test report and SHAP explanations.
output/churn_model.joblib(the fitted pipeline) andoutput/metadata.json(threshold, business settings, scores, input schema).train_churn.py: a script that retrains the shipped model and writesmodels/churn_model.joblibandmodels/metadata.json, with a documented interface.- A short recommendation for the head of retention.
Skills practiced:
- Leakage-safe pipelines and encoders for trees (module 33, module 34).
- Classification metrics, calibration and thresholds (module 36).
- Stratified cross-validation, imbalanced data and the bootstrap (module 37, module 29).
- Gradient boosting with HistGradientBoosting and LightGBM (module 38).
- SHAP explanations of single customers (module 43).
- Model persistence and input contracts (module 34, module 44).
Dataset
Section titled “Dataset”data/customers.csv has 5,000 subscription customers, one row each, on the snapshot date 2024-12-31. The data dictionary describes every column.
| Group | Columns | Use |
|---|---|---|
| categorical | region, plan, contract, payment_method |
features |
| numeric | age, has_autopay, tenure_months, monthly_charges, total_charges, support_tickets, logins_last_30d, avg_session_minutes |
features |
| target | churned |
1 = the customer churned in the last month |
| left out | customer_id, signup_date |
an identifier, and a date closely tied to tenure_months |
Known quirks:
- The classes are imbalanced: 963 of the 5,000 customers churned (19.26%).
total_chargesis blank for exactly 10 brand-new customers (tenure_months0). The pipeline must handle blanks.tenure_monthsis capped at 72, so the oldest customers pile up at 72.- Timing. The label covers the last month, and
logins_last_30dcovers the last 30 days: the same window. The data dictionary does not say when in the month the features were recorded. This capstone assumes that they describe each customer at the start of the churn month. If they were recorded later, a customer who had already decided to leave logs in less, and the model learns an effect of churn as a cause. A production project builds the features at month t and the label at month t + 1. Milestone 3 measures how much the model depends onlogins_last_30d.
The data dictionary lists reference scores (hold-out ROC-AUC 0.813 for a logistic regression, 0.825 to 0.837 for HistGradientBoosting). Use them as a sanity check.
Milestones
Section titled “Milestones”Milestone 1 — Frame the business case and split the data
Section titled “Milestone 1 — Frame the business case and split the data”Goal: Turn the finance numbers into a break-even probability and a profit function with the budget, and split the data once.
Acceptance criteria:
- A stratified 75/25 train/test split with
random_state=42, then a stratified 75/25 fit/validation split of the training part. Vuses the mean monthly charge of the training churners, because only churners can be saved. The break-even probability and the expected profit of a random call are printed.expected_profit(y_true, scores, threshold)calls the highest scores first and stops at the budget. Calling nobody earns 0; a perfect model gives the upper bound.
Review: module 37 (break-even threshold).
Milestone 2 — Build leakage-safe pipelines and baselines
Section titled “Milestone 2 — Build leakage-safe pipelines and baselines”Goal: Put every learned step inside a pipeline and measure two baselines on fixed stratified folds.
Acceptance criteria:
- A preprocessing for linear models and one for trees. The tree encoder refuses unknown categories instead of guessing.
- One
StratifiedKFold(5, shuffle=True, random_state=42)on the training part, used for every model. - A majority-class baseline and a logistic regression with accuracy, ROC-AUC and PR-AUC, and proof that the imputer learns inside each fold.
Review: module 33 (data leakage), module 34 (Pipeline, ColumnTransformer).
Milestone 3 — Compare stronger models
Section titled “Milestone 3 — Compare stronger models”Goal: Find out if gradient boosting is worth it, and how much it relies on the feature with a timing risk.
Acceptance criteria:
- HistGradientBoosting and LightGBM on the same folds: mean and standard deviation of ROC-AUC and PR-AUC, the training score as an overfitting check, and per-fold differences against the rivals.
- A stated decision rule and a statement of how the settings were chosen.
- The cross-validated PR-AUC of the chosen model without
logins_last_30d.
Milestone 4 — Compare ways to handle the imbalance
Section titled “Milestone 4 — Compare ways to handle the imbalance”Goal: Compare class weights, resampling inside the folds and threshold tuning on the chosen model.
Acceptance criteria:
- Out-of-fold probabilities for no weighting,
class_weight="balanced"and random undersampling in animblearnpipeline. - For each: ROC-AUC, PR-AUC, Brier score, mean probability, profit at 0.5 and profit at its best threshold.
- A decision that names the trade-off between ranking, calibration and simplicity, and the limits of the comparison.
Review: module 37 (imbalanced classes).
Milestone 5 — Choose the threshold and the budget
Section titled “Milestone 5 — Choose the threshold and the budget”Goal: Check calibration on the validation part, find the most profitable threshold with its uncertainty, choose between it and the break-even probability, and test other budgets.
Acceptance criteria:
- A Brier score and a calibration curve (figure) for the chosen model and a class-weighted version.
- A profit-vs-threshold plot that marks the break-even probability, the empirical best threshold and the region where the budget is the limit.
- A bootstrap of the validation customers (500 resamples) that gives a range for the best threshold. A stated choice between that threshold and the break-even probability, made before the test set is used.
- The profit for budgets from 5% to 30% of the customers.
Review: module 36 (calibration), module 29 (bootstrap).
Milestone 6 — Evaluate on the test set once
Section titled “Milestone 6 — Evaluate on the test set once”Goal: Report honest numbers, with error bars, for the shipped model and threshold.
Acceptance criteria:
- The final model is refitted on the whole training part. The test set is scored once.
- ROC-AUC, PR-AUC, Brier score, the confusion matrix of the called customers, precision, recall and the expected profit.
- The profit against five policies fixed in advance: call nobody, call at random, threshold 0.5, the empirical threshold of Milestone 5 and a perfect model.
- Bootstrap 95% intervals for the profit and for the differences between the policies. Asserts only on results that the intervals support.
- The score distribution of the churners that the campaign misses.
Milestone 7 — Explain single customers with SHAP
Section titled “Milestone 7 — Explain single customers with SHAP”Goal: Give the agents reasons for single scores, and say where the explanations stop.
Acceptance criteria:
shap.TreeExplaineron the LightGBM step, with an additivity check, and a short global summary.- Waterfall plots for the highest-risk test customer and for the missed churner with the lowest score, each read in plain words.
- One note on the base value and one on correlated features.
Review: module 43 (SHAP values, waterfall plots).
Milestone 8 — Ship the model
Section titled “Milestone 8 — Ship the model”Goal: Save the pipeline and its metadata, define what happens with bad inputs, and package the training as a script.
Acceptance criteria:
- The behavior of the pipeline on an unknown category is shown, not assumed.
output/churn_model.joblibandoutput/metadata.json; the reloaded pipeline gives the same probabilities.train_churn.pywritesmodels/churn_model.joblibandmodels/metadata.json, and its model gives the same test probabilities and threshold as the analysis.- The interface is documented.
The interface of the saved model:
| Input column | Type | Allowed values |
|---|---|---|
region |
str | East, North, South, West |
plan |
str | basic, premium, standard |
contract |
str | month-to-month, one-year, two-year |
payment_method |
str | bank_transfer, credit_card, electronic_check, paypal |
age |
int | 18–80 in training |
has_autopay |
int | 0 or 1 |
tenure_months |
int | 0–72 in training |
monthly_charges |
float | USD per month |
total_charges |
float | USD to date; may be blank (NaN) for new customers |
support_tickets |
int | count |
logins_last_30d |
int | count over the 30 days before the snapshot |
avg_session_minutes |
float | minutes |
Output: pipeline.predict_proba(X)[:, 1] is the probability that each customer churns within the month after the feature snapshot (see the timing assumption in the Dataset section). Decision: call a customer when the probability is at least metadata["threshold"], highest probability first, and stop at metadata["business"]["call_share"] of the customers. Bad inputs: an unknown or blank category makes predict_proba raise ValueError. The service must check every request against metadata["categories"] and reject it with a clear message before it calls the model. metadata["numeric_ranges"] gives the training range of each numeric column.
Review: module 34 (joblib), module 44 (metadata, input validation).
Grading rubric
Section titled “Grading rubric”| Criterion | Needs work | Meets | Excellent | Points |
|---|---|---|---|---|
| Business framing | costs not used, or only accuracy reported (0–3) | break-even probability from the churners’ value and a profit function with the budget (4–7) | plus random-call and perfect-model reference points, profit per 1,000 customers and the timing assumption stated (8–10) | 10 |
| Leakage-safe pipelines | preprocessing fitted before the split (0–3) | all learned steps inside pipelines; one fixed set of folds (4–7) | plus a check that shows the fold-wise statistics (8–10) | 10 |
| Model comparison | test scores used to choose (0–5) | two baselines and two boosting models, mean and std of two metrics (6–11) | plus per-fold differences, an overfitting check, an honest note on how settings were chosen and the logins_last_30d sensitivity (12–15) |
15 |
| Imbalance handling | resampling outside the folds (0–4) | three variants compared on ranking and profit (5–8) | plus calibration in the decision and the limits of the comparison (9–10) | 10 |
| Threshold and budget | threshold 0.5 or chosen on test (0–7) | calibration curve and a profit curve on validation (8–14) | plus a bootstrap range for the threshold, a reasoned choice against break-even and budget scenarios (15–20) | 20 |
| Test report | metrics missing, or the test set used more than once (0–5) | metrics, confusion matrix and profit at the chosen threshold (6–11) | plus policies fixed in advance, bootstrap intervals and the missed-churner analysis (12–15) | 15 |
| Explanations | no SHAP, or SHAP on raw text columns (0–3) | two waterfalls with plain-language reasons (4–7) | plus additivity, base value and correlated-feature notes (8–10) | 10 |
| Shipping | no saved model (0–3) | joblib file, metadata and a script that runs (4–7) | plus identical results from the script, the real behavior on bad inputs and a documented interface (8–10) | 10 |
| Total | 100 |
Reference solution
Section titled “Reference solution”The solution runs top to bottom in one Python session, in well under a minute on a laptop. Each milestone uses the variables of the previous ones. Open a milestone only after you have tried it yourself.
Reference solution — Milestone 1: Frame the business case and split the data
Load the data, name the feature groups once and split. The test set (25%) stays locked until Milestone 6. The validation set (25% of the rest) is for the calibration check and the threshold.
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_split
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")CATEGORICAL = ["region", "plan", "contract", "payment_method"]NUMERIC = [ "age", "has_autopay", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes",]FEATURES = CATEGORICAL + NUMERICTARGET = "churned"
X, y = customers[FEATURES], customers[TARGET]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)parts = {"train": y_train, "fit": y_fit, "validation": y_val, "test": y_test}for name, part in parts.items(): print(f"{name:<11}{len(part):>6,} rows churn {part.mean():.1%}")assert not set(X_train.index) & set(X_test.index)train 3,750 rows churn 19.3%fit 2,812 rows churn 19.2%validation 938 rows churn 19.3%test 1,250 rows churn 19.3%Only churners can be saved, so V uses the churners’ charges, from the training rows only.
CALLS_PER_MONTH = 1_000CALL_SHARE = CALLS_PER_MONTH / len(customers) # the budget as a share of customersCALL_COST = 40.0 # X, USD per callSAVE_RATE = 0.30 # pMONTHS_KEPT = 6charges = X_train.groupby(y_train)["monthly_charges"].mean()VALUE_SAVED = MONTHS_KEPT * charges[1] # VBREAK_EVEN = CALL_COST / (SAVE_RATE * VALUE_SAVED)
print(f"mean monthly charge: stayers USD {charges[0]:.2f}, " f"churners USD {charges[1]:.2f}")print(f"value of a saved churner V: USD {VALUE_SAVED:.2f}")print(f"break-even churn probability X/(p*V): {BREAK_EVEN:.3f}")random_call = SAVE_RATE * VALUE_SAVED * y_train.mean() - CALL_COSTprint(f"expected profit of one random call: USD {random_call:.2f}")mean monthly charge: stayers USD 59.47, churners USD 66.29value of a saved churner V: USD 397.72break-even churn probability X/(p*V): 0.335expected profit of one random call: USD -17.03Churners pay more per month than stayers, so the value of the average customer would understate V and push the break-even probability up. A random call reaches a churner about one time in five and loses money: any model must first beat “call nobody”.
The profit function follows the decision rule: rank by score, keep the customers at or above the threshold, stop at the budget. On labeled data, each called churner counts and each call costs . Profits are reported per 1,000 customers, so splits of different sizes compare.
def expected_profit(y_true, scores, threshold, share=CALL_SHARE): """Return (expected profit in USD, number of calls) for one threshold.
Call the customers whose score is at least ``threshold``, highest score first, and never more than ``share`` of all customers (the budget). """ y_true, scores = np.asarray(y_true), np.asarray(scores) order = np.argsort(-scores, kind="stable") n_calls = min(int((scores >= threshold).sum()), int(share * len(scores))) saved_churners = SAVE_RATE * y_true[order[:n_calls]].sum() return saved_churners * VALUE_SAVED - CALL_COST * n_calls, n_calls
def per_1000(profit, n_customers): return 1000 * profit / n_customers
assert expected_profit(y_train, np.zeros(len(y_train)), 0.5) == (0, 0)best, calls = expected_profit(y_train, y_train.to_numpy(), 0.5)print(f"perfect model: {calls} calls, " f"USD {per_1000(best, len(y_train)):,.0f} per 1,000 customers")perfect model: 722 calls, USD 15,271 per 1,000 customersThe budget (20%) is just above the churn rate, so a perfect model could call every churner. No real model gets close to this ceiling.
Reference solution — Milestone 2: Build leakage-safe pipelines and baselines
Linear models need one-hot columns, no blanks and scaled numbers. Trees need none of that: an OrdinalEncoder turns each category into a number, and LightGBM handles the blank total_charges itself. The tree encoder keeps its default handle_unknown="error"; Milestone 8 shows why. set_output(transform="pandas") keeps the column names for SHAP.
from sklearn.compose import ColumnTransformerfrom sklearn.dummy import DummyClassifierfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_validatefrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
def linear_prep(): numeric = make_pipeline(SimpleImputer(strategy="median"), StandardScaler()) return ColumnTransformer( [ ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL), ("num", numeric, NUMERIC), ] )
def tree_prep(lenient=False): """Ordinal codes for trees; lenient=True maps unknown categories to NaN.""" if lenient: encoder = OrdinalEncoder( handle_unknown="use_encoded_value", unknown_value=np.nan ) else: encoder = OrdinalEncoder() # handle_unknown="error" return ColumnTransformer( [("cat", encoder, CATEGORICAL)], remainder="passthrough", verbose_feature_names_out=False, ).set_output(transform="pandas")
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)SCORING = {"accuracy": "accuracy", "roc_auc": "roc_auc", "pr_auc": "average_precision"}results = {}
def run_cv(name, model): results[name] = cross_validate( model, X_train, y_train, cv=cv, scoring=SCORING, return_estimator=True, return_train_score=True, )
run_cv("majority", DummyClassifier(strategy="most_frequent"))logistic = Pipeline( [("prep", linear_prep()), ("model", LogisticRegression(max_iter=1000))])run_cv("logistic", logistic)summary = pd.DataFrame( {n: {m: r[f"test_{m}"].mean() for m in SCORING} for n, r in results.items()}).Tprint(summary.round(3))fold_medians = [ est["prep"].named_transformers_["num"][0].statistics_[NUMERIC.index("total_charges")] for est in results["logistic"]["estimator"]]print("total_charges median per fold:", np.round(fold_medians, 2))print(f"median of all training rows: {X_train['total_charges'].median():.2f}") accuracy roc_auc pr_aucmajority 0.807 0.500 0.193logistic 0.836 0.813 0.553total_charges median per fold: [ 979.97 988.79 964.8 964.65 1002.54]median of all training rows: 977.61The majority baseline is 80.7% accurate and finds no churner, so the capstone ranks models by ROC-AUC and PR-AUC. The logistic regression matches the data dictionary’s reference scores. The five fold medians differ from each other and from the median of all training rows: each fold’s imputer learned only from that fold’s training rows.
Reference solution — Milestone 3: Compare stronger models
Three boosting candidates on the same folds: HistGradientBoosting with native categorical splits and the settings of the data dictionary, LightGBM with its defaults, and a small LightGBM. The small LightGBM’s settings (8 leaves, a low learning rate, at least 40 customers per leaf) came from a short manual search on these same folds. Its cross-validated score is therefore a little optimistic; stretch goal 4 measures by how much with nested cross-validation.
from lightgbm import LGBMClassifierfrom sklearn.ensemble import HistGradientBoostingClassifier
LGBM_SMALL = { "n_estimators": 150, "learning_rate": 0.03, "num_leaves": 8, "min_child_samples": 40, "random_state": 42, "verbose": -1,}hist_gb = HistGradientBoostingClassifier( learning_rate=0.05, max_iter=300, max_leaf_nodes=15, early_stopping=True, categorical_features=CATEGORICAL, random_state=42,)candidates = { "hist_gb": hist_gb, "lgbm_default": LGBMClassifier(random_state=42, verbose=-1), "lgbm_small": LGBMClassifier(**LGBM_SMALL),}for name, model in candidates.items(): run_cv(name, Pipeline([("prep", tree_prep()), ("model", model)]))
table = pd.DataFrame( { name: { "train_roc": r["train_roc_auc"].mean(), "roc_auc": r["test_roc_auc"].mean(), "roc_std": r["test_roc_auc"].std(), "pr_auc": r["test_pr_auc"].mean(), "pr_std": r["test_pr_auc"].std(), } for name, r in results.items() }).Tprint(table.sort_values("pr_auc", ascending=False).round(3))for rival in ["hist_gb", "logistic"]: gain = results["lgbm_small"]["test_pr_auc"] - results[rival]["test_pr_auc"] wins = int((gain > 0).sum()) print(f"PR-AUC gain over {rival:<9}", gain.round(3), f"wins {wins}/5") train_roc roc_auc roc_std pr_auc pr_stdlgbm_small 0.891 0.844 0.013 0.623 0.016hist_gb 0.926 0.840 0.010 0.606 0.014lgbm_default 0.998 0.822 0.011 0.584 0.024logistic 0.819 0.813 0.011 0.553 0.023majority 0.500 0.500 0.000 0.193 0.001PR-AUC gain over hist_gb [0.018 0.011 0.016 0.027 0.014] wins 5/5PR-AUC gain over logistic [0.073 0.072 0.028 0.076 0.101] wins 5/5The decision rule is the highest mean PR-AUC, because the budget only reaches the top 20% of the ranking and PR-AUC rewards a clean top. The small LightGBM wins, in every fold against both rivals. The default LightGBM shows why small trees help here: its training ROC-AUC is almost perfect, but its cross-validated score is the lowest of the boosting models. That is overfitting.
Now the timing risk of the Dataset section. How much does the winner rely on logins_last_30d?
no_logins = [c for c in FEATURES if c != "logins_last_30d"]small = Pipeline([("prep", tree_prep()), ("model", LGBMClassifier(**LGBM_SMALL))])res = cross_validate(small, X_train[no_logins], y_train, cv=cv, scoring=SCORING)print(f"without logins_last_30d: ROC-AUC {res['test_roc_auc'].mean():.3f}, " f"PR-AUC {res['test_pr_auc'].mean():.3f}")without logins_last_30d: ROC-AUC 0.825, PR-AUC 0.582Without the login count, the model loses about 0.04 of PR-AUC but still beats the logistic regression with all features. The capstone keeps the column under the stated assumption, so the input schema stays as it is. The cost of being wrong is now known: if a later check shows that the logins were recorded after the churn decision, drop the column and expect about this score.
Reference solution — Milestone 4: Compare ways to handle the imbalance
Three variants of the small LightGBM. Class weights make each churner count about four times as much. Random undersampling drops stayers until both classes are the same size, inside an imblearn pipeline, so only the training rows of each fold change. The third option is threshold tuning: keep the unweighted model and move the threshold. best_threshold tries thresholds from 0.05 to 0.95 and keeps the most profitable; on a tie it keeps the highest, which makes fewer calls.
from imblearn.pipeline import Pipeline as ImbPipelinefrom imblearn.under_sampling import RandomUnderSamplerfrom sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_scorefrom sklearn.model_selection import cross_val_predict
THRESHOLDS = np.round(np.arange(0.05, 0.951, 0.01), 2)
def best_threshold(y_true, scores): profits = np.array([expected_profit(y_true, scores, t)[0] for t in THRESHOLDS]) i = len(profits) - 1 - int(profits[::-1].argmax()) # highest on ties return THRESHOLDS[i], profits[i], profits
variants = { "no weighting": Pipeline( [("prep", tree_prep()), ("model", LGBMClassifier(**LGBM_SMALL))] ), "class weights": Pipeline( [ ("prep", tree_prep()), ("model", LGBMClassifier(**LGBM_SMALL, class_weight="balanced")), ] ), "undersampling": ImbPipeline( [ ("prep", tree_prep()), ("sample", RandomUnderSampler(random_state=42)), ("model", LGBMClassifier(**LGBM_SMALL)), ] ),}rows = {}for name, model in variants.items(): oof = cross_val_predict(model, X_train, y_train, cv=cv, method="predict_proba") oof = oof[:, 1] t_best, profit_best, _ = best_threshold(y_train, oof) rows[name] = { "roc_auc": roc_auc_score(y_train, oof), "pr_auc": average_precision_score(y_train, oof), "brier": brier_score_loss(y_train, oof), "mean_p": oof.mean(), "usd@0.5": per_1000(expected_profit(y_train, oof, 0.5)[0], len(oof)), "best_t": t_best, "usd@best": per_1000(profit_best, len(oof)), }print(pd.DataFrame(rows).T.round(3))kept = RandomUnderSampler(random_state=42).fit_resample(X_train, y_train)[1]print(f"undersampling keeps {(kept == 0).sum()} of {(y_train == 0).sum()} stayers") roc_auc pr_auc brier mean_p usd@0.5 best_t usd@bestno weighting 0.844 0.619 0.110 0.191 4675.125 0.40 5372.812class weights 0.842 0.612 0.155 0.379 5331.501 0.69 5354.478undersampling 0.836 0.585 0.164 0.396 5045.144 0.73 5401.343undersampling keeps 722 of 3028 stayers- Ranking: weighting does not help, and undersampling is worse. It learns from about a quarter of the stayers.
- Calibration: the unweighted model’s mean probability is close to the churn rate. The rebalanced models predict about twice the truth, and their Brier scores are much worse.
- Profit: at 0.5, class weights look better, but only because 0.5 is the wrong threshold for the unweighted model. At each variant’s best threshold, the three are within USD 50 per 1,000 customers of each other.
Decision: keep the unweighted model and tune the threshold. It ranks at least as well, earns about as much, and its probabilities stay honest, so the break-even formula keeps its meaning. Two limits: the best thresholds were chosen on the rows they are scored on (optimistic for all three variants alike), and LGBM_SMALL was chosen for the unweighted model, which favors it a little. Undersampling, with fewer rows, might prefer other settings.
Reference solution — Milestone 5: Choose the threshold and the budget
Fit the chosen model on the fit part only, so the validation part is new to it. Fit the class-weighted version too, for comparison.
from sklearn.calibration import calibration_curve
model = variants["no weighting"].fit(X_fit, y_fit)weighted = variants["class weights"].fit(X_fit, y_fit)p_val = model.predict_proba(X_val)[:, 1]p_val_weighted = weighted.predict_proba(X_val)[:, 1]for name, p in [("no weighting", p_val), ("class weights", p_val_weighted)]: brier = brier_score_loss(y_val, p) print(f"{name:<14} Brier {brier:.4f} mean P(churn) {p.mean():.3f}")print(f"observed churn rate on validation: {y_val.mean():.3f}")observed, predicted = calibration_curve(y_val, p_val, n_bins=8, strategy="quantile")print(pd.DataFrame({"predicted": predicted, "observed": observed}).round(3))no weighting Brier 0.1079 mean P(churn) 0.188class weights Brier 0.1546 mean P(churn) 0.382observed churn rate on validation: 0.193 predicted observed0 0.025 0.0081 0.039 0.0342 0.061 0.0513 0.090 0.0774 0.136 0.1285 0.210 0.2056 0.352 0.3507 0.593 0.686import matplotlib.pyplot as plt
obs_w, pred_w = calibration_curve(y_val, p_val_weighted, n_bins=8, strategy="quantile")fig, ax = plt.subplots(figsize=(5.5, 5))ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="perfect calibration")ax.plot(predicted, observed, marker="o", label="no weighting")ax.plot(pred_w, obs_w, marker="s", label="class weights")ax.set_xlabel("mean predicted P(churn) in the bin")ax.set_ylabel("observed churn rate in the bin")ax.set_title("Calibration on the validation part")ax.legend()plt.show()
In seven of the eight bins, the unweighted model’s mean prediction is within 0.02 of the observed churn rate. Only the top bin is off: the model says 0.59 and 0.69 churned. These customers are far above any threshold near break-even and are called anyway. The class-weighted scores rank well but are not probabilities. No recalibration: a calibrator fitted on held-out data to the frozen model (CalibratedClassifierCV(FrozenEstimator(model))) is a monotone map, so it would not change whom the agents call first, only where the threshold sits.
Now the profit for every threshold on the validation part. The budget there is 20% of 938 customers, so 187 calls.
t_emp, profit_emp, profits = best_threshold(y_val, p_val)budget = int(CALL_SHARE * len(y_val))t_budget = np.sort(p_val)[::-1][budget - 1] # below this, the budget is the limitprint(f"budget {budget} calls; it is the limit for thresholds below {t_budget:.3f}")for name, t in [("empirical best", t_emp), ("break-even", BREAK_EVEN), ("0.5", 0.5)]: profit, calls = expected_profit(y_val, p_val, t) print(f"{name:<15}{t:.3f} {calls:>4} calls " f"USD {per_1000(profit, len(y_val)):>6,.0f} per 1,000 customers")budget 187 calls; it is the limit for thresholds below 0.339empirical best 0.390 148 calls USD 6,282 per 1,000 customersbreak-even 0.335 187 calls USD 5,891 per 1,000 customers0.5 0.500 85 calls USD 4,389 per 1,000 customersfig, ax = plt.subplots(figsize=(8, 4.5))ax.plot(THRESHOLDS, [per_1000(p, len(y_val)) for p in profits], color="C0")ax.axvspan(THRESHOLDS[0], t_budget, color="gray", alpha=0.15, label="budget limit")ax.axvline(BREAK_EVEN, color="C2", linestyle="--", label=f"break-even {BREAK_EVEN:.3f}")ax.axvline(t_emp, color="C3", label=f"empirical best {t_emp:.2f}")ax.axhline(0, color="black", linewidth=0.8)ax.set_xlabel("threshold on P(churn)")ax.set_ylabel("expected profit, USD per 1,000 customers")ax.set_title("Expected campaign profit on the validation part")ax.legend()plt.show()
Below 0.339, the budget is the limit and the profit is flat. The break-even probability, 0.335, falls just inside that region: the budget of 1,000 calls is almost exactly the number of calls that pay off. The empirical best threshold is higher. How sure is that? Resample the validation customers with replacement 500 times and find the best threshold each time. profit_curve computes all thresholds at once, so the bootstrap is fast.
def profit_curve(y_true, scores, share=CALL_SHARE): """Expected profit for every threshold in THRESHOLDS at once.""" y_true, scores = np.asarray(y_true), np.asarray(scores) order = np.argsort(-scores, kind="stable") caught = np.concatenate([[0], np.cumsum(y_true[order])]) above = (scores[:, None] >= THRESHOLDS).sum(axis=0) n_calls = np.minimum(above, int(share * len(scores))) return SAVE_RATE * VALUE_SAVED * caught[n_calls] - CALL_COST * n_calls
assert np.allclose(profit_curve(y_val, p_val), profits)rng = np.random.default_rng(42)y_val_arr = y_val.to_numpy()best_ts = []for _ in range(500): idx = rng.integers(0, len(y_val_arr), len(y_val_arr)) curve = profit_curve(y_val_arr[idx], p_val[idx]) best_ts.append(THRESHOLDS[len(curve) - 1 - curve[::-1].argmax()])low, mid, high = np.percentile(best_ts, [2.5, 50, 97.5])print(f"best threshold: median {mid:.2f}, 95% range {low:.2f} to {high:.2f}")print(f"share of resamples with the best at or below 0.34: " f"{np.mean(np.array(best_ts) <= 0.34):.1%}")gap = per_1000(profit_emp - expected_profit(y_val, p_val, BREAK_EVEN)[0], len(y_val))print(f"profit of the empirical best over break-even: USD {gap:,.0f} per 1,000")best threshold: median 0.39, 95% range 0.34 to 0.40share of resamples with the best at or below 0.34: 6.4%profit of the empirical best over break-even: USD 391 per 1,000Within these 938 customers, the preference for about 0.39 is stable: the best threshold lands between 0.34 and 0.40 in 95% of the resamples. But the bootstrap only reshuffles the same customers. It cannot tell whether this sample happens to hold few churners just above break-even. The gain is also small: about USD 390 per 1,000 customers, on a threshold picked from 91 candidates on the same rows.
Decision, made before the test set is used: ship the break-even threshold, rounded to 0.335. The model is calibrated, so theory says that break-even is the best threshold on new customers. It needs no tuning on 938 rows, and it moves by itself when the finance numbers change. Milestone 6 keeps the empirical 0.39 as a competing policy, fixed now, and checks whether the data were right.
Last, the question about agents. Keep the break-even rule and change the budget:
THRESHOLD = round(BREAK_EVEN, 3)for share in [0.05, 0.10, 0.15, 0.20, 0.30]: profit, calls = expected_profit(y_val, p_val, THRESHOLD, share=share) print(f"budget {share:>4.0%}: {calls:>4} calls " f"USD {per_1000(profit, len(y_val)):>6,.0f} per 1,000 customers")budget 5%: 46 calls USD 2,999 per 1,000 customersbudget 10%: 93 calls USD 4,684 per 1,000 customersbudget 15%: 140 calls USD 5,987 per 1,000 customersbudget 20%: 187 calls USD 5,891 per 1,000 customersbudget 30%: 187 calls USD 5,891 per 1,000 customersProfit rises quickly up to a budget of about 15%. Above 20%, nothing changes: no more customers are above break-even, so more agents would have no profitable calls to make. Between 15% and 20%, the extra calls are the ones closest to break-even; they earn about zero on average, so the dip here is noise. The current team size is about right.
Reference solution — Milestone 6: Evaluate on the test set once
The threshold is a business rule, not a value fitted to the validation probabilities, so the final model can learn from all 3,750 training rows. Its procedure has the same calibration as the out-of-fold “no weighting” row of Milestone 4 (mean probability close to the churn rate). This is the shipped model. This block is the only one that scores the test set.
from sklearn.base import clonefrom sklearn.metrics import confusion_matrix, precision_score, recall_score
final_model = clone(variants["no weighting"]).fit(X_train, y_train)p_test = final_model.predict_proba(X_test)[:, 1]profit_test, calls_test = expected_profit(y_test, p_test, THRESHOLD)called = np.zeros(len(p_test), dtype=bool)called[np.argsort(-p_test, kind="stable")[:calls_test]] = True
print(f"ROC-AUC {roc_auc_score(y_test, p_test):.3f} " f"PR-AUC {average_precision_score(y_test, p_test):.3f} " f"Brier {brier_score_loss(y_test, p_test):.4f}")cm = pd.DataFrame( confusion_matrix(y_test, called), index=["stayed", "churned"], columns=["not called", "called"],)print(cm)precision, recall = precision_score(y_test, called), recall_score(y_test, called)print(f"calls {calls_test} of {len(y_test)} (budget {int(CALL_SHARE * len(y_test))})")print(f"precision {precision:.3f} recall {recall:.3f}")
budget_test = int(CALL_SHARE * len(y_test))random_call_test = SAVE_RATE * VALUE_SAVED * y_test.mean() - CALL_COSTpolicies = { "call nobody": 0.0, "call at random": budget_test * random_call_test, "threshold 0.5": expected_profit(y_test, p_test, 0.5)[0], f"empirical {t_emp:.2f}": expected_profit(y_test, p_test, t_emp)[0], f"break-even {THRESHOLD}": profit_test, "perfect model": expected_profit(y_test, y_test.to_numpy(), 0.5)[0],}for name, profit in policies.items(): print(f"{name:<17}USD {per_1000(profit, len(y_test)):>8,.0f} per 1,000 customers")ROC-AUC 0.837 PR-AUC 0.583 Brier 0.1129 not called calledstayed 900 109churned 101 140calls 249 of 1250 (budget 250)precision 0.562 recall 0.581call nobody USD 0 per 1,000 customerscall at random USD -3,399 per 1,000 customersthreshold 0.5 USD 4,239 per 1,000 customersempirical 0.39 USD 5,182 per 1,000 customersbreak-even 0.335 USD 5,395 per 1,000 customersperfect model USD 15,292 per 1,000 customersThe test ROC-AUC is a little below the cross-validated 0.844 and about equal to the best reference model of the data dictionary (0.837 on the same test set). The agents use almost the whole budget; 56% of the called customers would churn, and the calls reach 58% of the churners.
One test set of 1,250 customers is a sample too. Bootstrap the test customers to put error bars on the profit and on the differences between policies:
y_test_arr = y_test.to_numpy()rng = np.random.default_rng(42)boot = []for _ in range(500): idx = rng.integers(0, len(y_test_arr), len(y_test_arr)) yb, pb = y_test_arr[idx], p_test[idx] shipped = expected_profit(yb, pb, THRESHOLD)[0] boot.append( { "shipped": shipped, "shipped - 0.5": shipped - expected_profit(yb, pb, 0.5)[0], "empirical - shipped": expected_profit(yb, pb, t_emp)[0] - shipped, } )intervals = per_1000(pd.DataFrame(boot), len(y_test)).quantile([0.025, 0.975]).Tintervals.columns = ["2.5%", "97.5%"]print(intervals.round(0))assert intervals.loc["shipped", "2.5%"] > 0assert intervals.loc["shipped - 0.5", "2.5%"] > 0 2.5% 97.5%shipped 3932.0 6845.0shipped - 0.5 205.0 2177.0empirical - shipped -851.0 343.0The shipped policy earns between about USD 3,900 and 6,800 per 1,000 customers (95% interval). It beats the default threshold 0.5: that interval is above zero. The empirical threshold 0.39 did slightly worse than break-even on the test set, but its interval includes zero, so the two rules are equal within noise. The validation data’s preference did not carry over, which supports the theory rule. The policies were fixed before this read, so the comparison only reports them; it must not be used now to switch the shipped threshold.
Who does the campaign miss?
missed = np.flatnonzero((y_test_arr == 1) & ~called)bands = pd.cut(p_test[missed], [0, 0.1, 0.2, THRESHOLD], right=False)print(f"{len(missed)} missed churners, median P(churn) {np.median(p_test[missed]):.3f}")print(pd.Series(bands).value_counts(sort=False).to_string())101 missed churners, median P(churn) 0.158[0.0, 0.1) 26[0.1, 0.2) 38[0.2, 0.335) 37About a quarter of the missed churners score below 0.1 and look safe to the model. The rest sit between 0.1 and the threshold: the model sees some risk, but less than a call is worth at USD 40.
Reference solution — Milestone 7: Explain single customers with SHAP
Module 43 covers the global plots. Here the focus is on single customers, which is what an agent needs. TreeExplainer explains the LightGBM step on the encoded rows. The ordinal encoder makes one column per original feature, so each feature gets one SHAP value per customer, in log-odds.
import shap
X_test_enc = final_model["prep"].transform(X_test)explainer = shap.TreeExplainer(final_model["model"])sv = explainer(X_test_enc)log_odds = final_model["model"].predict_proba(X_test_enc, raw_score=True)rebuilt = sv.base_values + sv.values.sum(axis=1)print(sv.values.shape, "feature names match:", sv.feature_names == FEATURES)print("base + SHAP = log-odds:", np.allclose(rebuilt, log_odds))base_p = 1 / (1 + np.exp(-sv.base_values[0]))print(f"base value {sv.base_values[0]:.3f} log-odds = P {base_p:.3f}; " f"churn rate {y_train.mean():.3f}")mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=FEATURES)print(mean_abs.sort_values(ascending=False).head(6).round(3).to_string())(1250, 12) feature names match: Truebase + SHAP = log-odds: Truebase value -1.900 log-odds = P 0.130; churn rate 0.193contract 0.532tenure_months 0.379monthly_charges 0.326age 0.259support_tickets 0.240logins_last_30d 0.188The additivity check passes for all 1,250 test customers. The base value is an average of the model’s log-odds, not the log-odds of the churn rate. The sigmoid of an average is not the average of the sigmoids, so the base value’s probability (0.130) is below the churn rate (0.193). Contract and tenure dominate the ranking. Read the ranking with care: total_charges is about monthly_charges × tenure_months, so the three share credit, and part of the total_charges value is tenure information.
def explain(pos, title): row = X_test.iloc[pos] explanation = shap.Explanation( values=sv.values[pos], base_values=sv.base_values[pos], data=row.to_numpy(), feature_names=FEATURES, ) shap.plots.waterfall(explanation, max_display=8, show=False) plt.title(title) plt.show() top = pd.Series(sv.values[pos], index=FEATURES) top = top.sort_values(key=abs, ascending=False).head(4) cid = customers.loc[X_test.index[pos], "customer_id"] print(f"{cid} P(churn) {p_test[pos]:.3f} churned {y_test.iloc[pos]}") print(pd.DataFrame({"value": row[top.index], "shap": top.round(3)}).to_string())
explain(int(p_test.argmax()), "Highest-risk test customer")C04816 P(churn) 0.900 churned 1 value shapsupport_tickets 5 1.340tenure_months 1 1.120contract month-to-month 0.744age 66 0.582
In plain words for the agent: “This customer joined a month ago, has already opened 5 support tickets and is on a month-to-month contract.” The tickets tell the agent what to talk about. The +0.35 of total_charges is mostly the short tenure again: a month of charges is a small total. The customer did churn.
lowest_missed = int(missed[p_test[missed].argmin()])explain(lowest_missed, "The missed churner with the lowest score")C00123 P(churn) 0.026 churned 1 value shapcontract two-year -0.674tenure_months 72 -0.659age 42 -0.236payment_method electronic_check 0.173
This customer has been there for 72 months, on a two-year contract, with average charges and 11 logins. Only the payment method raises the risk a little. The model is not wrong about this profile: the data dictionary shows 3.2% churn on two-year contracts. Whatever made this customer leave (a move, a competitor’s offer) is not in the data. Milestone 6 showed that such customers are a minority of the misses (26 of 101 score below 0.1); most missed churners have a moderate score below the threshold.
Reference solution — Milestone 8: Ship the model
First, bad inputs. What would happen if the encoder mapped an unknown category to a blank code, as tree_prep(lenient=True) does? Fit that variant and score every test customer twice: once with an unknown value, once with the first category of the same column.
lenient = Pipeline( [("prep", tree_prep(lenient=True)), ("model", LGBMClassifier(**LGBM_SMALL))]).fit(X_train, y_train)for column, unknown, first in [ ("plan", "enterprise", "basic"), ("contract", "monthly-plus", "month-to-month"),]: p_unknown = lenient.predict_proba(X_test.assign(**{column: unknown}))[:, 1] p_first = lenient.predict_proba(X_test.assign(**{column: first}))[:, 1] diff = np.abs(p_unknown - p_first).max() print(f"{column}={unknown!r} vs {first!r}: max difference {diff}")try: final_model.predict_proba(X_test.head(1).assign(plan="enterprise"))except ValueError as err: print("shipped pipeline raises ValueError:") print(err)plan='enterprise' vs 'basic': max difference 0.0contract='monthly-plus' vs 'month-to-month': max difference 0.0shipped pipeline raises ValueError:Found unknown categories ['enterprise'] in column 1 during transformThe lenient model does not treat the unknown value as “missing”. On all 1,250 test customers, an unknown value gets exactly the score of the first category in alphabetical order (code 0). No categorical column had blanks in training, and for such a column LightGBM sends a blank down the same path as 0. An unknown contract would be scored silently as month-to-month, the riskiest level. The shipped pipeline therefore keeps handle_unknown="error" and fails loudly. The service must validate the categories before it calls the model, and answer with a clear error.
Save the shipped model and a metadata file: the threshold and its rule, the business settings, the input schema and the scores. The categories come from the fitted encoder, so they describe exactly what the model saw. trained_at is fixed so that the page gives the same output every run; real code uses date.today().isoformat().
import jsonfrom pathlib import Path
import joblibimport lightgbmimport sklearn
out = Path("output")out.mkdir(exist_ok=True)joblib.dump(final_model, out / "churn_model.joblib")encoder = final_model["prep"].named_transformers_["cat"]metadata = { "model_name": "churn-lgbm", "model_version": "1.0.0", "trained_at": "2025-01-06", "sklearn_version": sklearn.__version__, "lightgbm_version": lightgbm.__version__, "features": FEATURES, "categories": { c: cats.tolist() for c, cats in zip(CATEGORICAL, encoder.categories_, strict=True) }, "threshold": THRESHOLD, "business": { "call_share": CALL_SHARE, "call_cost_usd": CALL_COST, "save_rate": SAVE_RATE, "value_saved_usd": round(VALUE_SAVED, 2), }, "metrics": { "test_roc_auc": round(roc_auc_score(y_test, p_test), 4), "test_profit_per_1000_usd": round(per_1000(profit_test, len(y_test)), 2), },}(out / "metadata.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
reloaded = joblib.load(out / "churn_model.joblib")same = np.array_equal(reloaded.predict_proba(X_test)[:, 1], p_test)print(sorted(p.name for p in out.iterdir()))print("reloaded model gives the same probabilities:", same)assert same['churn_model.joblib', 'metadata.json']reloaded model gives the same probabilities: Truetrain_churn.py packs the final recipe into one script that anyone can rerun: the same splits, the same pipeline, the break-even threshold, the validation diagnostics, one test evaluation and the two output files. It does not repeat the model search; that is the analysis above. Its metadata adds a hash of the data file, the training range of each numeric column, the timing assumption in the output field and the validation diagnostics.
"""Train the churn model and save it for the prediction service.
Usage (from the project folder): python train_churn.py [--data PATH] [--out DIR]
Writes DIR/churn_model.joblib (the fitted scikit-learn pipeline) andDIR/metadata.json (threshold, business settings, scores and the input schema).The pipeline takes a DataFrame with the 12 FEATURES columns and returnsP(churn) from predict_proba(X)[:, 1]. An unknown or blank category raisesValueError: validate the inputs against metadata["categories"] first."""
import argparseimport hashlibimport jsonfrom pathlib import Path
import joblibimport lightgbmimport numpy as npimport pandas as pdimport sklearnfrom lightgbm import LGBMClassifierfrom sklearn.compose import ColumnTransformerfrom sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, cross_validate, train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OrdinalEncoder
CATEGORICAL = ["region", "plan", "contract", "payment_method"]NUMERIC = [ "age", "has_autopay", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes",]FEATURES = CATEGORICAL + NUMERICTARGET = "churned"SEED = 42MODEL_VERSION = "1.0.0"TRAINED_AT = "2025-01-06" # fixed for the course; real code: date.today().isoformat()
# Business settings of the retention campaignCALL_SHARE = 0.20 # budget: 1,000 calls per month for 5,000 customersCALL_COST = 40.0 # USD per call, offer includedSAVE_RATE = 0.30 # share of called churners who stayMONTHS_KEPT = 6 # months of charges that a saved churner keeps payingTHRESHOLDS = np.round(np.arange(0.05, 0.951, 0.01), 2)
def build_pipeline() -> Pipeline: """Return the unfitted pipeline: ordinal codes plus a small LightGBM.
The encoder raises ValueError for a category it did not see in training. """ prep = ColumnTransformer( [("cat", OrdinalEncoder(handle_unknown="error"), CATEGORICAL)], remainder="passthrough", verbose_feature_names_out=False, ).set_output(transform="pandas") model = LGBMClassifier( n_estimators=150, learning_rate=0.03, num_leaves=8, min_child_samples=40, random_state=SEED, verbose=-1, ) return Pipeline([("prep", prep), ("model", model)])
def expected_profit( y_true: np.ndarray, scores: np.ndarray, threshold: float, value_saved: float) -> tuple[float, int]: """Return (expected profit in USD, calls) for one threshold, within budget.""" y_true, scores = np.asarray(y_true), np.asarray(scores) order = np.argsort(-scores, kind="stable") n_calls = min(int((scores >= threshold).sum()), int(CALL_SHARE * len(scores))) saved = SAVE_RATE * y_true[order[:n_calls]].sum() return float(saved * value_saved - CALL_COST * n_calls), n_calls
def choose_threshold( y_true: np.ndarray, scores: np.ndarray, value_saved: float) -> float: """Return the threshold with the highest expected profit (highest on ties).""" profits = [expected_profit(y_true, scores, t, value_saved)[0] for t in THRESHOLDS] return float(THRESHOLDS[len(profits) - 1 - int(np.argmax(profits[::-1]))])
def file_sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--data", type=Path, default=Path("data/customers.csv")) parser.add_argument("--out", type=Path, default=Path("models")) args = parser.parse_args()
customers = pd.read_csv(args.data) X, y = customers[FEATURES], customers[TARGET] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=SEED ) X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.25, stratify=y_train, random_state=SEED ) churner_charges = X_train.loc[y_train == 1, "monthly_charges"] value_saved = MONTHS_KEPT * float(churner_charges.mean()) threshold = round(CALL_COST / (SAVE_RATE * value_saved), 3) # break-even
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED) cv_res = cross_validate( build_pipeline(), X_train, y_train, cv=cv, scoring={"roc_auc": "roc_auc", "pr_auc": "average_precision"}, ) # Diagnostic only: calibration and the empirical best threshold on validation p_val = build_pipeline().fit(X_fit, y_fit).predict_proba(X_val)[:, 1] val_best = choose_threshold(y_val, p_val, value_saved)
pipeline = build_pipeline().fit(X_train, y_train) # the shipped model p_test = pipeline.predict_proba(X_test)[:, 1] profit, n_calls = expected_profit(y_test, p_test, threshold, value_saved) encoder = pipeline["prep"].named_transformers_["cat"]
metadata = { "model_name": "churn-lgbm", "model_version": MODEL_VERSION, "trained_at": TRAINED_AT, "data_file": args.data.name, "data_sha256": file_sha256(args.data), "n_train": len(X_train), "sklearn_version": sklearn.__version__, "lightgbm_version": lightgbm.__version__, "features": FEATURES, "categories": { c: cats.tolist() for c, cats in zip(CATEGORICAL, encoder.categories_, strict=True) }, "numeric_ranges": { c: [float(X_train[c].min()), float(X_train[c].max())] for c in NUMERIC }, "output": ( "predict_proba(X)[:, 1] = P(churn within the month after the " "feature snapshot); assumes the features precede the churn window" ), "threshold": threshold, "threshold_rule": "break-even: call_cost_usd / (save_rate * value_saved_usd)", "business": { "call_share": CALL_SHARE, "call_cost_usd": CALL_COST, "save_rate": SAVE_RATE, "value_saved_usd": round(value_saved, 2), }, "metrics": { "cv_roc_auc": round(float(cv_res["test_roc_auc"].mean()), 4), "cv_pr_auc": round(float(cv_res["test_pr_auc"].mean()), 4), "val_brier": round(float(brier_score_loss(y_val, p_val)), 4), "val_best_threshold": val_best, "test_roc_auc": round(float(roc_auc_score(y_test, p_test)), 4), "test_pr_auc": round(float(average_precision_score(y_test, p_test)), 4), "test_brier": round(float(brier_score_loss(y_test, p_test)), 4), "test_profit_per_1000_usd": round(1000 * profit / len(y_test), 2), }, } args.out.mkdir(parents=True, exist_ok=True) joblib.dump(pipeline, args.out / "churn_model.joblib") (args.out / "metadata.json").write_text( json.dumps(metadata, indent=2), encoding="utf-8" ) print(f"train {len(X_train):,} (fit {len(X_fit):,} + validation {len(X_val):,})") print( f"CV ROC-AUC {metadata['metrics']['cv_roc_auc']:.3f}, " f"PR-AUC {metadata['metrics']['cv_pr_auc']:.3f}" ) print(f"threshold {threshold:.3f} (break-even); validation best {val_best:.2f}") print( f"test: {n_calls} calls, USD {1000 * profit / len(y_test):,.0f} " "expected profit per 1,000 customers" ) print(f"saved {args.out / 'churn_model.joblib'} and {args.out / 'metadata.json'}")
if __name__ == "__main__": main()python train_churn.pytrain 3,750 (fit 2,812 + validation 938)CV ROC-AUC 0.844, PR-AUC 0.623threshold 0.335 (break-even); validation best 0.39test: 249 calls, USD 5,395 expected profit per 1,000 customerssaved models/churn_model.joblib and models/metadata.jsonCheck that the script and the analysis agree, then use the saved files as a service would: validate the categories, build a DataFrame with the 12 input columns and apply the decision rule from the metadata. The second new customer has a blank total_charges, which the model accepts.
import train_churn
pipeline = joblib.load("models/churn_model.joblib")meta = json.loads(Path("models/metadata.json").read_text(encoding="utf-8"))assert train_churn.FEATURES == FEATURES == meta["features"]assert np.array_equal(pipeline.predict_proba(X_test)[:, 1], p_test)assert meta["threshold"] == THRESHOLDprint("script model = analysis model; threshold", meta["threshold"])
new_customers = pd.DataFrame( [ {"region": "South", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "age": 29, "has_autopay": 0, "tenure_months": 2, "monthly_charges": 104.5, "total_charges": 209.0, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5}, {"region": "West", "plan": "standard", "contract": "two-year", "payment_method": "credit_card", "age": 51, "has_autopay": 1, "tenure_months": 0, "monthly_charges": 61.0, "total_charges": np.nan, "support_tickets": 0, "logins_last_30d": 15, "avg_session_minutes": 18.0}, ], columns=meta["features"],)for column, allowed in meta["categories"].items(): assert new_customers[column].isin(allowed).all(), columnproba = pipeline.predict_proba(new_customers)[:, 1]for p in proba: print(f"P(churn) {p:.3f} call: {p >= meta['threshold']}")script model = analysis model; threshold 0.335P(churn) 0.896 call: TrueP(churn) 0.046 call: FalseStretch goals
Section titled “Stretch goals”- Value per customer. Replace the constant
Vwith 6 × each customer’s ownmonthly_charges. The rule becomes “call when ”, which is no longer one threshold. Rank by expected profit instead of probability and compare the test profit with a bootstrap interval. - SMOTENC. Add SMOTENC inside the folds as a fourth imbalance variant (impute
total_charges, resample the raw columns, then encode), with its own small grid of settings. - Sensitivity to the finance numbers. The save rate 0.30 comes from one pilot. Recompute the break-even threshold, the calls and the test profit for save rates from 0.2 to 0.4. At which save rate does the campaign stop paying?
- Nested cross-validation. Tune the LightGBM settings with Optuna inside the training folds, and estimate the optimism of the manual search of Milestone 3.
- Timing check. Rebuild the model without
logins_last_30dand repeat Milestones 5 and 6. How much profit does the timing risk cost?
Next steps
Section titled “Next steps”- Capstone 8 — Deployment serves
models/churn_model.joblibwith FastAPI, validates the inputs againstmetadata.jsonand tests the service. - Module 44 shows how to monitor such a model for drift after launch.
- Capstone 5 — Customer segmentation looks at the same kind of customers without a label.