Lab 7 Solutions: Customer Churn Model with scikit-learn¶
These are the worked solutions, with outputs. Try the lab yourself first.
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 = members["churned"].mean()
churn_ratenp.float64(0.21383333333333332)check("A1 about one member in five churned", 0.20 < churn_rate < 0.23)✅ A1 about one member in five churned
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 = pd.get_dummies(members.drop(columns=["member_id", "churned"]), columns=["branch"], drop_first=True, dtype=int)
y = members["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=631, stratify=y)
X_train.shape, X_test.shape((4200, 9), (1800, 9))check("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)✅ A2 nine features (six numbers, three branch dummies)
✅ A2 1,800 members in the test set
✅ A2 the same churn rate in both sets
A3. The baseline¶
What accuracy does the “model” that predicts nobody leaves reach on the test set? Store it in baseline.
baseline = (y_test == 0).mean()
baselinenp.float64(0.7861111111111111)check("A3 the baseline accuracy", round(baseline, 3) == 0.786)✅ A3 the baseline accuracy
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 = DecisionTreeClassifier(random_state=631).fit(X_train, y_train)
tree_train = full.score(X_train, y_train)
tree_test = full.score(X_test, y_test)
print(f"training {tree_train:.1%} test {tree_test:.1%} baseline {baseline:.1%}")training 100.0% test 71.2% baseline 78.6%
check("B1 perfect on the training set", tree_train == 1)
check("B1 worse than the baseline on new members", tree_test < baseline)✅ B1 perfect on the training set
✅ B1 worse than the baseline on new members
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)] = cross_val_score(DecisionTreeClassifier(max_depth=d, random_state=631),
X_train, y_train, cv=5, scoring="roc_auc").mean()
cv_auc = pd.Series(cv_auc)
best_depth = cv_auc.idxmax()
print(cv_auc.round(3).to_string(), "\nbest:", best_depth)2 0.742
3 0.759
4 0.778
5 0.778
6 0.767
8 0.711
None 0.632
best: 4
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")✅ B2 seven depths scored
✅ B2 a medium depth wins
✅ B2 the unlimited tree scores worst
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?
Answer. The unlimited tree splits until every training member is classified correctly, so it learns the noise of those 4,200 members, and its rules fail on new members (71.2% accuracy, against 78.6% for “nobody leaves”). If we used the test set to choose the depth, the test set would become part of the model-building and would no longer measure performance on truly new data; cross-validation chooses on the training set only.
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 = LogisticRegression(max_iter=1000).fit(X_train, y_train)
p_test = logit.predict_proba(X_test)[:, 1]
auc = roc_auc_score(y_test, p_test)
auc0.7924445872149053check("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)✅ C1 one probability per test member
✅ C1 a better ranking than the best tree
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 = pd.Series(np.exp(logit.coef_[0]), index=X.columns)
odds.round(3).sort_values()branch_Corniche 0.752
visits_90d 0.776
branch_Olaya 0.802
offers_used_90d 0.855
avg_basket_sar 0.967
tenure_months 0.993
days_since_last 1.020
branch_University 1.209
complaint_90d 2.150
dtype: float64check("C2 a complaint more than doubles the odds", odds["complaint_90d"] > 2)
check("C2 more visits lower the odds", odds["visits_90d"] < 1)✅ C2 a complaint more than doubles the odds
✅ C2 more visits lower the odds
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 = (p_test >= 0.5).astype(int)
cm = confusion_matrix(y_test, pred)
prec = precision_score(y_test, pred)
rec = recall_score(y_test, pred)
print(cm, f"\nprecision {prec:.1%} recall {rec:.1%}")[[1356 59]
[ 275 110]]
precision 65.1% recall 28.6%
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)✅ C3 a 2 x 2 matrix over the 1,800 test members
✅ C3 the model misses most churners at 0.5
✅ C3 but is usually right when it flags someone
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 = p_test >= threshold
tp = (send & (y_test == 1)).sum()
fp = (send & (y_test == 0)).sum()
return 50 * tp - 10 * fp
profit(0.5), profit(0)(np.int64(4910), np.int64(5100))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)✅ D1 the default threshold earns 4,910 SAR
✅ D1 sending to everybody earns 5,100 SAR
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 = pd.DataFrame({"profit": [profit(t) for t in thresholds],
"accuracy": [accuracy_score(y_test, p_test >= t) for t in thresholds]}, index=thresholds)
best_t = scan["profit"].idxmax()
acc_t = scan["accuracy"].idxmax()
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)
best profit at 0.17 | best accuracy at 0.65
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)✅ D2 99 thresholds
✅ D2 the profit peaks near the break-even 1/6
✅ D2 accuracy peaks at a much higher threshold
✅ D2 the accuracy-best threshold earns less than half as much
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.
Recommendation. Send the voucher to every member whose predicted churn probability is at least 1/6 (about 0.17): a voucher costs 10 SAR and is worth 0.4 × 150 = 60 SAR when it reaches a member who would have left, so it pays whenever the probability exceeds 10/60. On the 1,800 test members this rule earns about 10,050 SAR, against 5,100 SAR for sending to everybody and only 3,790 SAR for the threshold that maximises the model’s accuracy, even though its accuracy is lower (66% against 82%). Before rolling it out, test the 40% save rate: send the voucher to a random half of the flagged members and compare their churn with the other half.
★ 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: a 20-SAR voucher: +40 for a true positive (0.4 x 150 - 20), -20 for a false positive
def profit_at(threshold, cost):
send = p_test >= threshold
tp = (send & (y_test == 1)).sum()
fp = (send & (y_test == 0)).sum()
return (0.4 * 150 - cost) * tp - cost * fp
scan20 = pd.Series([profit_at(t, 20) for t in thresholds], index=thresholds)
print(f"break-even threshold: 20 / 60 = {20 / 60:.3f}")
print(f"best threshold on the test set: {scan20.idxmax():.2f}, profit {scan20.max():,.0f} SAR")break-even threshold: 20 / 60 = 0.333
best threshold on the test set: 0.33, profit 4,080 SAR
The break-even rule gives 20 / 60 = 1/3, and the scan agrees closely. A dearer voucher raises the bar: fewer members are worth targeting, and the campaign earns less.
# E2: lift of the top 20%
order = np.argsort(-p_test)
top = order[: int(0.2 * len(order))]
share = y_test.to_numpy()[top].sum() / y_test.sum()
print(f"the top 20% of the list holds {share:.1%} of all churners (20% at random would hold 20%): lift {share / 0.2:.2f}")the top 20% of the list holds 47.8% of all churners (20% at random would hold 20%): lift 2.39
Ranking by the model concentrates the churners: the top fifth of the list holds well over twice its share of them. That is the AUC put to work.
# E3: random forest against logistic regression, 5-fold cross-validated AUC on the training set
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=300, min_samples_leaf=20, random_state=631)
cv_rf = cross_val_score(rf, X_train, y_train, cv=5, scoring="roc_auc")
cv_lr = cross_val_score(LogisticRegression(max_iter=1000), X_train, y_train, cv=5, scoring="roc_auc")
print(f"random forest: {cv_rf.mean():.3f}")
print(f"logistic regression: {cv_lr.mean():.3f}")random forest: 0.801
logistic regression: 0.811
The forest, an average of 300 trees, does far better than a single tree but no better than the logistic regression, which is simpler to fit, to explain and to check. Here the extra complexity is not worth it; on data with strong interactions between features it often is.