Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 7 Solutions: Customer Churn Model with scikit-learn

Open In Colab

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.

Loading...
ColumnMeaning
member_id, branchthe member and their usual branch
tenure_monthsmonths since the member joined the app
visits_90dvisits in the 90 days to 30 September 2025
days_since_lastdays since the last visit (above 90 when there was no visit in the period)
avg_basket_saraverage spend per visit (SAR)
offers_used_90dapp offers redeemed in the period
complaint_90d1 if the member made a complaint in the period
churnedthe 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 leavethe member would stay
send the voucher0.4 × 150 − 10 = +50 SAR (a true positive)−10 SAR (a false positive: a wasted voucher)
send nothing0 (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).

np.float64(0.21383333333333332)
✅ 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.

((4200, 9), (1800, 9))
✅ 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.

np.float64(0.7861111111111111)
✅ 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.

training 100.0%   test 71.2%   baseline 78.6%
✅ 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.

2       0.742
3       0.759
4       0.778
5       0.778
6       0.767
8       0.711
None    0.632 
best: 4
✅ 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.

0.7924445872149053
✅ 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?

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: float64
✅ 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.

[[1356   59]
 [ 275  110]] 
precision 65.1%   recall 28.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.

(np.int64(4910), np.int64(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.

<Figure size 700x340 with 2 Axes>
best profit at 0.17 | best accuracy at 0.65
✅ 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?

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.

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.

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.