Skip to content

Capstone 5 — Customer segmentation

The marketing lead of the subscription service plans the 2025 retention campaigns. The team can run 3 to 6 campaigns. She asks you:

  • Which groups of customers do we have, by how they buy and how they use their account?
  • How large is each group, and how often does each group churn?
  • What should we say to each group?
  • Can we trust the groups, or would a different sample give different ones?

Module 39 segmented the same customers on five account columns with k-means. This job uses different inputs and asks harder questions. You join two years of orders from data/sales.csv to the customer table, build RFM features, choose the transforms on purpose, check the number of segments with several criteria, compare two methods and test whether the segments hold up.

RFM describes a customer’s buying with three numbers: recency (days since the last order), frequency (how often the customer orders) and monetary value (how much the customer spends). Marketing teams use RFM because each number suggests an action: win back the lapsed, reward the frequent, look after the big spenders.

Deliverables:

  1. output/segments.csv: one row per customer (all 5,000) with customer_id, segment and churned, so the team can drop customers who already left.
  2. A profile table: size, medians of the features and churn rate per segment.
  3. A segment name and a one-line action per segment for the marketing team.
  4. A short validation: how stable the segments are, and whether churn differs between them.

Skills practiced: joins and groupby aggregation (24. pandas fundamentals, 25. pandas advanced), dates and data checks (26. Data cleaning), skew and distributions (27. Exploratory data analysis), charts (28. Visualization), the chi-square test and Cramér’s V (29. Statistics and probability), transforms and scaling (33. Feature engineering), pipelines (34. The scikit-learn workflow), and k-means, Gaussian mixtures, Ward clustering, PCA and the adjusted Rand index (39. Unsupervised learning).

Two files, described in the data dictionary:

File Rows Columns used
data/customers.csv 5,000 customers customer_id, signup_date, plan, contract, tenure_months, monthly_charges, logins_last_30d, avg_session_minutes, support_tickets, churned
data/sales.csv 20,228 order lines order_id, order_date, customer_id, revenue

Known quirks that matter for this job:

  • One order has 1 to 3 lines, so order_id is not unique. Count orders, not lines.
  • Only 3,254 of the 5,000 customers have orders. RFM is not defined for the others.
  • The orders cover 2023-01-01 to 2024-12-31, but signups start in 2018-12. A customer who signed up in 2024 had less time to order than a customer who signed up in 2019.
  • The snapshot date is 2024-12-31. Recency and the active window are measured from it.
  • churned flags the customers who churned in the last month. It stays out of the features. You use it only to check the segments afterward, and to remove those customers from the campaign list.
  • total_charges is blank for 10 new customers. This job does not use it.
  1. Build the customer table.

    • Goal: one row per buying customer with RFM features.
    • Acceptance: order lines are rolled up to orders first; recency, frequency and monetary value are computed per customer; frequency is fair to customers who signed up late, and any bias left is stated; the totals reconcile with sales.csv; the customers without orders are counted, not dropped silently.
    • Review: 24, 25, 26.
  2. Choose, transform and scale the features.

    • Goal: features that a distance-based method can use.
    • Acceptance: every included and excluded column has a reason; each transform has a printed reason (skew before and after); the scaler sits in a pipeline with the transforms.
    • Review: 27, 33, 34.
  3. Understand the feature space with PCA.

    • Goal: know which directions carry the variance and what the data looks like in 2-D.
    • Acceptance: explained variance ratio and cumulative share printed; loadings of the first components read in words; a scree plot and a 2-D density plot.
    • Review: 39.
  4. Choose k with several criteria.

    • Goal: an honest number of segments.
    • Acceptance: for k from 2 to 8, print inertia, silhouette, stability across random seeds and stability across bootstrap samples, all with the settings of the final model; plot them; choose k with a stated rule and show what the main alternative would give.
    • Review: 39.
  5. Compare with an alternative method.

    • Goal: know whether another method finds the same segments.
    • Acceptance: fit a Gaussian mixture (and optionally Ward clustering) with the same k; compare agreement (ARI), silhouette, stability and uncertainty; explain what BIC says and why you trust it or not.
    • Review: 39.
  6. Profile, name and act.

    • Goal: segments the marketing team can use.
    • Acceptance: a profile table in original units; sizes, churn rates and reachable (not churned) counts for every customer, including those without orders; a name and a one-line action per segment that match the printed profile; the segments drawn on the first two principal components.
    • Review: 25, 28, 39.
  7. Validate the segments.

    • Goal: evidence that the segments are stable and meaningful.
    • Acceptance: a chi-square test of churn by segment with an effect size; a split-half check over several random splits (segments defined on one half, compared with a model of the other half); a check of churn within tenure bands; output/segments.csv written; asserts on the key results.
    • Review: 29, 39.
Criterion Needs work (0–1) Meets (2) Excellent (3)
Customer table Counts lines as orders, or drops non-buyers silently Correct RFM per customer, totals reconciled Also corrects frequency for the active window and shows why
Features and scaling Raw columns, or no reason given Log transforms and scaling in a pipeline Every included and excluded column justified; each transform backed by printed skew
PCA Missing, or plots without reading Variance ratio and loadings printed Components named from loadings; limits of the 2-D view stated
Choice of k One criterion only Elbow, silhouette and one stability measure Seed and bootstrap stability on the final settings; a stated rule; the alternative k shown
Alternative method Missing GMM fitted and compared with ARI Also stability, uncertainty and a correct reading of BIC
Profiles and actions Cluster numbers only Named segments with sizes and churn All customers covered, churned ones flagged; one action each that fits the profile; no causal claims
Validation No test Chi-square test of churn by segment Effect size, split-half replication and a tenure check
Reproducibility Results change between runs Fixed seeds; runs top to bottom Asserts on key results; output file written and re-read
Total 24 points. 18 or more: the work is ready to hand over.

Try the milestones yourself first. The reference solution is one script, segments.py, shown in parts. The parts run top to bottom and share their variables. The whole script runs in well under a minute.

Reference solution — Milestone 1: Build the customer table
segments.py (setup)
from itertools import combinations
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.base import clone
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.compose import ColumnTransformer
from sklearn.decomposition import PCA
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.mixture import GaussianMixture
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
SNAPSHOT = pd.Timestamp("2024-12-31")
WINDOW_START = pd.Timestamp("2023-01-01")
MIN_YEARS = 90 / 365.25 # shortest active window used for a rate
segments.py (milestone 1a)
customers = pd.read_csv("data/customers.csv", parse_dates=["signup_date"])
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
# One date and one customer per order, so "first" loses nothing.
per_order = sales.groupby("order_id")[["order_date", "customer_id"]].nunique()
assert per_order.eq(1).all().all()
orders = sales.groupby(["customer_id", "order_id"], as_index=False).agg(
order_date=("order_date", "first"), revenue=("revenue", "sum")
)
print(f"{len(sales):,} order lines -> {len(orders):,} orders")
rfm = orders.groupby("customer_id").agg(
last_order=("order_date", "max"),
orders=("order_id", "size"),
revenue=("revenue", "sum"),
)
has_orders = customers["customer_id"].isin(rfm.index).rename("has_orders")
print(f"customers with orders: {has_orders.sum():,} of {len(customers):,}")
print(customers.groupby(has_orders)["churned"].agg(["size", "mean"]).round(3))
Output
20,228 order lines -> 14,877 orders
customers with orders: 3,254 of 5,000
size mean
has_orders
False 1746 0.270
True 3254 0.151

The assert confirms that each order has one date and one customer, so the roll-up loses nothing. The 20,228 lines become 14,877 orders. Only 3,254 customers have orders. The 1,746 others churn at 27.0%, against 15.1% for buyers. They cannot get RFM features, so they get rule-based segments in milestone 6. Clustering them with made-up RFM values (for example a recency of 730 days) would create a cluster that only says “no orders”.

segments.py (milestone 1b)
buyers = customers.set_index("customer_id").join(rfm, how="inner")
window_start = buyers["signup_date"].clip(lower=WINDOW_START)
window_years = ((SNAPSHOT - window_start).dt.days + 1) / 365.25
buyers["active_years"] = window_years.clip(lower=MIN_YEARS)
buyers["recency_days"] = (SNAPSHOT - buyers["last_order"]).dt.days
buyers["orders_per_year"] = buyers["orders"] / buyers["active_years"]
buyers["avg_order_value"] = buyers["revenue"] / buyers["orders"]
print("buyers with a window under 90 days:", (window_years < MIN_YEARS).sum())
cohort = pd.cut(
buyers["signup_date"].dt.year,
bins=[2017, 2022, 2023, 2024],
labels=["2018-2022", "2023", "2024"],
).rename("signup")
by_cohort = buyers.groupby(cohort, observed=True)
cohort_cols = ["active_years", "orders", "orders_per_year", "recency_days"]
print(by_cohort[cohort_cols].median().round(2))
rfm_cols = ["orders", "revenue", "orders_per_year", "avg_order_value"]
print(buyers[rfm_cols].corr().round(2))
assert len(buyers) == 3254
assert abs(buyers["revenue"].sum() - sales["revenue"].sum()) < 0.01
assert buyers["recency_days"].between(0, 730).all()
Output
buyers with a window under 90 days: 122
active_years orders orders_per_year recency_days
signup
2018-2022 2.00 4.0 2.00 99.0
2023 1.46 3.0 2.20 83.0
2024 0.58 2.0 3.43 40.0
orders revenue orders_per_year avg_order_value
orders 1.00 0.82 0.78 -0.01
revenue 0.82 1.00 0.64 0.39
orders_per_year 0.78 0.64 1.00 -0.01
avg_order_value -0.01 0.39 -0.01 1.00

Two design choices are visible here:

  • Frequency per active year. The active window of a customer runs from the later of the signup date and 2023-01-01 to the snapshot. Customers who signed up before 2023 had 2.00 years to order and placed a median of 4 orders. Customers who signed up in 2024 had 0.58 years and placed 2. Raw counts would mostly measure how long a customer could buy, which tenure_months already gives. A very short window has the opposite problem: 3 orders in 6 weeks would become a rate of about 26 a year. So the window has a floor of 90 days; 122 buyers hit it.
  • Average order value as monetary value. Total revenue is frequency times average order value (AOV), so it repeats frequency: orders and revenue correlate at 0.82. AOV correlates at −0.01 with orders per year, so the two features carry separate information.

A bias that stays. The rate does not fully remove the effect of a short window. Median orders per year are 3.43 for 2024 signups against 2.00 for older ones, and median recency is 40 days against 99. A customer who joined recently cannot have a long gap since the last order. Milestone 6 shows where this bias ends up.

Reference solution — Milestone 2: Choose, transform and scale the features
segments.py (milestone 2a)
FEATURES = [
"recency_days",
"orders_per_year",
"avg_order_value",
"tenure_months",
"monthly_charges",
"logins_last_30d",
"avg_session_minutes",
"support_tickets",
]
print(buyers.groupby("plan")["monthly_charges"].describe()[["min", "50%", "max"]])
print(buyers[FEATURES].skew().round(2))
aov = buyers["avg_order_value"]
print(f"AOV over 1,000 USD: {(aov > 1000).sum()} buyers, max {aov.max():,.2f}")
Output
min 50% max
plan
basic 28.05 37.990 77.63
premium 83.76 97.085 143.24
standard 51.36 62.720 98.54
recency_days 1.50
orders_per_year 2.11
avg_order_value 3.99
tenure_months 0.84
monthly_charges 0.58
logins_last_30d 1.83
avg_session_minutes 1.33
support_tickets 1.08
dtype: float64
AOV over 1,000 USD: 93 buyers, max 3,689.55

Columns in, and why. The three RFM numbers describe buying. Five account columns describe how the account is used and what it costs: tenure_months, monthly_charges, logins_last_30d, avg_session_minutes and support_tickets.

Columns out, and why:

Column Reason to leave it out
plan The medians of monthly_charges are 37.99, 62.72 and 97.085 USD for basic, standard and premium, so charges carry most of the plan information. It stays in the profile as a check.
contract, payment_method, has_autopay Contract and billing terms, not behavior. They are categories or 0/1 flags that would need an encoding, and they stay in the profile as checks.
age, region Demographics. The brief asks about buying and account use.
total_charges About monthly_charges × tenure_months (data dictionary), so it repeats two features; blank for 10 customers.
signup_date tenure_months and the active window already use it.
churned The outcome. Using it would make the churn check circular.

Six of the eight features have a skew above 1. AOV has the longest tail: 93 buyers spend more than 1,000 USD per order, up to 3,689.55. Long tails pull k-means centers toward a few customers.

segments.py (milestone 2b)
SHORT = {
"recency_days": "recency",
"orders_per_year": "ord/yr",
"avg_order_value": "AOV",
"tenure_months": "tenure",
"monthly_charges": "charges",
"logins_last_30d": "logins",
"avg_session_minutes": "session",
"support_tickets": "tickets",
}
LOG_FEATURES = [
"recency_days",
"orders_per_year",
"avg_order_value",
"logins_last_30d",
"avg_session_minutes",
"support_tickets",
]
log1p = FunctionTransformer(np.log1p, feature_names_out="one-to-one")
log_step = ColumnTransformer(
[("log", log1p, LOG_FEATURES)],
remainder="passthrough",
verbose_feature_names_out=False,
)
preprocess = make_pipeline(log_step, StandardScaler()).set_output(transform="pandas")
X = preprocess.fit_transform(buyers[FEATURES])
check = pd.DataFrame(
{
"skew raw": buyers[FEATURES].skew(),
"skew used": X.skew(),
"mean used": X.mean(),
"std used": X.std(ddof=0),
}
)
print(check.round(2) + 0.0) # + 0.0 turns -0.0 into 0.0
Output
skew raw skew used mean used std used
avg_order_value 3.99 -0.11 0.0 1.0
avg_session_minutes 1.33 -0.24 0.0 1.0
logins_last_30d 1.83 -0.41 0.0 1.0
monthly_charges 0.58 0.58 0.0 1.0
orders_per_year 2.11 0.40 0.0 1.0
recency_days 1.50 -0.46 0.0 1.0
support_tickets 1.08 0.09 0.0 1.0
tenure_months 0.84 0.84 0.0 1.0

log1p (the logarithm of 1 + x) shrinks long tails and keeps 0 at 0, which matters for recency, logins and tickets. It brings the six skews to between −0.46 and 0.40. tenure_months and monthly_charges keep their linear scale: their skew is below 1 and their units (months, USD) are easy to explain. The StandardScaler then gives every column mean 0 and standard deviation 1, so each feature has the same weight in the distance. A RobustScaler is not needed because the logs already tamed the outliers. The transforms and the scaler live in one pipeline, preprocess, so every later model refits them on its own rows.

Reference solution — Milestone 3: Understand the feature space with PCA
segments.py (milestone 3a)
pca = PCA(random_state=42).fit(X)
pc_names = [f"PC{i}" for i in range(1, len(FEATURES) + 1)]
ratio = pd.Series(pca.explained_variance_ratio_, index=pc_names)
print(pd.DataFrame({"ratio": ratio, "cumulative": ratio.cumsum()}).T.round(3))
loadings = pd.DataFrame(pca.components_[:4].T, index=X.columns, columns=pc_names[:4])
print(loadings.round(2) + 0.0)
Output
PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
ratio 0.213 0.163 0.149 0.133 0.101 0.099 0.087 0.055
cumulative 0.213 0.376 0.526 0.659 0.760 0.859 0.945 1.000
PC1 PC2 PC3 PC4
recency_days -0.64 0.00 0.02 0.00
orders_per_year 0.65 0.03 -0.09 0.07
avg_order_value 0.18 0.01 -0.28 0.73
logins_last_30d -0.03 0.70 0.01 -0.06
avg_session_minutes 0.02 0.71 -0.02 0.00
support_tickets 0.10 -0.02 0.69 0.09
tenure_months -0.35 0.03 -0.18 0.54
monthly_charges 0.01 -0.05 -0.63 -0.39

Read each component from its largest loadings:

  • PC1 (21.3%): high orders per year (0.65) and low recency (−0.64), with lower tenure (−0.35). It is “recent, frequent buying”, stronger among newer customers.
  • PC2 (16.3%): logins (0.70) and session minutes (0.71). It is “account use”.
  • PC3 (14.9%): many support tickets (0.69) and low charges (−0.63).
  • PC4 (13.3%): high AOV (0.73) and long tenure (0.54).

The variance is spread out: two components keep 37.6%, and it takes seven to pass 90%. Spread-out variance alone does not rule out clusters. The picture and the silhouette in milestone 4 decide that.

segments.py (milestone 3b)
scores = pca.transform(X)
PC1_LABEL = "PC1: recent, frequent buying"
PC2_LABEL = "PC2: account use"
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.bar(ratio.index, ratio, color="tab:blue", label="per component")
cumulative = ratio.cumsum()
ax1.plot(ratio.index, cumulative, color="tab:orange", marker="o", label="cumulative")
ax1.set(title="Explained variance ratio", ylabel="share of variance", ylim=(0, 1.05))
ax1.legend(loc="center right")
hexes = ax2.hexbin(scores[:, 0], scores[:, 1], gridsize=30, cmap="viridis", mincnt=1)
fig.colorbar(hexes, ax=ax2, label="buyers per hexagon")
ax2.set(title="Buyers on PC1 and PC2", xlabel=PC1_LABEL, ylabel=PC2_LABEL)
fig.tight_layout()
plt.show()
Left: bars of the explained variance ratio fall slowly from about 0.21 for PC1 to about 0.06 for PC8, and the cumulative line rises almost straight to 1. Right: a hexbin density of the buyers on PC1 and PC2 shows one round cloud with a single dense center and no gaps.
The variance is spread over many components, and the 2-D view shows one cloud, not separate groups.

The scree plot has no clear knee. The density plot shows one cloud with a single dense center. The segments you build next are a useful way to cut a continuum, not natural groups that the data separates on its own.

Reference solution — Milestone 4: Choose k with several criteria

Four criteria per k. Inertia and silhouette come from module 39. The two stability scores use the adjusted Rand index (ARI): 1 means two labelings group the customers identically, 0 means chance agreement. Both use the settings of the final model (n_init=10).

  • Seed stability: the same model with 10 random seeds, compared in all 45 pairs. A low value means the result depends on the seed.
  • Bootstrap stability: refit the whole pipeline on 20 bootstrap samples (rows drawn with replacement), label all buyers with each refit and compare with the full-data labels. A low value means a new sample of customers would give different segments. The score is a little optimistic: each refit is compared with a model of the full data, which contains all its rows (a bootstrap sample holds about 63% of the distinct buyers).
segments.py (milestone 4a)
def segmenter(k: int, seed: int = 42) -> Pipeline:
"""Preprocessing and k-means in one pipeline, fitted on raw features."""
model = KMeans(n_clusters=k, n_init=10, random_state=seed)
return Pipeline([("prep", clone(preprocess)), ("kmeans", model)])
rng = np.random.default_rng(42)
boot_rows = [rng.choice(len(buyers), size=len(buyers)) for _ in range(20)]
rows = []
for k in range(2, 9):
model = segmenter(k).fit(buyers[FEATURES])
labels = model["kmeans"].labels_
by_seed = [segmenter(k, seed=s)[-1].fit_predict(X) for s in range(10)]
seed_ari = [adjusted_rand_score(a, b) for a, b in combinations(by_seed, 2)]
boot_ari = [
adjusted_rand_score(
labels,
segmenter(k).fit(buyers.iloc[idx][FEATURES]).predict(buyers[FEATURES]),
)
for idx in boot_rows
]
rows.append(
{
"k": k,
"inertia": model["kmeans"].inertia_,
"silhouette": silhouette_score(X, labels),
"seed_ari": np.mean(seed_ari),
"boot_ari": np.mean(boot_ari),
"boot_worst": np.min(boot_ari),
"smallest": np.bincount(labels).min(),
}
)
k_table = pd.DataFrame(rows).set_index("k")
print(k_table.round(3))
Output
inertia silhouette seed_ari boot_ari boot_worst smallest
k
2 22254.220 0.137 0.997 0.909 0.820 1619
3 20482.202 0.116 0.855 0.586 0.292 912
4 19093.038 0.110 0.712 0.539 0.268 698
5 17939.854 0.112 0.875 0.585 0.348 583
6 17101.109 0.110 0.817 0.478 0.334 483
7 16328.959 0.107 0.852 0.614 0.402 421
8 15777.937 0.110 0.585 0.465 0.286 336

Inertia falls at every k, as it must, and shows no elbow. The silhouette is low everywhere (0.107 to 0.137) and highest at k = 2. With 10 starts per fit, the seed ARI is high for most k (0.712 to 0.997, and 0.585 at k = 8), so the seed matters little. The bootstrap ARI separates the k values better: 0.909 at k = 2, then between 0.465 and 0.614.

segments.py (milestone 4b)
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
axes[0].plot(k_table.index, k_table["inertia"], marker="o")
axes[0].set(title="Elbow: inertia", xlabel="k", ylabel="inertia")
axes[1].plot(k_table.index, k_table["silhouette"], marker="o", color="tab:orange")
axes[1].set(title="Silhouette", xlabel="k", ylabel="mean silhouette", ylim=(0, 0.3))
axes[2].plot(k_table.index, k_table["seed_ari"], marker="o", label="across seeds")
axes[2].plot(k_table.index, k_table["boot_ari"], marker="s", label="across bootstraps")
axes[2].set(title="Stability (ARI)", xlabel="k", ylabel="mean ARI", ylim=(0, 1))
axes[2].legend(loc="lower left")
for ax in axes:
ax.axvspan(2.5, 6.5, color="gray", alpha=0.12, linewidth=0)
fig.tight_layout()
plt.show()
Three panels for k from 2 to 8, with the range 3 to 6 shaded. Left: inertia falls smoothly from about 22,300 to about 15,800 with no sharp elbow. Middle: the silhouette is almost flat, from about 0.14 at k = 2 to about 0.11. Right: the seed ARI stays between about 0.6 and 1.0; the bootstrap ARI is about 0.91 at k = 2 and between about 0.47 and 0.61 for larger k.
No elbow and a flat silhouette. Only k = 2 is clearly stable across bootstrap samples.

The choice. The silhouette and both stability scores prefer k = 2, but two segments are below the 3 to 6 campaigns that the team can run. Inside the shaded range, the rule is: take the k values whose bootstrap ARI is within 0.01 of the best, then the smallest of them. k = 7 scores 0.614, but it is outside the range.

segments.py (milestone 4c)
in_range = k_table.loc[3:6] # the 3 to 6 campaigns the team can run
best = in_range["boot_ari"].max()
tied = in_range.index[in_range["boot_ari"] >= best - 0.01].tolist()
print("k within 0.01 of the best bootstrap ARI:", tied)
K = min(tied) # among equally stable choices, take the simplest
five = segmenter(5).fit(buyers[FEATURES])
by_five = buyers.groupby(five.predict(buyers[FEATURES]))
five_profile = by_five[FEATURES].median().rename(columns=SHORT)
five_profile["size"] = by_five.size()
print(five_profile.round(1))
assert K == 3
Output
k within 0.01 of the best bootstrap ARI: [3, 5]
recency ord/yr AOV tenure charges logins session tickets size
0 207.0 1.5 225.1 51.0 55.4 11.0 14.4 1.0 679
1 38.0 3.2 198.0 20.0 53.5 5.0 7.8 1.0 603
2 54.0 3.0 190.5 19.0 96.8 9.0 12.5 0.0 583
3 24.0 4.5 200.0 14.0 50.0 14.0 17.2 1.0 751
4 196.0 1.1 64.0 18.0 57.1 11.0 12.4 1.0 638

k = 3 (0.586) and k = 5 (0.585) tie, so the rule picks k = 3. The k = 5 solution, printed above, shows what this gives up: a high-charge group (cluster 2, median 96.8 USD) and a small-basket group (cluster 4, median AOV 64.0 USD) become their own segments. Both are clear profiles, but they are not more stable, and milestone 7 checks whether the three segments replicate. The asserts lock in the rule: if new data changes the tie, the script stops instead of silently changing the segments.

Reference solution — Milestone 5: Compare with a Gaussian mixture

A Gaussian mixture model (GMM) with full covariance matrices can fit stretched, tilted clusters that k-means cannot. Module 39 chose its number of components with BIC. Start there.

segments.py (milestone 5a)
bic = {}
for k in range(2, 9):
gm = GaussianMixture(n_components=k, n_init=2, random_state=42).fit(X)
bic[k] = gm.bic(X)
print(pd.Series(bic, name="BIC").round(0))
gm6 = GaussianMixture(n_components=6, n_init=2, random_state=42).fit(X)
variances = pd.DataFrame(
[np.diag(cov) for cov in gm6.covariances_], columns=X.columns
).rename(columns=SHORT)
variances.insert(0, "size", np.bincount(gm6.predict(X)))
print(variances.round(3))
print("buyers with 0 tickets:", (buyers["support_tickets"] == 0).sum())
Output
2 71638.0
3 70757.0
4 70558.0
5 70450.0
6 57811.0
7 45363.0
8 38869.0
Name: BIC, dtype: float64
size recency ord/yr AOV logins session tickets tenure charges
0 1079 0.998 1.037 0.950 1.016 1.002 0.000 0.987 0.981
1 223 1.200 1.073 0.596 0.917 0.855 0.205 0.143 1.079
2 346 0.736 0.639 1.066 1.213 0.972 0.434 0.712 0.231
3 782 0.885 0.901 0.631 1.022 1.018 0.236 0.486 1.049
4 333 0.167 0.257 1.771 0.911 1.134 0.358 0.193 1.027
5 491 0.626 0.746 1.197 0.729 0.954 0.448 0.060 0.298
buyers with 0 tickets: 1079

BIC falls slowly from k = 2 to k = 5, then drops by about 12,600 at k = 6 and keeps falling. The 6-component model shows why. Component 0 has exactly 1,079 members, the number of buyers with 0 tickets, and a ticket variance of 0.000. Those buyers all share one value of the scaled ticket column. A Gaussian squeezed onto a single value has a huge density, so the likelihood soars and BIC rewards it. The component models a discrete column, not a customer segment. Here BIC cannot choose k. Compare the methods at the chosen k = 3 instead.

segments.py (milestone 5b)
kmeans_labels = segmenter(K).fit_predict(buyers[FEATURES])
gmm = make_pipeline(
clone(preprocess), GaussianMixture(n_components=K, n_init=2, random_state=42)
)
gmm_labels = gmm.fit(buyers[FEATURES]).predict(buyers[FEATURES])
gmm_boot = [
adjusted_rand_score(
gmm_labels,
clone(gmm).fit(buyers.iloc[idx][FEATURES]).predict(buyers[FEATURES]),
)
for idx in boot_rows
]
ward_labels = AgglomerativeClustering(n_clusters=K, linkage="ward").fit_predict(X)
top_prob = gmm.predict_proba(buyers[FEATURES]).max(axis=1)
comparison = pd.DataFrame(
{
"ARI vs k-means": [1.0, adjusted_rand_score(kmeans_labels, gmm_labels),
adjusted_rand_score(kmeans_labels, ward_labels)],
"silhouette": [silhouette_score(X, lab)
for lab in (kmeans_labels, gmm_labels, ward_labels)],
"boot ARI": [k_table.loc[K, "boot_ari"], np.mean(gmm_boot), np.nan],
"smallest": [np.bincount(lab).min()
for lab in (kmeans_labels, gmm_labels, ward_labels)],
},
index=["k-means", "GMM (full)", "Ward"],
)
print(comparison.round(3))
print(f"GMM buyers with top probability < 0.8: {(top_prob < 0.8).mean():.1%}")
print(pd.crosstab(kmeans_labels, gmm_labels, rownames=["k-means"], colnames=["GMM"]))
gmm_profile = buyers.groupby(gmm_labels)[FEATURES].median().rename(columns=SHORT)
print(gmm_profile.round(1))
Output
ARI vs k-means silhouette boot ARI smallest
k-means 1.000 0.116 0.586 912
GMM (full) 0.125 0.073 0.602 745
Ward 0.134 0.069 NaN 860
GMM buyers with top probability < 0.8: 30.8%
GMM 0 1 2
k-means
0 711 2 504
1 390 172 350
2 207 571 347
recency ord/yr AOV tenure charges logins session tickets
0 46.0 3.0 157.5 10.0 60.4 10.0 13.0 1.0
1 351.0 1.0 140.0 29.0 58.5 10.0 12.7 1.0
2 36.0 3.5 193.5 37.0 57.9 9.0 12.5 1.0

The methods cut the data in different places: the ARI with k-means is 0.125 for the GMM and 0.134 for Ward. The GMM profile shows how. Its three groups split on tenure and recency: newer customers (median tenure 10), long-lapsed buyers (median recency 351 days) and established, active buyers (tenure 37, recency 36). Their logins (9 to 10) and session minutes (12.5 to 13.0) are almost the same, so the GMM ignores account use. When different methods find different groups, the data has no clear borders, which matches the PCA picture.

How to choose between them:

  • Silhouette (0.116 against 0.073 and 0.069) is biased toward k-means, because it rewards compact round clusters, which is what k-means builds. It does not decide.
  • Stability is a tie: bootstrap ARI 0.586 for k-means and 0.602 for the GMM.
  • Certainty: 30.8% of the buyers get a top GMM probability below 0.8. k-means gives every buyer one clear segment, which is what a campaign list needs.
  • Fit to the data: tickets and logins are small counts with spikes at single values, so the Gaussian shape fits them badly, as the BIC collapse showed.
  • The brief: it asks about buying and account use. The k-means segments use both; the GMM groups use only the buying side.

Keep k-means. This is a judgment on the brief, not a win on every number.

Reference solution — Milestone 6: Profile, name and act
segments.py (milestone 6a)
# (name, feature, pick the cluster with the largest value?)
NAMING_RULES = [
("Lapsed buyers", "recency_days", True),
("Light app users", "logins_last_30d", False),
("Frequent recent buyers", "recency_days", False),
]
def name_clusters(medians: pd.DataFrame) -> dict[int, str]:
"""Name clusters from their median profile, so names survive a refit."""
names: dict[int, str] = {}
for name, feature, largest in NAMING_RULES:
free = medians.loc[[c for c in medians.index if c not in names], feature]
names[free.idxmax() if largest else free.idxmin()] = name
return names
final = segmenter(K).fit(buyers[FEATURES])
buyers["cluster"] = final.predict(buyers[FEATURES])
names = name_clusters(buyers.groupby("cluster")[FEATURES].median())
buyers["segment"] = buyers["cluster"].map(names)
profile = buyers.groupby("segment")[FEATURES].median().rename(columns=SHORT)
profile["size"] = buyers["segment"].value_counts()
print(profile.sort_values("size").round(1))
Output
recency ord/yr AOV tenure charges logins session tickets size
segment
Light app users 76.0 2.4 198.6 21.0 63.1 6.0 7.9 1.0 912
Lapsed buyers 231.0 1.1 130.0 33.0 56.1 12.0 15.0 1.0 1125
Frequent recent buyers 25.0 4.4 186.2 14.0 58.2 12.0 15.1 1.0 1217

Cluster numbers change when the data or the seed changes, so name_clusters names the clusters by rules on their medians, in order: the longest recency, then the fewest logins, then the shortest recency. The same rules name the split-half models in milestone 7. The names come from this profile, in original units:

  • Lapsed buyers (1,125): last order a median 231 days ago, 1.1 orders a year, the lowest AOV (130.0 USD) and the longest tenure (33 months).
  • Light app users (912): 6 logins and 7.9 session minutes, against 12 and about 15 in the other segments. Their buying is in between (76 days, 2.4 orders a year).
  • Frequent recent buyers (1,217): last order 25 days ago, 4.4 orders a year, the shortest tenure (14 months).

Charges (56.1 to 63.1 USD) and tickets (median 1) are similar in all three. Unlike module 39, whose segments came from account columns only, these segments are shaped by buying (recency and frequency) and by account use (logins and sessions).

Now the bias from milestone 1. Each column of the next table is a signup cohort, and the shares add up to 1 within a column.

segments.py (milestone 6b)
print(pd.crosstab(buyers["segment"], cohort, normalize="columns").round(2))
Output
signup 2018-2022 2023 2024
segment
Frequent recent buyers 0.24 0.39 0.61
Lapsed buyers 0.50 0.32 0.11
Light app users 0.27 0.30 0.29

Frequent recent buyers hold 61% of the 2024 signups but only 24% of the 2018–2022 signups. Lapsed buyers hold 50% of the older signups and 11% of the 2024 ones. So “frequent recent” partly means “new account”: a short window gives a short gap since the last order and a higher rate. Light app users take a similar share of every cohort (27% to 30%). The action for frequent recent buyers below takes this into account.

Next, the customers without orders. They split by signup date: those who joined in 2024 had less than a year to order, and those who joined earlier had a full year or more and still did not.

segments.py (milestone 6c)
segment_of = buyers["segment"].reindex(customers["customer_id"]).to_numpy()
new_account = customers["signup_date"] >= pd.Timestamp("2024-01-01")
no_orders = np.where(new_account, "New, no order yet", "Long-time non-buyers")
everyone = customers.assign(
segment=np.where(pd.isna(segment_of), no_orders, segment_of)
)
summary = everyone.groupby("segment").agg(
customers=("customer_id", "size"),
churn=("churned", "mean"),
reachable=("churned", lambda c: (c == 0).sum()),
tenure=("tenure_months", "median"),
premium=("plan", lambda plan: (plan == "premium").mean()),
m2m=("contract", lambda c: (c == "month-to-month").mean()),
)
summary.insert(1, "share", summary["customers"] / len(everyone))
print(summary.sort_values("churn").round(3))
Output
customers share churn reachable tenure premium m2m
segment
Lapsed buyers 1125 0.225 0.080 1035 33.0 0.154 0.384
Long-time non-buyers 765 0.153 0.123 671 25.0 0.209 0.413
Frequent recent buyers 1217 0.243 0.179 999 14.0 0.185 0.608
Light app users 912 0.182 0.202 728 21.0 0.294 0.507
New, no order yet 981 0.196 0.384 604 4.0 0.167 0.850

This table covers all 5,000 customers. Every column comes from customers.csv, so it works for the customers without orders too. reachable counts the customers who have not churned; only they can receive a campaign. The churn rate is the one-month rate in the snapshot, used here to check the segments, not as a forecast.

Two columns that k-means never saw, contract and plan, support the profiles. The month-to-month share is 60.8% for frequent recent buyers, in line with their short tenure, and 38.4% for lapsed buyers. Light app users have the highest premium share among buyers (29.4% against 15.4% and 18.5%), although their median charges (63.1 USD) are only a little higher.

Segments and actions for the marketing team. An action is a candidate to test, not a promise: the segments show where churn concentrates, not what causes it.

SegmentReachable / allChurnProfile in one lineAction
Lapsed buyers1,035 / 1,1258.0%Last order 231 days ago, 1.1 orders a year, median tenure 33 monthsSend a win-back offer for the next order; keep retention spend low.
Long-time non-buyers671 / 76512.3%Joined before 2024, no order in 2023–2024, median tenure 25 monthsShow them the shop with product picks; they keep the subscription without buying.
Frequent recent buyers999 / 1,21717.9%Last order 25 days ago, 4.4 orders a year, median tenure 14 months, 60.8% month-to-monthOffer an annual contract while they are active; for new accounts, add onboarding.
Light app users728 / 91220.2%6 logins and 7.9 session minutes, 29.4% on the premium planRun a re-engagement series that shows the features they do not use.
New, no order yet604 / 98138.4%Joined in 2024, median tenure 4 months, 85.0% month-to-monthSend a first-purchase welcome offer and onboarding.
segments.py (milestone 6d)
fig, ax = plt.subplots(figsize=(8.5, 5))
for name in sorted(names.values()):
mask = (buyers["segment"] == name).to_numpy()
ax.scatter(scores[mask, 0], scores[mask, 1], s=5, alpha=0.5, label=name)
ax.set(xlabel=PC1_LABEL, ylabel=PC2_LABEL, title="Buyer segments on PC1 and PC2")
ax.legend(markerscale=3, fontsize=8, loc="upper left", bbox_to_anchor=(1, 1))
fig.tight_layout()
plt.show()
A scatter plot of the 3,254 buyers on PC1 and PC2, colored by segment. Frequent recent buyers fill the right side along PC1, lapsed buyers the left side, and light app users the bottom along PC2; the three colors touch at their borders.
The segments cut one cloud into three regions: PC1 separates frequent recent from lapsed buyers, and PC2 separates the light app users.

The picture matches the loadings: frequent recent buyers score high on PC1 (recent, frequent buying), lapsed buyers low, and light app users low on PC2 (account use). The colors touch at their borders. The 2-D view keeps 37.6% of the variance; k-means used all eight dimensions.

Reference solution — Milestone 7: Validate the segments

Three checks. First, is churn related to the segment at all? The chi-square test of independence answers yes or no, and Cramér’s V (0 = no relation, 1 = perfect) gives the strength.

segments.py (milestone 7a)
def churn_test(segment: pd.Series, churned: pd.Series) -> str:
table = pd.crosstab(segment, churned)
res = stats.chi2_contingency(table)
v = np.sqrt(res.statistic / (table.to_numpy().sum() * (min(table.shape) - 1)))
return (
f"chi2 = {res.statistic:.1f}, dof = {res.dof}, "
f"p = {res.pvalue:.1e}, V = {v:.3f}"
)
print("buyers: ", churn_test(buyers["segment"], buyers["churned"]))
print("everyone: ", churn_test(everyone["segment"], everyone["churned"]))
Output
buyers: chi2 = 70.0, dof = 2, p = 6.3e-16, V = 0.147
everyone: chi2 = 349.4, dof = 4, p = 2.4e-74, V = 0.264

Churn differs by segment far beyond chance (p = 6.3e-16 for the buyers). The strength is modest for the three buyer segments (V = 0.147); adding the two non-buyer groups raises it to 0.264, mostly because of the 38.4% churn of new customers without orders. The churn flag never entered the model. One caveat: logins, session minutes and recency are measured in the same last month as the churn flag, so part of the relation may reflect the churn itself, for example a customer who stopped logging in before leaving.

But the same data built the segments and tests them. Second check, a split-half validation: split the buyers at random into halves A and B, build and name the segments on A only, and compare them on B with segments built and named on B itself. Five random splits show how much the result depends on the split.

segments.py (milestone 7b)
def named_segments(train: pd.DataFrame, apply_to: pd.DataFrame) -> pd.Series:
"""Fit the pipeline on train, name its clusters, label apply_to."""
model = segmenter(K).fit(train[FEATURES])
train_names = name_clusters(
train.groupby(model.predict(train[FEATURES]))[FEATURES].median()
)
labels = model.predict(apply_to[FEATURES])
return pd.Series(labels, index=apply_to.index).map(train_names)
split_rows = []
for split in range(5):
perm = np.random.default_rng(split).permutation(len(buyers))
half_a = buyers.iloc[perm[: len(perm) // 2]]
half_b = buyers.iloc[perm[len(perm) // 2 :]]
seg_b_from_a = named_segments(half_a, half_b) # B is held out from A
seg_b_from_b = named_segments(half_b, half_b)
row = {
"ARI A vs B": adjusted_rand_score(seg_b_from_a, seg_b_from_b),
"same name": (seg_b_from_a == seg_b_from_b).mean(),
}
row |= half_b.groupby(seg_b_from_a)["churned"].mean().to_dict()
split_rows.append(row)
if split == 0:
print("split 0, half B:", churn_test(seg_b_from_a, half_b["churned"]))
splits = pd.DataFrame(split_rows).rename_axis("split")
print(splits.round(3))
Output
split 0, half B: chi2 = 44.0, dof = 2, p = 2.9e-10, V = 0.164
ARI A vs B same name Frequent recent buyers Lapsed buyers Light app users
split
0 0.406 0.726 0.133 0.089 0.230
1 0.230 0.501 0.164 0.094 0.242
2 0.551 0.816 0.186 0.079 0.196
3 0.540 0.805 0.166 0.077 0.214
4 0.579 0.825 0.173 0.082 0.218

The agreement depends on the split. In four of the five splits, 72.6% to 82.5% of the half-B buyers get the same name from both models (ARI 0.406 to 0.579). In split 1, only 50.1% do (ARI 0.230). Chance agreement for three names is about one in three. So expect one buyer in five to one in two to switch segments when the model is refit; the borders are soft. The churn pattern is steadier: in every split, half B’s churn is lowest for lapsed buyers (7.7% to 9.4%), highest for light app users (19.6% to 24.2%), with frequent recent buyers in between. The test on half B of split 0 is clear (p = 2.9e-10, V = 0.164).

Third check: tenure. Short tenure goes with high churn in the whole customer base (the data dictionary reports 44.4% churn for tenures of 1 to 6 months), and the segments differ in tenure. Are they more than tenure bands? Compare churn inside tenure bands.

segments.py (milestone 7c)
band = pd.cut(buyers["tenure_months"], bins=[0, 12, 24, 48, 72]).rename("tenure")
within = buyers.pivot_table(
index="segment", columns=band, values="churned", aggfunc="mean", observed=True
)
counts = buyers.pivot_table(
index="segment", columns=band, values="churned", aggfunc="size", observed=True
)
print(within.round(3))
print(counts.fillna(0).astype(int))
Output
tenure (0, 12] (12, 24] (24, 48] (48, 72]
segment
Frequent recent buyers 0.278 0.130 0.060 0.062
Lapsed buyers 0.164 0.100 0.083 0.034
Light app users 0.349 0.178 0.131 0.052
tenure (0, 12] (12, 24] (24, 48] (48, 72]
segment
Frequent recent buyers 561 323 252 81
Lapsed buyers 110 281 386 348
Light app users 275 258 282 97

Churn falls with tenure in every segment. Light app users churn the most in the first three bands (34.9%, 17.8% and 13.1%), so their higher churn is not only a tenure effect. The two other segments swap places. Overall, frequent recent buyers churn more than lapsed buyers (17.9% against 8.0%), but 561 of them are in the first year, where everyone churns more. From 24 to 48 months, frequent recent buyers churn less than lapsed buyers (6.0% against 8.3%); from 48 months on, a little more (6.2% against 3.4%). So the gap between these two segments goes mostly with tenure. None of this shows that tenure or usage causes churn; other columns vary with them, such as the contract type (see the month-to-month shares in milestone 6).

segments.py (milestone 7d)
Path("output").mkdir(exist_ok=True)
everyone[["customer_id", "segment", "churned"]].to_csv(
"output/segments.csv", index=False
)
saved = pd.read_csv("output/segments.csv")
print(saved.groupby("segment")["churned"].agg(customers="size", churned="sum"))
assert len(saved) == len(customers) and saved["customer_id"].is_unique
assert profile["size"].min() >= 0.1 * len(buyers)
assert splits["same name"].min() > 0.45 # chance level for 3 names is about 1/3
churn_cols = sorted(names.values())
assert (splits[churn_cols].idxmin(axis=1) == "Lapsed buyers").all()
assert (splits[churn_cols].idxmax(axis=1) == "Light app users").all()
Output
customers churned
segment
Frequent recent buyers 1217 218
Lapsed buyers 1125 90
Light app users 912 184
Long-time non-buyers 765 94
New, no order yet 981 377

The file has one row per customer with the churn flag, so the team can keep only the 4,037 reachable customers (5,000 minus the 963 churned ones). Reading it back gives the same counts as the summary table. The asserts lock in the key results: every customer appears once, the smallest buyer segment holds at least 10% of the buyers, every split keeps more than 45% of names (well above the one-in-three chance level), and the churn order of the buyer segments holds in every split.

Summary for the marketing lead. The buyers form one continuous cloud, not separate groups. Three buyer segments are a useful way to cut it, and two rule-based groups cover the customers without orders: five campaigns in total. Churn differs clearly between the five, from 8.0% to 38.4%, and the order of the buyer segments repeats on held-out halves. The borders are soft: one buyer in five to one in two can switch segment when the model is refit, and “frequent recent buyers” are partly new accounts. Refit on a schedule, and test each action against a control group before rolling it out.

  1. Re-run milestones 6 and 7 with k = 5 (extend the naming rules for the high-charge and small-basket clusters). Do the five churn rates keep their order across the five splits?
  2. Replace log1p by np.log for the two strictly positive features (orders per year and AOV). Does the stability table of milestone 4 still point to the same k? What does that say about how much a transform choice can move the result?
  3. Add the online share of each customer’s order lines (channel == "online") as a ninth feature. Does it create a new segment or only add noise?
  4. Score each buyer’s distances to the cluster centers with final.transform(...). List the 5% of buyers closest to a border and check how often they switch segment across the five splits.
  5. Write a function assign_segment(new_customers: pd.DataFrame) -> pd.Series that applies final to new buyers and the two no-order rules to the others, with a pytest test.