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.

Model Validation and Classification

Open In Colab

Model Validation and Classification

Last week, regression predicted a number. Many business decisions turn on a category instead: will this customer leave or stay, will this invoice be paid late, is this transaction a fraud? A model that predicts a category is a classifier. This reading builds two classifiers in scikit-learn, shows how to judge them honestly on data they have not seen, and then turns their predictions into a decision with a price on every kind of error.

After this reading you can:

  • explain why a model is judged on data it has not seen, and split the data into training and test sets;

  • fit a logistic regression and a decision tree with scikit-learn and read their output;

  • build a confusion matrix and compute accuracy, precision and recall;

  • read an ROC curve and its AUC;

  • recognise overfitting and use cross-validation to choose a model’s complexity;

  • choose a classification threshold from the costs and benefits of each kind of error.

Textbook: Albright & Winston, Chapters 11 and 17.

The decision

Qahwa House’s loyalty app has 6,000 members. Some of them stop coming. The marketing team can send a retention voucher, but vouchers cost money, so they should go to the members most likely to leave. Which members should get one?

The data describes each member on 30 September 2025, from their activity over the previous 90 days, and records whether they then churned: made no visit at all from October to December.

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
members: 6,000   churned: 1,283 (21.4%)
branch Al Faisaliyah 22.8 Corniche 17.7 Olaya 19.6 University 25.9 Name: churn rate (%), dtype: float64

About one member in five churned (21.4%). The University branch loses most: its members are students, and many leave over the summer break.

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)

1. Train and test: judge a model on new data

A model is useful only if it predicts well for members it has not seen: next quarter’s members, not last quarter’s. So we hide part of the data while we build the model, and judge the model on that part only.

  • The training set (here 70% of the members) is used to fit the model.

  • The test set (the other 30%) is used once, at the end, to measure how well it predicts.

train_test_split draws the two sets at random. stratify=y keeps the same churn rate in both, and random_state makes the split reproducible. scikit-learn needs numbers, so the branch column becomes dummy columns, as in Week 6.

training set: (4200, 9)  churners: 898
test set:     (1800, 9)  churners: 385
features: ['tenure_months', 'visits_90d', 'days_since_last', 'avg_basket_sar', 'offers_used_90d', 'complaint_90d', 'branch_Corniche', 'branch_Olaya', 'branch_University']

The accuracy trap. Before building anything, look at the simplest “model” of all: predict that nobody leaves. It is right for every member who stays.

accuracy of 'nobody leaves' on the test set: 78.6%

It is right 78.6% of the time, and it saves no one. When one class is much rarer than the other, accuracy (the share of correct predictions) flatters any model. Keep this number in mind: a churn model must do better than 78.6% to beat doing nothing, and accuracy is not the right yardstick for the decision anyway (section 6).

2. Logistic regression

Linear regression could predict 0 or 1, but its predictions would run below 0 and above 1. Logistic regression passes the linear combination of the features through the S-shaped logistic function, so the prediction is always a probability between 0 and 1:

P(churn)=11+e−(b0+b1x1+⋯+bkxk)P(\text{churn}) = \frac{1}{1 + e^{-(b_0 + b_1 x_1 + \dots + b_k x_k)}}
<Figure size 600x300 with 1 Axes>

In scikit-learn every model works the same way: create it, fit it on the training set, then predict classes or predict_proba probabilities. (max_iter=1000 gives the fitting algorithm enough steps to converge.)

first five members of the test set: [0.03  0.1   0.066 0.266 0.008]
test accuracy at the default threshold 0.5: 81.4%

At the default threshold (predict churn when the probability is at least 0.5) the model is right 81.4% of the time: only 2.8 points better than “nobody leaves”. Does that make it useless? Not at all, as the next sections show.

Reading the coefficients. A coefficient changes the log-odds of churn, which is hard to picture. Its exponential, the odds ratio, multiplies the odds of churn when the feature grows by one unit, the others held fixed:

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
  • A complaint multiplies the odds of churn by 2.15: more than doubles them.

  • Each extra visit in the last 90 days multiplies them by 0.776 (22% lower odds); each redeemed offer by 0.855.

  • Each day since the last visit multiplies them by 1.02, so ten more days multiply them by 1.02¹⁰ ≈ 1.22.

  • The branch dummies compare each branch with Al Faisaliyah (the dropped one): University members have 1.21 times the odds.

scikit-learn’s LogisticRegression shrinks the coefficients slightly by default (a penalty that guards against overfitting) and reports no p-values. For p-values and confidence intervals, statsmodels’ Logit fits the same model the Week 6 way.

3. The confusion matrix

A probability becomes a decision with a threshold: predict churn when P(churn)≥tP(\text{churn}) \ge t. The confusion matrix counts the four outcomes on the test set:

predicted: stayspredicted: leaves
actually staystrue negative (TN)false positive (FP)
actually leavesfalse negative (FN)true positive (TP)
                 predicted: stays  predicted: leaves
actually stays               1356                 59
actually leaves               275                110

precision: 65.1%   recall: 28.6%

Two rates describe the predicted churners better than accuracy:

  • Precision = TP / (TP + FP): of the members we flag, how many really leave? Here 110 / 169 = 65.1%.

  • Recall (sensitivity) = TP / (TP + FN): of the members who leave, how many do we flag? Here 110 / 385 = 28.6%.

At the threshold 0.5 the model is cautious: when it flags a member it is usually right, but it misses 275 of the 385 churners. Lowering the threshold flags more members, raising recall and lowering precision. Which balance is right depends on what each error costs, which is the subject of section 6.

4. The ROC curve and AUC

To judge the model’s ranking independently of any threshold, sweep the threshold from 1 down to 0 and plot, at each step, the share of churners caught (the true positive rate, i.e. recall) against the share of stayers wrongly flagged (the false positive rate, FP / (FP + TN)). That is the ROC curve.

<Figure size 460x420 with 1 Axes>
  • A perfect model goes straight up to the top-left corner; random guessing follows the diagonal.

  • The AUC (area under the curve) summarises the curve in one number. It is the probability that a randomly chosen churner gets a higher score than a randomly chosen stayer: 0.5 for guessing, 1 for a perfect ranking. Here it is 0.792.

  • The curve shows the trade-off on offer: catching 60% of the churners means flagging about 20% of the stayers; catching 80% means flagging about 40%.

So a model that is “only” 81.4% accurate ranks members far better than chance. That ranking is what the voucher decision needs.

5. Decision trees, overfitting and cross-validation

A decision tree splits the members again and again on one feature at a time, and predicts the churn rate of the group each member ends in. A tree of depth 2 reads like a rule book:

|--- days_since_last <= 74.50
|   |--- visits_90d <= 3.50
|   |   |--- weights: [915.00, 412.00] class: 0
|   |--- visits_90d >  3.50
|   |   |--- weights: [2322.00, 248.00] class: 0
|--- days_since_last >  74.50
|   |--- days_since_last <= 114.50
|   |   |--- weights: [57.00, 115.00] class: 1
|   |--- days_since_last >  114.50
|   |   |--- weights: [8.00, 123.00] class: 1

Each leaf shows how many training members it holds as [stayed, churned]. Members who have not visited for more than about 75 days mostly churn; regular visitors rarely do. Easy to explain to a manager.

Overfitting. Let the tree grow without limit and it keeps splitting until every training member sits in a leaf with members of the same class:

depth 25, 816 leaves
training accuracy: 100.0%
test accuracy:     71.2%   ('nobody leaves': 78.6%)

A perfect score on the training set, and on new members a worse score than predicting that nobody leaves. The full tree has memorised the training members, noise included, instead of learning the pattern. This is overfitting: a model that is too flexible fits the accidents of its sample. The plot shows it happening as the tree grows:

<Figure size 640x340 with 1 Axes>

Training accuracy climbs steadily with depth; test accuracy stalls, then falls. The gap between the two curves is the overfitting.

Cross-validation. We should not pick the depth by looking at the test set: then the test set would no longer be new data. Instead, k-fold cross-validation splits the training set into k folds (here 5), fits the model on four folds, scores it on the fifth, and repeats so that each fold is scored once. The average of the five scores estimates performance on new data, and the test set stays untouched.

We score with the AUC rather than accuracy: with 79% stayers, accuracy barely separates the models (section 1).

5-fold cross-validated AUC by maximum depth:
1       0.624
2       0.742
3       0.759
4       0.778
5       0.778
6       0.767
8       0.711
10      0.688
None    0.632

logistic regression: 0.811  (folds: [0.823 0.806 0.811 0.805 0.808])

Cross-validation prefers a tree of depth 4 (AUC 0.778): shallower trees miss patterns, deeper ones overfit, and the unlimited tree (0.632) is not far above guessing. Logistic regression does better still (0.811), and its five folds agree closely, so it is the model we keep. A last look at the test set confirms the choice:

test AUC, tree of depth 4:    0.749
test AUC, logistic regression: 0.792

6. Choosing the threshold from costs and benefits

The model gives each member a probability pp of churning. Sending the voucher is worth, on average,

p×60−10 SAR(60=0.4×150),p \times 60 - 10 \text{ SAR} \quad (60 = 0.4 \times 150),

which is positive when p>10/60=1/6≈0.17p > 10/60 = 1/6 \approx 0.17. That break-even threshold comes from the business, not from the model. Let us check it on the test set by computing the profit of the campaign at every threshold:

highest accuracy: threshold 0.65, accuracy 81.9%, profit 3,790 SAR
highest profit:   threshold 0.17, accuracy 66.8%, profit 10,040 SAR
<Figure size 700x360 with 2 Axes>

The blue curve peaks at 0.17, exactly where the economics said; the orange curve, accuracy, peaks at 0.65. The two goals disagree. Here is what each policy earns on the 1,800 test members:

send to nobody                                  0
send to everybody                            5100
model, threshold 0.65 (highest accuracy)     3790
model, threshold 0.5 (the default)           4910
model, threshold 1/6 (break-even)           10050

at 1/6: 831 vouchers, 306 of 385 churners reached, precision 36.8%, recall 79.5%, accuracy 66.4%

The threshold that maximises accuracy earns 3,790 SAR, less than sending the voucher to everybody (5,100 SAR). The break-even threshold earns 10,050 SAR, 2.7 times as much, while its accuracy drops to 66.4%. It sends 831 vouchers and reaches 306 of the 385 churners (recall 79.5%); most of its vouchers go to members who would have stayed (precision 36.8%), and that is fine, because a wasted voucher costs 10 SAR while a saved member is worth 50.

The lesson: accuracy counts every error as equally bad. A business decision almost never does. Rank with the model, then set the threshold from the costs: with benefit BB for a true positive and cost cc per action, act when p>c/(B+c)p > c / (B + c), here 10 / 60.

Before rolling it out. The 40% save rate is an assumption. The honest next step is a test: send the vouchers to a random half of the flagged members and compare their churn with the other half. And check the features: the model may use only what is known on the day of the decision (a “visits in October” column would leak the answer).

Summary

  • Judge a model on data it has not seen: a training set to fit, a test set to judge, used once.

  • With a rare class, accuracy flatters: compare with the “nobody leaves” baseline, and prefer precision, recall and the AUC.

  • Logistic regression predicts a probability; its odds ratios say how each feature moves the odds.

  • A flexible model such as a deep decision tree can overfit; cross-validation on the training set chooses the complexity.

  • The threshold is a business decision: act when the probability exceeds cost / (benefit + cost).

Next week: time-series forecasting: trend, seasonality, exponential smoothing and forecast errors.