Lesson 12 of 12 · In Practice
Project: Customer Churn Prediction
Predict customer churn in Python step by step: a stratified split, baselines, logistic regression vs a random forest, class weights and a cost-based threshold.
- 18 min read
- Intermediate
- Reviewed
- Frame churn prediction as a business problem and choose metrics that match its costs
- Build a pipeline that scales numbers and one-hot encodes categories
- Compare a baseline, logistic regression and a random forest without touching the test set
- Handle the imbalance with class weights and a decision threshold chosen from costs
- Test the final model once, explain it in plain words and plan how to monitor it
The task
A broadband company loses customers every month, and each one takes their future payments with them. The retention team can make an offer, such as a discount, to customers who seem about to leave, but it can't call everybody. They want a model that answers one question every month: which customers are likely to cancel?
As Learning From Labels advised, define the label before collecting any data: churned = 1 if the customer cancelled within 90 days of the day the data was taken, and every feature must be known on that day. It's a classification problem (Regression vs Classification), and we want probabilities, not just yes or no.
Accuracy is no help: if one customer in five leaves, predicting "stays" for everyone is right 80% of the time and saves nobody. Two other numbers match the business:
- Recall: of the customers who were going to leave, the share who got an offer. Every churner we miss is lost revenue.
- Precision: of the customers who got an offer, the share who were really going to leave. Every other offer is a discount given away for nothing.
The team puts a price on both mistakes: an offer costs 50, and a customer who leaves without an offer costs 250 in lost profit. A missed churner costs five times as much as a wasted offer, so it's worth accepting quite a few wasted offers to catch more churners. To keep the sums simple, assume an offer always keeps a customer who was about to leave. The total cost of any plan is then 50 × offers made + 250 × churners missed.
Step 1: build and explore the data
There are no data files in this course, so the program below creates 3,000 realistic customers with a seeded NumPy random generator. Everyone gets the same data, and you can see the hidden rule that decides who leaves. Each customer has five features: tenure (months as a customer), monthly charges, support calls in the last 3 months, late payments in the last 12 months, and the contract type (monthly, one year or two year).
import numpy as np
# ---- 3,000 customers of a broadband company ----
rng = np.random.RandomState(0)
n = 3000
tenure = rng.randint(1, 73, size=n) # months as a customer
charges = rng.uniform(20, 120, size=n).round(2) # monthly bill
calls = rng.poisson(1.0, size=n) # support calls in the last 3 months
late = rng.poisson(0.4, size=n) # late payments in the last 12 months
contract = rng.choice(["monthly", "one year", "two year"], size=n, p=[0.55, 0.25, 0.2])
# The hidden rule: a weighted sum, turned into a probability of leaving
z = (-1.6 - 0.035 * tenure + 0.015 * (charges - 70) + 0.4 * calls + 0.6 * late
+ 1.3 * (contract == "monthly") - 1.0 * (contract == "two year"))
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-z))).astype(int) # 1 = cancelled within 90 days
X = np.array([tenure, charges, calls, late, contract], dtype=object).T
# ---- Look before modelling ----
print(f"{n} customers, {y.sum()} churned ({y.mean():.1%})")
print("\nFirst 3 customers: tenure, charges, calls, late payments, contract")
for row, label in zip(X[:3], y[:3]):
print(" ", row.tolist(), "->", "churned" if label else "stayed")
print("\nChurn rate by contract:")
for kind in ["monthly", "one year", "two year"]:
group = contract == kind
print(f" {kind:<9} {y[group].mean():4.0%} ({group.sum()} customers)")
print("\nAverage for customers who stayed vs churned:")
for name, values in [("tenure (months)", tenure), ("monthly charges", charges),
("support calls", calls), ("late payments", late)]:
print(f" {name:<16} {values[y == 0].mean():6.2f} vs {values[y == 1].mean():6.2f}")3000 customers, 679 churned (22.6%) First 3 customers: tenure, charges, calls, late payments, contract [45, 87.63, 5, 1, 'monthly'] -> stayed [48, 104.02, 1, 0, 'monthly'] -> churned [65, 93.43, 1, 0, 'two year'] -> stayed Churn rate by contract: monthly 32% (1702 customers) one year 14% (709 customers) two year 6% (589 customers) Average for customers who stayed vs churned: tenure (months) 38.91 vs 26.00 monthly charges 68.74 vs 78.42 support calls 0.93 vs 1.18 late payments 0.35 vs 0.57
Three things stand out:
- The classes are imbalanced: 679 of the 3,000 customers (22.6%) churned.
- The contract matters a lot: 32% of monthly customers left, against 14% on one-year and 6% on two-year contracts.
- Churners differ on average: they had been customers for 26 months instead of 39, paid more (78.42 against 68.74 a month), and made more support calls and late payments. But averages hide a lot of overlap: the second customer had stayed for four years and still left, while the first made 5 support calls and stayed. No model will be perfect.
Step 2: split, then compare models
The next program follows the recipe from Choosing an Algorithm:
- Split the customers into 75% for training and 25% for testing, with
stratify=y. The test set then stays locked away until the very end. - Prepare the features in a pipeline: a
ColumnTransformersends the four number columns toStandardScalerand the contract toOneHotEncoder, which turns its text into three 0/1 columns, because scikit-learn models need numbers (Tree-Based Models). Inside the pipeline, both are fitted on training data only. - Compare a dummy baseline (Baselines), logistic regression (Linear Models) and a random forest (Tree-Based Models), where
min_samples_leaf=5stops the trees memorising single customers. All three are scored on out-of-fold predictions fromcross_val_predict, as in Handling Imbalanced Classes: each training customer is scored by a model trained on the other four folds.
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.RandomState(0) # the same 3,000 customers as in Step 1
n = 3000
tenure, charges = rng.randint(1, 73, n), rng.uniform(20, 120, n).round(2)
calls, late = rng.poisson(1.0, n), rng.poisson(0.4, n)
contract = rng.choice(["monthly", "one year", "two year"], n, p=[0.55, 0.25, 0.2])
z = (-1.6 - 0.035 * tenure + 0.015 * (charges - 70) + 0.4 * calls + 0.6 * late
+ 1.3 * (contract == "monthly") - 1.0 * (contract == "two year"))
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-z))).astype(int)
X = np.array([tenure, charges, calls, late, contract], dtype=object).T
# ---- Split once, keeping the same share of churners on both sides ----
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
print(f"churn rate: training {y_train.mean():.3f}, test {y_test.mean():.3f}")
# ---- Scale the four numbers, one-hot encode the contract ----
prep = ColumnTransformer([("numbers", StandardScaler(), [0, 1, 2, 3]),
("contract", OneHotEncoder(), [4])])
models = {
"always churn (baseline)": DummyClassifier(strategy="constant", constant=1),
"logistic regression": make_pipeline(prep, LogisticRegression()),
"random forest": make_pipeline(prep, RandomForestClassifier(min_samples_leaf=5, random_state=0)),
}
print(f"\n{'threshold 0.5':<24} precision recall F1 ROC AUC")
predictions = {}
for name, model in models.items():
# Out-of-fold: each training customer is scored by a model that never saw them
p = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
predictions[name] = pred = (p >= 0.5).astype(int)
print(f"{name:<24} {precision_score(y_train, pred):9.2f} {recall_score(y_train, pred):7.2f} "
f"{f1_score(y_train, pred):5.2f} {roc_auc_score(y_train, p):8.3f}")
for name in ["logistic regression", "random forest"]:
(tn, fp), (fn, tp) = confusion_matrix(y_train, predictions[name])
print(f"\n{name:<20}{'predicted stay':>16}{'predicted churn':>17}")
print(f"{' really stayed':<20}{tn:>16}{fp:>17}")
print(f"{' really churned':<20}{fn:>16}{tp:>17}")churn rate: training 0.226, test 0.227 threshold 0.5 precision recall F1 ROC AUC always churn (baseline) 0.23 1.00 0.37 0.500 logistic regression 0.65 0.31 0.42 0.788 random forest 0.61 0.30 0.40 0.757 logistic regression predicted stay predicted churn really stayed 1656 85 really churned 352 157 random forest predicted stay predicted churn really stayed 1645 96 really churned 357 152
The split. With stratify=y, both parts keep the real share of churners: 0.226 in training and 0.227 in the test set. Without it, luck decides how many churners land among the 750 test customers, and precision, recall and cost move with them. The test set must keep the real mix, so that its results say what will happen in real use.
The models. The baseline, always predicting "churn", finds every churner, but its precision is only 0.23. Its F1 of 0.37 is the score to beat, and its ROC AUC of 0.500 is the score of guessing. Logistic regression ranks customers best (ROC AUC 0.788 against 0.757 for the forest) and wins on every other column too. That's no surprise here: the hidden rule is a weighted sum, exactly the shape logistic regression assumes, while the forest has to build it from many small steps. Real churn data is messier, which is why you compare instead of assuming.
The confusion matrices show the real problem. At the default threshold of 0.5, logistic regression catches 157 churners and misses 352; the forest catches 152 and misses 357. Both miss more than two out of every three customers who leave. The models aren't useless (their ROC AUC is well above 0.5); the threshold is wrong for this business.
Step 3: handle the imbalance with costs
Two fixes from Handling Imbalanced Classes make a model flag more customers: train it with class_weight="balanced", or keep it and lower the threshold. The costs tell us how far to go. As in Probabilistic Models, an offer is worth making when its expected saving is bigger than its cost:
expected saving of an offer = P(churn) × 250
make the offer when P(churn) × 250 > 50
which means P(churn) > 50 ÷ 250 = 0.2The program below tests this rule on the out-of-fold probabilities of the training customers, so the test set stays untouched:
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.RandomState(0) # the same 3,000 customers as in Step 1
n = 3000
tenure, charges = rng.randint(1, 73, n), rng.uniform(20, 120, n).round(2)
calls, late = rng.poisson(1.0, n), rng.poisson(0.4, n)
contract = rng.choice(["monthly", "one year", "two year"], n, p=[0.55, 0.25, 0.2])
z = (-1.6 - 0.035 * tenure + 0.015 * (charges - 70) + 0.4 * calls + 0.6 * late
+ 1.3 * (contract == "monthly") - 1.0 * (contract == "two year"))
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-z))).astype(int)
X = np.array([tenure, charges, calls, late, contract], dtype=object).T
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
prep = ColumnTransformer([("numbers", StandardScaler(), [0, 1, 2, 3]),
("contract", OneHotEncoder(), [4])])
OFFER, MISSED = 50, 250 # cost of one offer, cost of one missed churner
def cost(offer): # offer: True = this customer gets an offer
return OFFER * offer.sum() + MISSED * (y_train[~offer] == 1).sum()
def report(name, offer):
offers, missed = offer.sum(), (y_train[~offer] == 1).sum()
precision = y_train[offer].sum() / offers if offers else 0
recall = 1 - missed / y_train.sum()
print(f"{name:<24}{offers:6d}{missed:8d}{precision:11.2f}{recall:8.2f}{cost(offer):12,d}")
plain = make_pipeline(prep, LogisticRegression())
balanced = make_pipeline(prep, LogisticRegression(class_weight="balanced"))
p_plain = cross_val_predict(plain, X_train, y_train, cv=5, method="predict_proba")[:, 1]
p_balanced = cross_val_predict(balanced, X_train, y_train, cv=5, method="predict_proba")[:, 1]
nobody = np.zeros(len(y_train), dtype=bool)
print(f"{'':<24}{'offers':>6}{'missed':>8}{'precision':>11}{'recall':>8}{'total cost':>12}")
report("offer nobody", nobody)
report("offer everybody", ~nobody)
for t in [0.5, 0.2, 0.1]:
report(f"plain, threshold {t}", p_plain >= t)
report("balanced, threshold 0.5", p_balanced >= 0.5)
report("balanced, threshold 0.2", p_balanced >= 0.2)
best = min(np.arange(0.05, 0.95, 0.01), key=lambda t: cost(p_plain >= t))
print(f"\ncheapest threshold for the plain model: {best:.2f}")
print(f"average P(churn): plain {p_plain.mean():.3f}, balanced {p_balanced.mean():.3f}, "
f"real churn rate {y_train.mean():.3f}")offers missed precision recall total cost offer nobody 0 509 0.00 0.00 127,250 offer everybody 2250 0 0.23 1.00 112,500 plain, threshold 0.5 242 352 0.65 0.31 100,100 plain, threshold 0.2 1002 114 0.39 0.78 78,600 plain, threshold 0.1 1524 38 0.31 0.93 85,700 balanced, threshold 0.5 887 136 0.42 0.73 78,350 balanced, threshold 0.2 1746 16 0.28 0.97 91,300 cheapest threshold for the plain model: 0.19 average P(churn): plain 0.226, balanced 0.429, real churn rate 0.226
- Simple strategies are expensive. Offering nobody costs 127,250 in lost customers; offering everybody costs 112,500 in discounts. A model has to beat the cheaper of the two.
- The default threshold wastes the model. At 0.5, logistic regression costs 100,100, only a little better than offering everybody, because it misses 352 churners. At 0.2 the cost falls to 78,600. At 0.1 it rises again, to 85,700, because now too many offers are wasted. Trying every threshold from 0.05 to 0.94 finds the cheapest at 0.19, right next to the rule's 0.2.
- Class weights turn the same dial. The balanced model at the default threshold lands in almost the same place: 887 offers, 136 missed churners and a cost of 78,350.
- But class weights bend the probabilities. The balanced model's average P(churn) is 0.429, although only 0.226 of customers churn; the plain model's average, 0.226, is honest. Feeding the inflated numbers into the 0.2 rule sends 1,746 offers and costs 91,300. Use a cost rule only with honest probabilities, or measure the costs as above.
The decision: keep the plain logistic regression, and make an offer when P(churn) is at least 0.2. Its probabilities mean what they say, so the team can also use them to rank customers and estimate expected savings, and the threshold comes from a rule anyone can check, not from a search that might fit the noise.
Step 4: test once, then explain the model
Every choice is now made: the features, the model and the threshold. Only now does the test set come out, once. The same program then asks what the model has learned:
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.RandomState(0) # the same 3,000 customers as in Step 1
n = 3000
tenure, charges = rng.randint(1, 73, n), rng.uniform(20, 120, n).round(2)
calls, late = rng.poisson(1.0, n), rng.poisson(0.4, n)
contract = rng.choice(["monthly", "one year", "two year"], n, p=[0.55, 0.25, 0.2])
z = (-1.6 - 0.035 * tenure + 0.015 * (charges - 70) + 0.4 * calls + 0.6 * late
+ 1.3 * (contract == "monthly") - 1.0 * (contract == "two year"))
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-z))).astype(int)
X = np.array([tenure, charges, calls, late, contract], dtype=object).T
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
prep = ColumnTransformer([("numbers", StandardScaler(), [0, 1, 2, 3]),
("contract", OneHotEncoder(), [4])])
# ---- The final model: trained on all training customers, tested once ----
final = make_pipeline(prep, LogisticRegression()).fit(X_train, y_train)
p_test = final.predict_proba(X_test)[:, 1]
offer = p_test >= 0.2 # the cost rule
(tn, fp), (fn, tp) = confusion_matrix(y_test, offer)
print(f"test set: precision {precision_score(y_test, offer):.2f}, recall {recall_score(y_test, offer):.2f}, "
f"F1 {f1_score(y_test, offer):.2f}, ROC AUC {roc_auc_score(y_test, p_test):.3f}")
print(f"{tp + fp} offers: {tp} to churners, {fp} wasted; {fn} churners missed, {tn} correctly left alone")
print(f"total cost {50 * (tp + fp) + 250 * fn:,} (offer everybody {50 * len(y_test):,}, "
f"offer nobody {250 * y_test.sum():,})")
# ---- What did it learn? ----
columns = ["tenure", "monthly charges", "support calls", "late payments", "contract"]
names = columns[:4] + ["contract: monthly", "contract: one year", "contract: two year"]
weights = final[-1].coef_[0] # the logistic regression step
print("\nCoefficients after scaling (+ pushes towards leaving):")
for i in np.argsort(-abs(weights)):
print(f" {names[i]:<19} {weights[i]:+.2f}")
# Shuffle one column at a time and measure how much ROC AUC drops
result = permutation_importance(final, X_test, y_test, scoring="roc_auc", n_repeats=10, random_state=0)
print("\nPermutation importance (drop in ROC AUC):")
for i in np.argsort(-result.importances_mean):
print(f" {columns[i]:<16} {result.importances_mean[i]:.3f}")test set: precision 0.41, recall 0.81, F1 0.55, ROC AUC 0.806 331 offers: 137 to churners, 194 wasted; 33 churners missed, 386 correctly left alone total cost 24,800 (offer everybody 37,500, offer nobody 42,500) Coefficients after scaling (+ pushes towards leaving): contract: monthly +1.10 contract: two year -0.98 tenure -0.73 monthly charges +0.41 late payments +0.33 support calls +0.30 contract: one year -0.13 Permutation importance (drop in ROC AUC): contract 0.135 tenure 0.110 monthly charges 0.030 late payments 0.020 support calls 0.015
The test. On 750 customers the model has never seen, precision is 0.41 and recall 0.81, close to the out-of-fold estimates at 0.2 (0.39 and 0.78), and ROC AUC is 0.806. That agreement is the reward for keeping the test set locked away: the choices hold up on new customers. The team would send 331 offers, reach 137 churners and miss 33, for a total cost of 24,800, against 37,500 for offering everybody and 42,500 for offering nobody.
The coefficients. After scaling, each coefficient shows the effect of a typical change in its feature (Linear Models), and a plus sign pushes towards leaving. The contract matters most: a monthly contract pushes strongly towards leaving (+1.10) and a two-year contract towards staying (−0.98). Tenure comes next (−0.73): the longer someone has been a customer, the more likely they are to stay. Monthly charges, late payments and support calls push towards leaving more gently (+0.30 to +0.41). That matches the hidden rule in the generator: the same directions, with the contract and tenure as the strongest effects.
Permutation importance asks a question that works for any model: if one column is shuffled so that it carries no information, how much worse does the model get? Shuffling the contract drops ROC AUC by 0.135 and tenure by 0.110; the other three cost 0.015 to 0.030 each. It tells the same story, treats the contract as one column instead of three, and is measured on held-out data, so it is a more reliable guide than the impurity-based importances in Tree-Based Models. Both describe what the model uses, not what causes churn: monthly customers may leave more because they were never very committed, so pushing them onto long contracts might not keep them. An idea like that needs a real experiment.
Step 5: choose, ship and monitor
The final model is plain logistic regression in a pipeline, making an offer when P(churn) is at least 0.2. It ranked customers best in cross-validation, it beat both simple strategies on cost, its probabilities are honest, and its seven weights and one intercept can be read out to the retention team. The forest added nothing here, so the simpler model wins, as Choosing an Algorithm recommends. A model's real work starts when it goes live, so plan what to watch:
- Inputs. Compare each month's customers with the training data: the share on monthly contracts, the average bill, the number of support calls. A price rise or a new product changes them, and the model only knows the old world (distribution shift, from Generalisation).
- Outputs. Track the share of customers flagged and their average P(churn). A sudden jump usually means a broken data feed, not a wave of cancellations.
- Outcomes. The labels arrive 90 days later. Then measure recall, precision and total cost for that month's customers, and check that the average P(churn) still matches the real churn rate.
- A control group. Hold back a small random group of flagged customers who get no offer. Without it, nobody can tell whether the offers work, and customers kept by an offer look exactly like customers who never meant to leave.
- Retraining. Retrain on recent data on a schedule, and switch only if the new model beats the old one on the same recent test data.
Next steps for the project: richer features (changes in usage, complaints, price rises), tuning with GridSearchCV, gradient boosting from the XGBoost and Gradient Boosting course, and a cost per customer, because losing a big bill costs more than losing a small one. The Feature Engineering, Model Evaluation and Model Monitoring courses take each step further.
Common mistakes
Practice
Apply the cost rule by hand: work out the threshold from the two costs, then compare the total cost of the default threshold, 0.5, with the rule's threshold.
probs = [0.82, 0.15, 0.35, 0.05, 0.60, 0.22, 0.12, 0.45, 0.28, 0.09] # P(churn)
churned = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] # 1 = really left
OFFER, MISSED = 40, 200 # cost of one offer, cost of one missed churner
# 1. The cost rule: make an offer when P(churn) is above OFFER / MISSED.
rule = 0
print(f"rule threshold: {rule:.2f}")
# 2. For each threshold, offer every customer whose probability is >= the threshold.
# Count the offers and the churners who got no offer, then add up the cost:
# OFFER for each offer, MISSED for each missed churner.
for threshold in [0.5, rule]:
offers, missed, cost = 0, 0, 0
print(f"threshold {threshold:.2f}: {offers} offers, {missed} missed, cost {cost}")
An offer costs 50 and a churner you miss costs 250. The model's probabilities are honest. Which customers should get an offer?
Summary
- Start from the business: define the label precisely, and put a cost on each kind of mistake.
- Split once with
stratify=yand lock the test set away. Prepare features in a pipeline (ColumnTransformer), and compare a baseline and models on out-of-fold predictions. - Choose the threshold from costs: offer when P(churn) × the cost of a miss beats the cost of an offer. Class weights move the same trade-off but inflate the probabilities.
- Explain the model with scaled coefficients and permutation importance, then monitor its inputs, outputs and outcomes in production, with a control group.
This is the last lesson of the course.
Finished reading? Tick it off to track your progress.