Skip to content

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.

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.

Your script must:

  1. Split the data 75/25 with stratify and random_state=42. Split a 25% validation set off the training part the same way. Do not touch the test set before the final report.
  2. 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.
  3. Pick one model and state the reason in one sentence.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. Write the flagged test customers to output/call_list.csv with customer_id and churn_probability, highest risk first, and print the first five rows.
  9. End with a three-line recommendation for the retention manager and at least two assert checks.
  10. Run in under a minute on a laptop.
  1. Load and split. Read the CSV, define the feature lists and make the train/test split. Then split X_train into X_fit and X_val. Print the sizes and the churn rate of each part.

  2. Build the preprocessing. Write make_preprocess() (impute, scale, one-hot) for logistic regression. Cast the four text columns to a CategoricalDtype built from the training data for the boosting model. Trees need no scaling.

  3. Compare models. Loop over a dict of models with cross_validate and scoring=["roc_auc", "average_precision", "neg_brier_score"]. Put the means in a DataFrame sorted by ROC-AUC.

  4. Choose and check calibration. Fit the winner on X_fit. Use calibration_curve(..., n_bins=5, strategy="quantile") on the validation probabilities. If the predicted and observed rows are close, keep the model as it is.

  5. 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.

  6. Final test report. Predict the test set once with the model from step 4 and print every number from requirement 6.

  7. Explain. Fit make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000)) on X_train, exponentiate the coefficients, and sort each group (numeric, one-hot) by the size of the log-odds effect.

  8. Deliver. Build the call list with customer_id from 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 (starter)
# churn_warning.py: a churn early-warning model and a cost-based call list.
from pathlib import Path
import numpy as np
import 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, asserts
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
  • Replace the manual threshold search with TunedThresholdClassifierCV and 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 contract type. 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, or p × monthly_charges × 12 − 50 with a revenue-based loss.
Reference solution

The solution runs as one script. Each block below continues the previous one.

from pathlib import Path
import numpy as np
import pandas as pd
from lightgbm import LGBMClassifier
from sklearn.calibration import calibration_curve
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
average_precision_score,
brier_score_loss,
confusion_matrix,
roc_auc_score,
)
from sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
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}")
Output
fit 2812 rows, churn rate 0.192
validation 938 rows, churn rate 0.193
test 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))
Output
roc_auc auc_std pr_auc brier
model
random forest 0.838 0.011 0.600 0.113
LightGBM 0.835 0.016 0.605 0.113
logistic regression 0.813 0.012 0.553 0.119

The 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)
Output
validation Brier 0.109
0 1 2 3 4
predicted 0.012 0.038 0.088 0.218 0.578
observed 0.027 0.053 0.090 0.214 0.580

The 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():,})")
Output
theoretical threshold 0.167
chosen 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,}")
Output
test ROC-AUC 0.831
test PR-AUC 0.582
test Brier 0.116
no call call
stayed 725 284
churned 54 187
threshold 0.14 cost 39,750
threshold 0.50 cost 51,600
no 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))
Output
numeric features, per standard deviation
coef odds_ratio
tenure_months -0.916 0.400
support_tickets 0.543 1.721
monthly_charges 0.454 1.574
one-hot levels, against the reference level
coef odds_ratio
contract_two-year -1.726 0.178
contract_one-year -1.052 0.349
payment_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_decreasing
chosen_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.8
Output
471 customers to call, saved to output/call_list.csv
customer_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:

  1. 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.
  2. The validation threshold lands close to the theoretical 50 / 300, a second sign that the probabilities are well calibrated.
  3. 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.
  4. 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.