Sub topic 7
Predictive segments: propensity and churn
This chapter assumes you can read Python and pandas, you know what a train/test split is, and you have met logistic regression or tree models. You should also know RFM features from the earlier chapter on feature engineering. No new maths is needed.
Why predict instead of describe
A cluster segment describes customers as they look now: "frequent, high spend" or "dormant". It does not say what they will do next. A predictive segment groups customers by an estimated probability of a future event. Two events matter most in personalisation:
- Propensity: the probability that a customer takes a wanted action, such as buying, upgrading or opening an app, within a set period.
- Churn: the probability that a customer stops being active within a set period.
Both are binary classification problems. The model's output is a score between 0 and 1. The segment is a rule applied to that score, such as "top 10% by purchase propensity" or "churn risk above 0.6". The decisioning chapter later uses these segments to choose content.
Define the target before the model
Most predictive segments fail at this step, not in the algorithm. You need three dates:
- A snapshot date: the moment you pretend to be standing at.
- A feature window: the history before the snapshot that you compute features from.
- A label window: the period after the snapshot in which you check whether the event happened.
Choose window lengths from the business cycle. A grocery retailer can use a 7-day label window. A car insurer needs a year. If the window is too short, the label is mostly noise. If it is too long, the score is stale by the time you use it.
Defining churn
Churn is easy to define when customers cancel a subscription. This is contractual churn, and the cancellation date is the label. Retail, media and apps have non-contractual churn: nobody announces they have left. You must pick a rule, for example "no purchase in 90 days". Base that threshold on the data. Look at the distribution of gaps between purchases and pick a gap that most returning customers do not exceed. A fixed rule that is too short labels ordinary slow buyers as churned, and you then send them win-back discounts they did not need.
Build a propensity model
The example below builds synthetic monthly snapshots, trains on the first two months, and tests on the third. It scales the features and fits a logistic regression. Logistic regression is a sensible first model because it is fast, its coefficients are explainable, and its probabilities are usually reasonably calibrated.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(7)
n = 6000
df = pd.DataFrame({
"snapshot_month": rng.integers(1, 4, size=n), # 1, 2 or 3
"recency_days": rng.exponential(30, size=n).round(),
"frequency_90d": rng.poisson(4, size=n),
"email_opens_30d": rng.poisson(3, size=n),
})
df["monetary_90d"] = df["frequency_90d"] * rng.uniform(20, 60, size=n)
# Synthetic "truth": recent, frequent, engaged customers buy more often.
logit = (-0.5 - 0.04 * df["recency_days"]
+ 0.25 * df["frequency_90d"] + 0.10 * df["email_opens_30d"])
df["bought_next_30d"] = rng.random(n) < 1 / (1 + np.exp(-logit))
features = ["recency_days", "frequency_90d", "monetary_90d", "email_opens_30d"]
# Time-based split: train on earlier snapshots, test on the latest one.
train = df[df["snapshot_month"] <= 2]
test = df[df["snapshot_month"] == 3].copy()
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(train[features], train["bought_next_30d"])
test["score"] = model.predict_proba(test[features])[:, 1]
print("AUC:", round(roc_auc_score(test["bought_next_30d"], test["score"]), 3))
# Turn scores into segments: top 10%, next 40%, bottom 50%.
test["tier"] = pd.qcut(test["score"].rank(method="first"),
[0, 0.5, 0.9, 1.0], labels=["low", "medium", "high"])
print("Base rate:", round(test["bought_next_30d"].mean(), 3))
print(test.groupby("tier", observed=True)["bought_next_30d"].agg(["mean", "size"]))The final table is the check that matters. The observed purchase rate should rise from "low" to "high". If it does not, the score is not ordering customers usefully, whatever the AUC says.
Evaluate for the decision you will make
Pick metrics that match how the score will be used.
| Metric | What it tells you | When to use it |
|---|---|---|
| AUC (area under the ROC curve) | How well the score ranks buyers above non-buyers, from 0.5 (random) to 1.0 | A quick overall comparison between models |
| Precision at k | The share of true events among the top k customers | You can only contact a fixed number of people |
| Lift by decile | Each score decile's event rate divided by the base rate | Showing business teams why the segment is worth targeting |
| Calibration | Whether customers scored 0.3 really convert about 30% of the time | You multiply the score by a value or cost |
Calibration matters more than people expect. Ranking is enough for "contact the top 10%". It is not enough for "send the offer if probability times margin exceeds the discount cost", because that arithmetic uses the number itself. Class weights or resampling used to handle rare events usually distort probabilities, so recalibrate afterwards (scikit-learn's CalibratedClassifierCV) or avoid those techniques.
Turn scores into segments
A score is not yet a segment. Three common ways to cut it:
- Quantile tiers, as in the code above. The tier sizes stay stable, which suits capacity-limited channels like call centres.
- Fixed thresholds, such as score above 0.6. The size of the segment moves as the model or the customer base changes, so monitor it.
- Value-weighted rules, such as expected value above cost. These need calibrated probabilities.
Keep the segment definition in versioned configuration, not in a notebook. Record the model version, the threshold and the scoring date with each customer's segment, so you can explain later why a customer received a message.
Common errors
Most problems with predictive segments come from a short list of causes.
Target leakage. A feature contains information from after the snapshot. Examples are "support tickets this month" when the month includes the label window, or a "cancellation requested" flag when predicting churn. Leakage produces excellent test scores and useless production scores. For each feature, ask whether you would have known this value on the snapshot date.
Random splits on time-ordered data. A random split puts later behaviour in the training set and earlier behaviour in the test set. Split by snapshot date, as the code does. Also keep one customer's rows from appearing on both sides if rows are repeated per customer.
Predicting the wrong thing. A high propensity score finds customers who are likely to buy. Many of them would buy without a message. Likewise a high churn score finds customers likely to leave, but a discount may not change their mind. Scores rank risk, not persuadability. Whether a message changes behaviour is a causal question, handled by the holdout testing chapters and by uplift modelling.
Ignoring base rates. If 2% of customers churn, a model that predicts "no churn" for everyone is 98% accurate. Do not use accuracy. Use precision at k, lift and AUC.
Treating the score as permanent. Behaviour shifts with seasons, promotions and product changes. A model trained on last spring's snapshots will drift. The segment operations chapter covers refresh schedules and drift checks.
Using consent-restricted data. Features built from data the customer has not agreed to have used for profiling can make the whole model non-compliant. Check each feature against the consent flags from the earlier privacy chapter before training.
Propensity versus churn in practice
The two segment types are built the same way but used differently. Propensity segments usually drive acquisition and cross-sell content: promote the next product to customers likely to want it. Churn segments drive retention content: service reminders, loyalty benefits or a win-back message. Customers can sit in both. A high-value customer with high churn risk is a strong candidate for human outreach. A low-value customer with high churn risk may not justify any spend. That is why the decisioning chapter combines these scores with value and rules instead of using one score alone.
Exercise
Your churn model reaches an AUC of 0.97 on the test set, but in production it performs barely better than random. The training data used the feature "days since last contact with the cancellation team". Explain the likely cause and how you would fix it.
Show answer
This is target leakage. Customers who are about to cancel often contact the cancellation team shortly before leaving, so the feature reveals the outcome. It is only known after the customer has already started to churn, so it would not be available at scoring time. Remove the feature, or recompute every feature strictly from data before the snapshot date. Then retrain with a time-based split and check that the AUC drops to a believable level.
Exercise
A retailer wants to send a 20% discount to customers whose purchase probability, multiplied by a £15 margin, exceeds the £2 cost of the discount. The model was trained with class weights to handle a 3% purchase rate. Why is this a problem, and what two options do you have?
Show answer
Class weights distort predicted probabilities, so the score is no longer a true probability and the margin calculation gives the wrong answer. One option is to recalibrate the scores on a held-out set, for example with CalibratedClassifierCV. The other is to train without class weights and rely on the ranking metrics, and keep the probabilities honest.