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.
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")
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 |
print(f"members: {len(members):,} churned: {members['churned'].sum():,} ({members['churned'].mean():.1%})")
members.groupby("branch")["churned"].mean().mul(100).round(1).rename("churn rate (%)")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: float64About 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 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) |
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.
from sklearn.model_selection import train_test_split
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)
print("training set:", X_train.shape, " churners:", y_train.sum())
print("test set: ", X_test.shape, " churners:", y_test.sum())
print("features:", list(X.columns))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.
baseline = (y_test == 0).mean()
print(f"accuracy of 'nobody leaves' on the test set: {baseline:.1%}")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:
import numpy as np
import matplotlib.pyplot as plt
z = np.linspace(-6, 6, 200)
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(z, 1 / (1 + np.exp(-z)), color="#1f6f8b", lw=2.5)
ax.axhline(0.5, color="grey", ls=":", lw=1)
ax.set_xlabel("b0 + b1 x1 + ... + bk xk")
ax.set_ylabel("P(churn)")
ax.set_ylim(-0.05, 1.05)
ax.grid(alpha=0.3)
plt.show()
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.)
from sklearn.linear_model import LogisticRegression
logit = LogisticRegression(max_iter=1000)
logit.fit(X_train, y_train)
p_test = logit.predict_proba(X_test)[:, 1] # the probability of class 1, churn
print("first five members of the test set:", p_test[:5].round(3))
print(f"test accuracy at the default threshold 0.5: {logit.score(X_test, y_test):.1%}")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:
odds = pd.Series(np.exp(logit.coef_[0]), index=X.columns).round(3)
odds.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: float64A 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 . The confusion matrix counts the four outcomes on the test set:
| predicted: stays | predicted: leaves | |
|---|---|---|
| actually stays | true negative (TN) | false positive (FP) |
| actually leaves | false negative (FN) | true positive (TP) |
from sklearn.metrics import confusion_matrix, precision_score, recall_score
pred = (p_test >= 0.5).astype(int)
cm = confusion_matrix(y_test, pred)
print(pd.DataFrame(cm, index=["actually stays", "actually leaves"], columns=["predicted: stays", "predicted: leaves"]))
print(f"\nprecision: {precision_score(y_test, pred):.1%} recall: {recall_score(y_test, pred):.1%}") 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.
from sklearn.metrics import roc_curve, roc_auc_score
fpr, tpr, _ = roc_curve(y_test, p_test)
auc = roc_auc_score(y_test, p_test)
fig, ax = plt.subplots(figsize=(4.6, 4.2))
ax.plot(fpr, tpr, color="#1f6f8b", lw=2.5, label=f"logistic regression (AUC = {auc:.3f})")
ax.plot([0, 1], [0, 1], color="grey", ls="--", lw=1, label="random guessing (AUC = 0.5)")
ax.set_xlabel("false positive rate (stayers flagged)")
ax.set_ylabel("true positive rate (churners caught)")
ax.legend(loc="lower right", fontsize=8)
ax.grid(alpha=0.3)
plt.show()
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:
from sklearn.tree import DecisionTreeClassifier, export_text
small = DecisionTreeClassifier(max_depth=2, random_state=631).fit(X_train, y_train)
print(export_text(small, feature_names=list(X.columns), show_weights=True))|--- 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:
full = DecisionTreeClassifier(random_state=631).fit(X_train, y_train)
print(f"depth {full.get_depth()}, {full.get_n_leaves()} leaves")
print(f"training accuracy: {full.score(X_train, y_train):.1%}")
print(f"test accuracy: {full.score(X_test, y_test):.1%} ('nobody leaves': {baseline:.1%})")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:
depths = range(1, 16)
train_acc, test_acc = [], []
for d in depths:
tree = DecisionTreeClassifier(max_depth=d, random_state=631).fit(X_train, y_train)
train_acc.append(tree.score(X_train, y_train))
test_acc.append(tree.score(X_test, y_test))
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(depths, train_acc, "o-", color="#e07b39", label="training set")
ax.plot(depths, test_acc, "o-", color="#1f6f8b", label="test set")
ax.axhline(baseline, color="grey", ls=":", lw=1, label="'nobody leaves'")
ax.set_xlabel("maximum depth of the tree")
ax.set_ylabel("accuracy")
ax.legend(fontsize=8)
ax.grid(alpha=0.3)
plt.show()
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).
from sklearn.model_selection import cross_val_score
cv_auc = {}
for d in [1, 2, 3, 4, 5, 6, 8, 10, None]:
tree = DecisionTreeClassifier(max_depth=d, random_state=631)
cv_auc[str(d)] = cross_val_score(tree, X_train, y_train, cv=5, scoring="roc_auc").mean()
cv_auc = pd.Series(cv_auc).round(3)
print("5-fold cross-validated AUC by maximum depth:")
print(cv_auc.to_string())
cv_logit = cross_val_score(LogisticRegression(max_iter=1000), X_train, y_train, cv=5, scoring="roc_auc")
print(f"\nlogistic regression: {cv_logit.mean():.3f} (folds: {cv_logit.round(3)})")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:
tree4 = DecisionTreeClassifier(max_depth=4, random_state=631).fit(X_train, y_train)
print(f"test AUC, tree of depth 4: {roc_auc_score(y_test, tree4.predict_proba(X_test)[:, 1]):.3f}")
print(f"test AUC, logistic regression: {auc:.3f}")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 of churning. Sending the voucher is worth, on average,
which is positive when . 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:
from sklearn.metrics import accuracy_score
def profit(threshold):
send = p_test >= threshold
tp = (send & (y_test == 1)).sum() # vouchers to members who would have left: +50 SAR each
fp = (send & (y_test == 0)).sum() # vouchers to members who would have stayed: -10 SAR each
return 50 * tp - 10 * fp
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_acc = scan["accuracy"].idxmax()
best_profit = scan["profit"].idxmax()
print(f"highest accuracy: threshold {best_acc:.2f}, accuracy {scan.loc[best_acc, 'accuracy']:.1%}, profit {scan.loc[best_acc, 'profit']:,} SAR")
print(f"highest profit: threshold {best_profit:.2f}, accuracy {scan.loc[best_profit, 'accuracy']:.1%}, profit {scan.loc[best_profit, 'profit']:,} SAR")highest accuracy: threshold 0.65, accuracy 81.9%, profit 3,790 SAR
highest profit: threshold 0.17, accuracy 66.8%, profit 10,040 SAR
fig, ax1 = plt.subplots(figsize=(7, 3.6))
ax1.plot(scan.index, scan["profit"], color="#1f6f8b", lw=2.5)
ax1.set_xlabel("threshold: send the voucher when P(churn) is at least ...")
ax1.set_ylabel("campaign profit on the test set (SAR)", color="#1f6f8b")
ax1.axvline(1 / 6, color="#1f6f8b", ls="--", lw=1)
ax2 = ax1.twinx()
ax2.plot(scan.index, scan["accuracy"], color="#e07b39", lw=2)
ax2.set_ylabel("accuracy", color="#e07b39")
ax2.axvline(best_acc, color="#e07b39", ls="--", lw=1)
ax1.grid(alpha=0.3)
plt.show()
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:
policies = {
"send to nobody": 0,
"send to everybody": profit(0),
"model, threshold 0.65 (highest accuracy)": profit(best_acc),
"model, threshold 0.5 (the default)": profit(0.5),
"model, threshold 1/6 (break-even)": profit(1 / 6),
}
send = p_test >= 1 / 6
print(pd.Series(policies, name="profit (SAR)").to_string())
print(f"\nat 1/6: {send.sum()} vouchers, {(send & (y_test == 1)).sum()} of {y_test.sum()} churners reached, "
f"precision {precision_score(y_test, send):.1%}, recall {recall_score(y_test, send):.1%}, accuracy {accuracy_score(y_test, send):.1%}")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 for a true positive and cost per action, act when , 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.