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: Customer Churn Model with scikit-learn

Open In Colab

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.

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

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.

A3. The baseline

What accuracy does the “model” that predicts nobody leaves reach on the test set? Store it in baseline.

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.

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.

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.

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?

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.

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.

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.

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?

AI-use log (if you used an AI assistant)

What you asked, what you kept, what you changed.