Classification and evaluation
Yes or no? Fraud or not? Classification drives many business decisions — and choosing how to evaluate it is as important as choosing the model.
Learning objectives
- Explain logistic regression and predicted probabilities
- Train and read a decision tree
- Interpret a confusion matrix, precision, recall, F1 and AUC
- Choose a threshold based on business costs
- Handle imbalanced classes
- Plot precision and recall across thresholds
- Check whether predicted probabilities are calibrated
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
"tenure_months": rng.integers(1, 60, n),
"monthly_spend": rng.normal(40, 15, n).clip(5, 120).round(2),
"support_tickets": rng.poisson(1.2, n),
"on_promo": rng.integers(0, 2, n),
"region": rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
- 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
+ rng.normal(0, 40, n)).round(2)
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
features = ["tenure_months", "monthly_spend", "support_tickets", "on_promo"]
X, y = customers[features], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)3.1 Logistic regression
Despite its name, logistic regression is a classification model. It combines features in a weighted sum, then squashes the result into a probability between 0 and 1. By default, probabilities above 0.5 become "yes".
proba = model.predict_proba(X_test)[:, 1] # probability of churn for each customer
print(proba[:5].round(2))
print(model.predict(X_test)[:5]) # the same five as yes/no labels
The probabilities are worth far more than the labels. A customer at 0.52 and one at 0.97 both get the label 1, but you would treat them very differently. Keep the probabilities and decide the cut-off yourself (3.4).
3.2 Decision trees
A decision tree learns a flowchart of yes/no questions ("tenure under 8 months?", "more than 2 tickets?"). Trees are intuitive and capture non-linear patterns and interactions, but a single deep tree overfits easily (Module 4).
from sklearn.tree import DecisionTreeClassifier, export_text
tree = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print(export_text(tree, feature_names=features))
print("Tree accuracy:", round(tree.score(X_test, y_test), 3))
Read the printout from the top: each indented line is a question, and each class: line is the answer for customers who reach that leaf. Try changing max_depth to 2 or 5 and running the cell again to see the flowchart shrink and grow.
3.3 Beyond accuracy: the confusion matrix
from sklearn.metrics import confusion_matrix, classification_report
pred = model.predict(X_test)
print(confusion_matrix(y_test, pred)) # rows = actual, columns = predicted
print(classification_report(y_test, pred, digits=3))
| Metric | Question |
|---|---|
| Precision | Of customers we flagged as churners, how many actually churned? |
| Recall | Of customers who churned, how many did we flag? |
| F1 | A single score balancing precision and recall |
| ROC-AUC | How well the model ranks positives above negatives, across all thresholds (0.5 = random, 1 = perfect) |
3.4 Choosing the threshold is a business decision
0.5 is just a default. If a retention call is cheap and losing a customer is expensive, flag more people (lower threshold, higher recall). If the team can only make 50 calls a week, flag only the most likely (higher threshold, higher precision).
from sklearn.metrics import precision_score, recall_score, roc_auc_score
print("ROC-AUC:", round(roc_auc_score(y_test, proba), 3))
for t in [0.3, 0.5, 0.7]:
p = (proba >= t).astype(int)
print(f"threshold {t}: precision {precision_score(y_test, p):.2f} "
f"recall {recall_score(y_test, p):.2f} flagged {p.sum()}")
3.5 Imbalanced classes
When the positive class is rare (fraud, rare diseases), accuracy is misleading. Use precision, recall and AUC; stratify splits; consider class_weight="balanced"; and evaluate at the threshold you'll actually use.
class_weight="balanced" tells the model that mistakes on the rarer class count for more. It doesn't make the model smarter; it shifts where the 0.5 line falls. See the effect:
Python · the effect of class weightsweighted = LogisticRegression(max_iter=1000, class_weight="balanced").fit(X_train, y_train)
for name, m in [("default", model), ("balanced", weighted)]:
p = m.predict(X_test)
print(f"{name:9} precision {precision_score(y_test, p):.2f} recall {recall_score(y_test, p):.2f} "
f"AUC {roc_auc_score(y_test, m.predict_proba(X_test)[:, 1]):.3f}")
Precision and recall trade places while AUC barely moves: the ranking of customers is the same, only the cut-off has changed. You could get the same effect by choosing a different threshold yourself.
3.6 See the whole trade-off
Three thresholds give three snapshots. Plotting precision and recall for every threshold shows the whole trade-off at once, which is far easier to discuss with the people who will act on the predictions.
Python · precision and recall at every thresholdimport matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
prec, rec, thresholds = precision_recall_curve(y_test, proba)
plt.plot(thresholds, prec[:-1], label="precision")
plt.plot(thresholds, rec[:-1], label="recall")
plt.xlabel("Threshold"); plt.ylabel("Score"); plt.legend()
plt.title("Raise the threshold: precision up, recall down")
plt.show()
3.7 Can you trust the probabilities?
If the model says "70% chance of churn" for a group of customers, about 70% of them should actually churn. A model that does this is well calibrated. It matters whenever the number itself is used — for expected revenue, risk scores or pricing — and not just the ranking.
Python · a simple calibration checkcal = pd.DataFrame({"predicted": proba, "actual": y_test.values})
cal["band"] = pd.cut(cal["predicted"], [0, 0.2, 0.4, 0.6, 0.8, 1.0])
print(cal.groupby("band", observed=True).agg(avg_predicted=("predicted", "mean"),
actual_rate=("actual", "mean"),
customers=("actual", "count")).round(2))
In each band the average predicted probability should be close to the actual churn rate. Logistic regression is usually well calibrated; tree ensembles and models trained with class weights often are not, and may need recalibrating (scikit-learn's CalibratedClassifierCV).
A missed churner costs £200; a retention call costs £10. Using proba, find the threshold between 0.05 and 0.95 that minimises total cost on the test set.
Your turn# Write your code here, then press RunShow a solution
best = None
for t in np.arange(0.05, 0.96, 0.05):
p = (proba >= t).astype(int)
missed = ((p == 0) & (y_test == 1)).sum()
calls = p.sum()
cost = missed * 200 + calls * 10
if best is None or cost < best[1]:
best = (float(round(t, 2)), int(cost))
print("Best threshold and cost:", best)
# Calls are so cheap compared with a lost customer that it pays to call almost everyone.The team can make 50 calls. Pick the 50 test customers with the highest churn probability. What share of them actually churned (precision in the top 50), and how does that compare with the overall churn rate?
Your turnranked = pd.DataFrame({"proba": proba, "actual": y_test.values})
# Sort, take the top 50, then press RunShow a solution
ranked = pd.DataFrame({"proba": proba, "actual": y_test.values}).sort_values("proba", ascending=False)
top50 = ranked.head(50)
print("Churn rate in top 50:", top50["actual"].mean().round(2))
print("Overall churn rate: ", ranked["actual"].mean().round(2))
# The gap between the two numbers is the value the model adds to those 50 calls.Key takeaways
- Logistic regression outputs probabilities; 0.5 is just a default threshold.
- Decision trees are readable flowcharts that can overfit.
- Precision: of flagged, how many right? Recall: of real, how many caught?
- Thresholds are business decisions — use costs and capacity.
- With rare classes, ignore raw accuracy.
- Class weights move the cut-off; they don't improve the ranking.
- Calibrated probabilities match reality: of customers scored 70%, about 70% churn.