Lab 7: Customer Churn Model with scikit-learn¶
In this lab you build and validate a churn model, then use it to decide who gets a retention offer.
The question. Qahwa House can send a retention voucher to loyalty-app members who look likely to leave. Which members should get one, and how much is the campaign worth?
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part D, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import pandas as pd
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
members = load("qahwa_members_2025.csv")
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, precision_score, recall_score, roc_auc_score, accuracy_score
members.head()| Column | Meaning |
|---|---|
member_id, branch | the member and their usual branch |
tenure_months | months since the member joined the app |
visits_90d | visits in the 90 days to 30 September 2025 |
days_since_last | days since the last visit (above 90 when there was no visit in the period) |
avg_basket_sar | average spend per visit (SAR) |
offers_used_90d | app offers redeemed in the period |
complaint_90d | 1 if the member made a complaint in the period |
churned | the target: 1 if the member made no visit at all from October to December 2025 |
The economics of the offer. A retention voucher costs Qahwa House 10 SAR per member who receives it. A member who was about to leave and gets the voucher stays with probability 40%, and a member who stays brings about 150 SAR of margin over the next year. So:
| the member would leave | the member would stay | |
|---|---|---|
| send the voucher | 0.4 × 150 − 10 = +50 SAR (a true positive) | −10 SAR (a false positive: a wasted voucher) |
| send nothing | 0 (a false negative: a lost chance) | 0 (a true negative) |
Part A: The data and the split¶
A1. The churn rate¶
What share of the members churned? Store it in churn_rate (a number between 0 and 1).
churn_rate = ...
churn_ratecheck("A1 about one member in five churned", 0.20 < churn_rate < 0.23)A2. Features, target and split¶
Build X: every column except member_id and churned, with branch turned into dummy columns (pd.get_dummies(..., columns=["branch"], drop_first=True, dtype=int)). The target y is churned. Then split with train_test_split: 30% for the test set, random_state=631 and stratify=y.
X = ...
y = ...
X_train, X_test, y_train, y_test = ...
X_train.shape, X_test.shapecheck("A2 nine features (six numbers, three branch dummies)", X.shape[1] == 9 and "branch" not in X.columns)
check("A2 1,800 members in the test set", len(X_test) == 1800)
check("A2 the same churn rate in both sets", abs(y_train.mean() - y_test.mean()) < 0.005)A3. The baseline¶
What accuracy does the “model” that predicts nobody leaves reach on the test set? Store it in baseline.
baseline = ...
baselinecheck("A3 the baseline accuracy", round(baseline, 3) == 0.786)Part B: Overfitting and cross-validation¶
B1. A tree without limits¶
Fit a DecisionTreeClassifier(random_state=631) with no maximum depth on the training set. Store its accuracy on the training set in tree_train and on the test set in tree_test.
full = ...
tree_train = ...
tree_test = ...
print(f"training {tree_train:.1%} test {tree_test:.1%} baseline {baseline:.1%}")check("B1 perfect on the training set", tree_train == 1)
check("B1 worse than the baseline on new members", tree_test < baseline)B2. Choose the depth by cross-validation¶
For each maximum depth in [2, 3, 4, 5, 6, 8, None], compute the mean 5-fold cross-validated AUC on the training set (cross_val_score(..., cv=5, scoring="roc_auc")). Store the results in a Series cv_auc indexed by the depth as text (str(d)), and the best depth (as text) in best_depth.
cv_auc = {}
for d in [2, 3, 4, 5, 6, 8, None]:
cv_auc[str(d)] = ...
cv_auc = pd.Series(cv_auc)
best_depth = ...
print(cv_auc.round(3).to_string(), "\nbest:", best_depth)check("B2 seven depths scored", len(cv_auc) == 7)
check("B2 a medium depth wins", best_depth in ("4", "5"))
check("B2 the unlimited tree scores worst", cv_auc.idxmin() == "None")B3. In two sentences: why does the unlimited tree do worse than predicting that nobody leaves, and why must we choose the depth with cross-validation rather than with the test set?
Your answer here (double-click to edit).
Part C: Logistic regression¶
C1. Fit and score¶
Fit LogisticRegression(max_iter=1000) on the training set and store it in logit. Store the predicted churn probabilities of the test members in p_test (the second column of predict_proba) and the test AUC in auc.
logit = ...
p_test = ...
auc = ...
auccheck("C1 one probability per test member", len(p_test) == 1800 and 0 <= p_test.min() and p_test.max() <= 1)
check("C1 a better ranking than the best tree", auc > 0.78)C2. Odds ratios¶
Store the odds ratios (the exponential of the coefficients) in a Series odds indexed by the feature names. Which feature raises the odds of churn most?
odds = ...
odds.round(3).sort_values()check("C2 a complaint more than doubles the odds", odds["complaint_90d"] > 2)
check("C2 more visits lower the odds", odds["visits_90d"] < 1)C3. The confusion matrix at 0.5¶
Predict churn when p_test >= 0.5. Store the confusion matrix in cm, the precision in prec and the recall in rec.
pred = ...
cm = ...
prec = ...
rec = ...
print(cm, f"\nprecision {prec:.1%} recall {rec:.1%}")check("C3 a 2 x 2 matrix over the 1,800 test members", cm.shape == (2, 2) and cm.sum() == 1800)
check("C3 the model misses most churners at 0.5", rec < 0.35)
check("C3 but is usually right when it flags someone", prec > 0.6)Part D: The decision¶
D1. The profit of a campaign¶
Write profit(threshold): send the voucher to every test member with p_test >= threshold and return the profit in SAR, +50 for each voucher sent to a member who churned and −10 for each voucher sent to a member who stayed.
def profit(threshold):
send = ...
...
return ...
profit(0.5), profit(0)check("D1 the default threshold earns 4,910 SAR", profit(0.5) == 4910)
check("D1 sending to everybody earns 5,100 SAR", profit(0) == 5100)D2. Scan the thresholds¶
For every threshold from 0.01 to 0.99 in steps of 0.01 (np.round(np.arange(0.01, 1.0, 0.01), 2)), compute the profit and the accuracy. Store them in a DataFrame scan (columns profit and accuracy, indexed by the threshold), then the threshold with the highest profit in best_t and the one with the highest accuracy in acc_t. The cell then plots both curves.
thresholds = np.round(np.arange(0.01, 1.0, 0.01), 2)
scan = ...
best_t = ...
acc_t = ...
fig, ax1 = plt.subplots(figsize=(7, 3.4))
ax1.plot(scan.index, scan["profit"], color="#1f6f8b", lw=2.5)
ax1.set_xlabel("threshold")
ax1.set_ylabel("profit (SAR)", color="#1f6f8b")
ax2 = ax1.twinx()
ax2.plot(scan.index, scan["accuracy"], color="#e07b39")
ax2.set_ylabel("accuracy", color="#e07b39")
plt.show()
print("best profit at", best_t, "| best accuracy at", acc_t)check("D2 99 thresholds", len(scan) == 99)
check("D2 the profit peaks near the break-even 1/6", 0.12 <= best_t <= 0.22)
check("D2 accuracy peaks at a much higher threshold", acc_t >= 0.5)
check("D2 the accuracy-best threshold earns less than half as much", scan.loc[acc_t, "profit"] < scan["profit"].max() / 2)D3. Your recommendation¶
Write three sentences for the marketing manager: which members should get the voucher (state the rule as a probability threshold and explain where it comes from), what the campaign is worth compared with the alternatives (with numbers from D1 and D2), and one thing to check or test before rolling it out.
Write your recommendation here (double-click to edit).
★ Extended challenges¶
E1. A dearer voucher. If the voucher cost 20 SAR (and still kept 40% of the would-be churners), what would the break-even threshold be? Find the best threshold with a scan and compare.
E2. Lift. Sort the test members by p_test, highest first. What share of all churners is in the top 20% of the list? How does that compare with 20% chosen at random?
E3. A random forest. Compare the 5-fold cross-validated AUC of RandomForestClassifier(n_estimators=300, min_samples_leaf=20, random_state=631) with that of the logistic regression. Is the extra complexity worth it here?
# E1# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.