Build a Customer Segmentation Pipeline with K-Means Clustering


classical-ml feature-engineering model-evaluation
View full code for this problem

ML Problem & Solution

Customer Segmentation with K-Means

There is no right answer to grade against, so the only defensible target is a partition that survives resampling.

⏱ 23 min read 📐 Intermediate 🧩 Classical ML

A direct-to-consumer retailer sends one email to 2.1 million customers. It converts at 0.9% and earns $0.31 per recipient. The growth team’s proposal is obvious and correct: stop sending one email. Send six, each built for a group of customers who behave alike, and the revenue per send should rise because the offer finally matches the person.

The part nobody says out loud is that the six groups do not exist yet. Marketing currently has five tiers drawn in a workshop in 2023: “new”, “loyal”, “lapsed”, “VIP”, and “everyone else”, defined by thresholds somebody picked because they were round numbers. The VIP threshold is $500 lifetime spend. Nothing in the data happens at $500. It is a number a human likes.

This is where segmentation differs from every supervised problem on this site. There is no held-out label to score against. No amount of cross-validation will tell you the segments are correct, because correctness is not defined. Ask three analysts to segment the same 2.1M customers and you get three different answers, all of which have a plausible story attached, and the story is the problem: a clustering will always produce groups, and humans will always be able to narrate them. KMeans(n_clusters=5).fit(X) never fails. It never warns you. It returns five labels on random noise with the same confidence it returns five labels on genuinely separated data.

Think of it like drawing borders on an unmapped continent. There is no true border. But some borders follow rivers and mountain ranges, and those survive when a different surveyor walks the same ground. Others were drawn with a ruler, and the next surveyor draws them somewhere else entirely. We cannot measure whether a border is right. We can measure whether it is reproducible, and for segmentation that turns out to be most of what we need, because a segment that moves when you resample the data cannot support a campaign calendar that runs for a quarter.

The second constraint is that a segment nobody can act on is worth nothing. A mathematically gorgeous partition into 34 clusters distinguished by principal components 4 through 9 is a dead end, because marketing has the operational capacity to run roughly six campaign tracks and a segment has to be describable in one sentence to a copywriter.

Formally: given 2.1M customer behavioural histories over an 18 month window, partition them into k groups that maximise between-group difference in forward 90 day behaviour, optimising for a partition that is stable under resampling (bootstrap ARI) and internally cohesive (silhouette), under the constraints that k is between 4 and 8, every segment holds at least 4% of customers, and segment membership survives a monthly refit without wholesale reassignment.

Framing the Problem

This is unsupervised partitional clustering, and the framing choice that matters most is what we refuse to let it be. It is not a proxy for churn prediction, it is not a proxy for CLV, and it is not a substitute for either. If the question is “who will lapse next quarter”, that is supervised, the label exists, and a gradient boosted classifier will beat any clustering at it by a wide margin. Segmentation answers a different question: what kinds of customer do we have, so that we can build a small number of distinct treatments rather than 2.1M individual ones.

There is no target variable. That single fact reshapes the whole project, so it is worth being explicit about what replaces it.

The objective K-Means actually optimises is within-cluster sum of squares, also called inertia:

J = sum over i=1..k  sum over x in C_i  ||x - mu_i||^2

Lloyd’s algorithm alternates two steps until assignments stop changing: assign every point to its nearest centroid, then move every centroid to the mean of its assigned points. Both steps monotonically decrease J, which guarantees convergence and guarantees nothing about the result being good. J decreases monotonically in k as well, which is exactly why you cannot pick k by minimising it.

Three consequences of that objective are load-bearing and get their own sections later:

  • Minimising squared Euclidean distance means every feature’s scale is a weight on that feature. A column in dollars beats a column in counts, not because it matters more but because its numbers are bigger.
  • Centroids are means, so the model assumes clusters are roughly spherical and roughly equal in spread. Elongated or wildly unequal clusters get sliced across rather than found.
  • The assignment step is a Voronoi partition, so K-Means will happily cut through a dense region if that lowers J, and will split one real group into two before it isolates a small distinct one.

Constraints

  • k between 4 and 8, hard. Six campaign tracks is what the marketing team can staff. This is not a modelling constraint that we are free to relax with a better algorithm; it is a headcount constraint. Any k selection procedure that recommends 23 is answering a question nobody asked.
  • Minimum segment size 4%, roughly 84,000 customers. Below that the email volume cannot power a test at the effect sizes we care about, and the segment becomes an unmeasurable pet project.
  • Stability across monthly refits. The campaign calendar is built a quarter out. If the February refit moves 40% of customers between segments, every campaign in flight is now pointed at the wrong people.
  • Each segment describable in one sentence. The copywriter needs “recent, frequent, low basket size, discount-driven”, not “high on PC3”.
  • Batch only, no latency budget worth discussing. Assignment is an argmin over k centroids in a handful of dimensions. Scoring all 2.1M customers is a single matrix multiply. There is no serving problem here, which is a relief given how much else there is.
  • No protected attributes. Age, gender, and inferred ethnicity stay out. Segments drive differential discounting, and a segment that is 80% one demographic group receiving systematically worse offers is a legal problem regardless of how it arose.
Metric That Matters

Bootstrap adjusted Rand index at the chosen k. Resample the customer base with replacement 50 times, refit the whole pipeline on each resample, and measure the agreement between each resampled partition and the reference partition on the customers they share. ARI corrects for chance agreement, so 0 means the partition is no more consistent than random relabelling and 1 means identical. We require ARI >= 0.80. Silhouette is reported but it is a secondary metric, because silhouette measures whether the clusters are geometrically tight in the space you chose, and it cannot tell you that you chose a space where any partition would look tight. Inertia is not a metric at all: it decreases with k by construction.

Guardrail metrics: largest and smallest segment share (a partition where one cluster holds 90% of customers is a failure even at ARI 0.95), between-segment spread in forward 90 day revenue (the partition has to separate on something we care about, not just on something that happens to have variance), and month-over-month migration rate after centroid matching.

Out of scope: choosing the offers. This post produces segments and profiles them. Deciding that segment 4 gets free shipping and segment 2 gets a bundle is a pricing and incrementality question that needs holdout tests, and a clustering cannot tell you what treatment works.

Key Insight

Because there is no ground truth, the substitute is reproducibility, and reproducibility has to be measured against resampling the data, not against reseeding the algorithm. Running KMeans with 10 different random_state values and getting the same answer tells you the optimiser is converging consistently, which n_init=10 and k-means++ seeding already handle. It tells you nothing about whether the structure is real. Bootstrap the customers, refit end to end including the transforms, and compare. That is the difference between a stable optimiser and a stable finding.

Data and Features

The unit of observation is one customer as of the snapshot date. 2.1M customers with at least one order in the 18 month window, from 9.4M orders and 41M web sessions.

Source Grain Fields used Notes
orders order 14 timestamp, gross, discount, channel, fulfilment
order_lines line 8 category, unit price, quantity, margin
sessions session 9 device, referrer, duration, pages, cart events
email_events send 6 opens, clicks, unsubscribes
returns return 5 date, reason code, refund amount
customers customer 4 signup date, acquisition channel, market
Customer segmentation pipeline: order, session and email tables aggregated to customer level RFM and behavioural features, rank transformed, correlation grouped and whitened, then k selected by bootstrap stability before MiniBatchKMeans assignment, profiling and activation

The feature set, and why it is deliberately small

We use 14 features in five groups. Restraint matters here in a way it does not in supervised learning. A gradient boosted tree given 400 features will ignore the 380 useless ones. K-Means cannot ignore anything: every feature contributes its full variance to the distance metric, so an irrelevant feature is not neutral, it is noise injected directly into the objective. Adding 30 low-signal columns will visibly degrade a clustering that worked with 14.

# Customer level feature construction. Everything is computed strictly from
# events before `snapshot`, and every monetary column is left raw here because
# the transform stage owns the skew correction.
import numpy as np
import pandas as pd

RECENCY_CAP_DAYS = 540


def build_customer_features(orders: pd.DataFrame, lines: pd.DataFrame,
                            sessions: pd.DataFrame, emails: pd.DataFrame,
                            snapshot: pd.Timestamp) -> pd.DataFrame:
    o = orders[orders["order_ts"] < snapshot]
    s = sessions[sessions["session_ts"] < snapshot]
    e = emails[emails["send_ts"] < snapshot]

    # Group 1: recency, frequency, monetary. The classical RFM triple, still
    # the backbone of every retail segmentation since Hughes formalised it for
    # database marketing in the 1990s.
    g = o.groupby("customer_id")
    f = pd.DataFrame(index=g.size().index)
    f["recency_days"] = ((snapshot - g["order_ts"].max()).dt.days
                         .clip(upper=RECENCY_CAP_DAYS))
    f["frequency"] = g.size()
    f["monetary_total"] = g["gross_amount"].sum()
    f["avg_order_value"] = f["monetary_total"] / f["frequency"]

    # Group 2: tenure and cadence. tenure_days separates a customer with 4
    # orders in 3 weeks from one with 4 orders in 17 months, which RFM alone
    # collapses into the same cell.
    f["tenure_days"] = (snapshot - g["order_ts"].min()).dt.days
    spans = g["order_ts"].agg(lambda t: t.sort_values().diff().dt.days.mean())
    f["mean_interorder_days"] = spans
    # Single-order customers have no interval. Imputing the population mean
    # would place them in the middle of the cadence axis, which is the one
    # place they certainly do not belong.
    f["mean_interorder_days"] = f["mean_interorder_days"].fillna(
        RECENCY_CAP_DAYS)
    f["orders_per_active_month"] = f["frequency"] / (
        f["tenure_days"].clip(lower=30) / 30.44)

    # Group 3: discount dependence. The behavioural axis most likely to be
    # worth a distinct treatment, and the one pure RFM is blind to.
    f["discount_rate"] = (o.groupby("customer_id")["discount_amount"].sum()
                          / f["monetary_total"]).clip(0, 1)
    promo = o[o["discount_amount"] > 0].groupby("customer_id").size()
    f["promo_order_share"] = (promo.reindex(f.index).fillna(0)
                              / f["frequency"])

    # Group 4: breadth and basket shape. Category entropy distinguishes the
    # single-category replenisher from the browse-everything customer at the
    # same spend level.
    cat = (lines.merge(o[["order_id", "customer_id"]], on="order_id")
           .groupby(["customer_id", "category"]).size()
           .rename("n").reset_index())
    tot = cat.groupby("customer_id")["n"].transform("sum")
    p = cat["n"] / tot
    f["category_entropy"] = (-(p * np.log(p)).groupby(cat["customer_id"])
                             .sum().reindex(f.index).fillna(0))
    f["distinct_categories"] = (cat.groupby("customer_id").size()
                                .reindex(f.index).fillna(0))
    f["items_per_order"] = (lines.merge(o[["order_id", "customer_id"]],
                                        on="order_id")
                            .groupby("customer_id")["quantity"].sum()
                            / f["frequency"])

    # Group 5: engagement and friction, from non-purchase signals.
    f["sessions_per_order"] = (s.groupby("customer_id").size()
                               .reindex(f.index).fillna(0) / f["frequency"])
    f["email_click_rate"] = (e.groupby("customer_id")["clicked"].mean()
                             .reindex(f.index).fillna(0.0))
    f["return_rate"] = (o.groupby("customer_id")["was_returned"].mean()
                        .reindex(f.index).fillna(0.0))
    return f

The leakage risk here is not what you expect

Clustering has no label, so the classical “feature known only after the outcome” leakage cannot happen. A different and more damaging contamination takes its place: evaluating the segmentation using the same window that produced the features.

The tempting validation is to show that segments differ in average order value, using the same avg_order_value column that went into the clustering. That is circular. K-Means was told to separate on that column and it did. The number proves the optimiser ran.

The honest version splits time. Features come from months 1 to 15. The evaluation of whether segments separate on anything we care about comes from months 16 to 18, which the clustering never saw. On this data the gap is stark: within-window AOV separation between the top and bottom segment is 14.1x, and forward 90 day revenue separation is 11.3x. The second number is the real one. Any project that only reports the first is showing you a tautology.

The narrower version of the same mistake bites the k selection. Choosing k by the silhouette of the fitted partition and then reporting that silhouette as evidence of quality reports a maximum over a selection you just made. Select k on a subsample, report the metric on held-out customers.

Common Pitfall

Including a monetary total and an order count and an average order value puts the same underlying quantity into the distance metric three times, because monetary_total = frequency * avg_order_value by construction. The spend axis then carries three times the weight of the discount axis, and the resulting clusters are almost pure spend tiers wearing the costume of a multi-dimensional segmentation. In this feature set monetary_total correlates 0.71 with frequency and 0.66 with avg_order_value. Correlated features are not a mild inefficiency in K-Means the way they are in a tree ensemble; they are a silent reweighting of the objective.

Transform before you cluster, and rank-transform rather than z-score

Every monetary and count feature here is heavily right-skewed. monetary_total has a mean of $247, a median of $89, and a maximum of $412,000. Standardising with StandardScaler divides by a standard deviation that the tail itself inflated, so the 99% of customers under $1,000 get compressed into a narrow band while a few thousand whales occupy the rest of the axis. K-Means then spends its clusters describing the tail, because that is where the squared distance is. This is the single most common cause of the “one cluster with 91% of customers” outcome.

log1p fixes most of it. QuantileTransformer with a normal output distribution fixes all of it, by mapping each feature to its rank and then to a Gaussian, which makes the transform immune to how heavy the tail is. The cost is that distances become distances in rank space, so “twice as far” no longer means “twice the dollars”. For segmentation that trade is worth taking: we want customers ordered and spaced sensibly, not preserved in dollar units.

# Transform stage. Rank-normalise, group correlated features, then whiten.
# Fit on train only and reuse the fitted object at scoring time, or the
# monthly refit will silently change the space the centroids live in.
from sklearn.compose import ColumnTransformer
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import QuantileTransformer

SKEWED = ["frequency", "monetary_total", "avg_order_value", "tenure_days",
          "mean_interorder_days", "orders_per_active_month",
          "sessions_per_order", "items_per_order", "distinct_categories",
          "recency_days"]
BOUNDED = ["discount_rate", "promo_order_share", "email_click_rate",
           "return_rate", "category_entropy"]


def build_transform(n_components: int = 7, seed: int = 11) -> Pipeline:
    quantile = QuantileTransformer(output_distribution="normal",
                                   n_quantiles=1000, subsample=200_000,
                                   random_state=seed)
    pre = ColumnTransformer([
        ("skewed", quantile, SKEWED),
        # Bounded ratios are already on a comparable 0-1 scale, but they are
        # not Gaussian, and leaving them untransformed next to rank-normalised
        # columns understates their weight. Rank them too, for consistency of
        # the distance metric rather than for skew.
        ("bounded", QuantileTransformer(output_distribution="normal",
                                        n_quantiles=1000, subsample=200_000,
                                        random_state=seed), BOUNDED),
    ])
    # Whitening is the part people skip. PCA with whiten=True decorrelates the
    # features and equalises component variance, which removes the triple
    # counting of the spend axis. Without it, the clusters found below are
    # spend tiers; with it, they separate on cadence and discount too.
    return Pipeline([
        ("pre", pre),
        ("pca", PCA(n_components=n_components, whiten=True,
                    random_state=seed)),
    ])

Seven components retain 94.2% of the variance of the 15 transformed columns. Dropping the last eight components is not only a speed optimisation: those components are dominated by the noisiest features, and clustering in the full space gives a bootstrap ARI of 0.71 against 0.89 in the whitened 7-dimensional space.

The Naive Baseline

Two baselines, because the interesting failure is not the hand-drawn one.

Baseline 1: the 2023 workshop tiers. Five rules on lifetime spend and days since last order. This is what production runs today.

# The incumbent. Worth implementing honestly rather than strawmanning, because
# it is the thing the new model has to beat on business metrics.
import numpy as np


def workshop_tiers(f):
    spend, rec, freq = f["monetary_total"], f["recency_days"], f["frequency"]
    return np.select(
        [(spend >= 500) & (rec <= 90),
         (freq >= 3) & (rec <= 90),
         (rec > 180),
         (f["tenure_days"] <= 60)],
        ["vip", "loyal", "lapsed", "new"],
        default="everyone_else")

It produces tiers holding 3.1%, 11.4%, 46.8%, 7.2%, and 31.5% of customers. lapsed and everyone_else together are 78% of the base and neither is a description of anything. Forward 90 day revenue ratio between the best and worst tier is 6.2x, which is not nothing: recency is genuinely predictive and the tiers do capture it. Revenue per email is $0.31.

Baseline 2: K-Means on raw features. Five clusters, no transform, StandardScaler only. This is the baseline that teaches the lesson.

# K-Means with the standard-issue preprocessing everyone reaches for first.
# This does not error, does not warn, and produces a table that looks like a
# result.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(features.to_numpy())
km = KMeans(n_clusters=5, n_init=10, random_state=11).fit(X)
sizes = np.bincount(km.labels_) / len(X)
print(np.round(np.sort(sizes)[::-1], 4))
# [0.9131 0.0722 0.0128 0.0018 0.0001]
print(round(silhouette_score(X[:50_000], km.labels_[:50_000]), 4))
# 0.1064

One cluster holds 91.3% of customers. The smallest holds 212 people, all of them wholesale accounts that should have been filtered out upstream. The silhouette is 0.106, which on Rousseeuw’s original scale means essentially no structure. Bootstrap ARI is 0.41: refit on a resample and more than half the pairwise co-membership decisions change.

The diagnosis is entirely in the skew. K-Means minimises squared distance, the squared distance is dominated by the monetary tail, so four of the five available clusters get spent describing the top 8.7% of spenders and everyone else lands in one undifferentiated blob. The model did its job. We gave it the wrong geometry.

Key Insight

A 91% cluster is not a sign that the customer base is homogeneous. It is nearly always a sign that one feature's tail is eating the distance metric. Before reaching for a different algorithm, check the size distribution of the clusters and the skew of the inputs: DBSCAN and Gaussian mixtures fail the same way on the same data, and a rank transform fixes all three at once.

The Solution

The approach has four parts, and the clustering algorithm is the least interesting of them: rank-transform and whiten the feature space, choose k by resampling stability rather than by the elbow, fit MiniBatchKMeans with k-means++ seeding, then profile and name the segments against a held-out forward window.

The analogy for k-means++ is worth having before the code. Plain random initialisation is like dropping six flags on a map with your eyes closed: two often land in the same city and a whole region gets none, and Lloyd’s iterations cannot recover because each flag only ever moves to the mean of what is already nearest it. k-means++ drops the first flag at random and then drops each subsequent flag with probability proportional to squared distance from the nearest existing flag, so flags spread out. Arthur and Vassilvitskii’s 2007 result is that this gives an expected O(log k) approximation to the optimal inertia, and in practice it is the difference between needing n_init=50 and needing n_init=10.

Choosing k

This is where most segmentation projects go wrong, and the reason is that the three standard methods disagree on this data.

The elbow method plots inertia against k and looks for the bend. Here inertia falls smoothly and the bend is somewhere between 4 and 9 depending on the aspect ratio of the plot. The elbow method is not a method; it is a plot people interpret to agree with what they already wanted.

Silhouette peaks at k=2, which is the most common silhouette failure. Silhouette rewards well-separated compact clusters, and the cleanest separation in almost any retail dataset is one-time buyers versus repeat buyers. It is a real finding and a useless segmentation, because we already knew and because two segments cannot fill six campaign tracks.

The gap statistic (Tibshirani, Walther, Hastie, 2001) compares observed inertia against inertia on uniform reference data with the same bounding box, which corrects for the fact that inertia always falls. It suggests 6 here.

The method we actually decide on is bootstrap stability, because it maps directly to the constraint that matters: segments must survive a refit.

# k selection by resampling stability. For each k, bootstrap the customers,
# refit the ENTIRE pipeline including the transform, and measure agreement
# with the reference partition on the customers both fits saw.
import numpy as np
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import adjusted_rand_score


def stability_curve(F, k_values=range(2, 11), n_boot=25, sample=150_000,
                    seed=11):
    rng = np.random.default_rng(seed)
    out = {}
    for k in k_values:
        idx0 = rng.choice(len(F), sample, replace=False)
        ref_pipe = build_transform(n_components=7, seed=seed)
        ref_km = MiniBatchKMeans(n_clusters=k, n_init=10, batch_size=4096,
                                 random_state=seed)
        ref_lab = ref_km.fit_predict(ref_pipe.fit_transform(F.iloc[idx0]))
        scores = []
        for b in range(n_boot):
            idx = rng.choice(len(F), sample, replace=True)
            pipe = build_transform(n_components=7, seed=seed + b + 1)
            km = MiniBatchKMeans(n_clusters=k, n_init=10, batch_size=4096,
                                 random_state=seed + b + 1)
            lab = km.fit_predict(pipe.fit_transform(F.iloc[idx]))
            # Compare only on customers present in both, mapping the
            # reference labels through the shared index.
            shared, a_pos, b_pos = np.intersect1d(idx0, idx,
                                                  return_indices=True)
            if len(shared) > 1000:
                scores.append(adjusted_rand_score(ref_lab[a_pos],
                                                  lab[b_pos]))
        out[k] = (float(np.mean(scores)), float(np.std(scores)))
    return out
k Bootstrap ARI Silhouette Smallest segment Gap statistic Verdict
2 0.94 0.42 31.2% 0.18 Stable, real, unusable: one-time vs repeat
3 0.91 0.34 18.7% 0.24 Stable, still just a spend ladder
4 0.90 0.29 12.1% 0.31 Viable, misses discount axis
5 0.84 0.30 9.4% 0.36 Viable
6 0.89 0.31 6.1% 0.41 Chosen
7 0.72 0.28 4.8% 0.39 Unstable: 7th segment splits inconsistently
8 0.61 0.27 2.2% 0.37 Fails minimum size and stability

The stability curve is not monotone, and that non-monotonicity is the signal. ARI dips at k=5 and recovers at k=6, which is the fingerprint of a genuine sixth group: at k=5 the algorithm has to fold that group into a neighbour, and which neighbour it picks depends on the resample. At k=7 there is no seventh group to find, so the extra centroid carves an arbitrary line through an existing cluster and the line moves every time.

We take k=6. Both of the other defensible candidates (4 and 6) satisfy the constraints; 6 wins because it is the largest k that holds ARI above 0.80 while keeping every segment above the 4% floor, and because at k=4 the discount-driven group is not separated and that group is the whole reason marketing wanted this.

Fitting at 2.1M rows

Full-batch KMeans on 2.1M by 7 is feasible but wasteful. MiniBatchKMeans converges to a near-identical solution in a fraction of the time by updating centroids from small random batches, at the cost of a slightly higher final inertia.

# Final fit. MiniBatchKMeans over 2.1M customers in the whitened 7-d space.
from sklearn.cluster import MiniBatchKMeans
from sklearn.pipeline import Pipeline

K = 6

pipeline = Pipeline([
    ("space", build_transform(n_components=7, seed=11)),
    ("kmeans", MiniBatchKMeans(
        n_clusters=K,
        init="k-means++",
        # n_init applies to the seeding trials. 10 is enough with k-means++;
        # with init="random" this problem needs 40 or more to stop landing in
        # a local optimum where two centroids share a region.
        n_init=10,
        batch_size=4096,
        # Stop when 15 consecutive batches fail to improve inertia. The
        # default of None disables early stopping and wastes most of the run.
        max_no_improvement=15,
        reassignment_ratio=0.005,
        max_iter=300,
        random_state=11,
    )),
])

labels = pipeline.fit_predict(features)

On a 2.1M by 15 input this fits in 47 seconds on one core against 6 minutes 40 seconds for full-batch KMeans, and the resulting partitions agree at ARI 0.97. reassignment_ratio=0.005 is the one non-obvious parameter: it controls how aggressively low-count centroids get moved to high-variance regions, and the default 0.01 is too eager on skewed data, producing exactly the tiny-cluster churn we are trying to avoid.

Profiling, which is where the segmentation becomes usable

A label from 0 to 5 is not a segment. The deliverable is a table a copywriter can read.

# Profile segments against the population, in original units, plus the
# forward-window columns the clustering never saw.
def profile(features, labels, forward):
    df = features.copy()
    df["segment"] = labels
    med = features.median()
    rows = []
    for s in sorted(df["segment"].unique()):
        sub = df[df["segment"] == s]
        row = {"segment": s, "share": len(sub) / len(df)}
        for c in ["recency_days", "frequency", "avg_order_value",
                  "discount_rate", "mean_interorder_days",
                  "category_entropy"]:
            # Index against the population median so a marketer reads "2.4x
            # the typical discount rate" rather than an absolute they have no
            # reference for.
            row[c + "_idx"] = round(sub[c].median() / med[c], 2)
        fwd = forward.reindex(sub.index)
        row["fwd_90d_rev"] = round(fwd["revenue_90d"].mean(), 2)
        row["fwd_order_rate"] = round((fwd["orders_90d"] > 0).mean(), 4)
        rows.append(row)
    return pd.DataFrame(rows)
Segment Share Recency idx Freq idx AOV idx Discount idx Forward 90d rev Name
0 28.4% 3.41 0.42 0.78 0.91 $4.20 Dormant single-purchase
1 19.1% 0.34 2.86 0.71 2.44 $38.60 Discount-driven frequent
2 17.3% 0.51 1.94 2.31 0.38 $47.50 Full-price loyalists
3 15.7% 0.88 0.74 1.12 1.06 $16.90 Occasional mainstream
4 13.4% 0.29 0.61 0.94 1.18 $21.30 Recently acquired
5 6.1% 0.44 4.72 3.88 0.44 $126.40 High-value replenishers

The spread in forward 90 day revenue between segment 0 and segment 5 is 30.1x, against 6.2x for the workshop tiers. Segments 1 and 2 have almost identical order frequency and nearly opposite discount behaviour, which is the distinction the incumbent tiers could not see and the one that turned into the largest campaign win.

Key Insight

The decision that mattered most was not k, and it was not the algorithm. It was whitening after the rank transform. Without whiten=True the three correlated spend features contribute their shared variance three times and the six clusters come out as six spend tiers, ordered, with a forward revenue spread of 9.4x and no discount axis at all. With whitening, the same k and the same algorithm find the discount-driven and full-price groups at comparable spend levels, which is where the incremental revenue came from. The clustering algorithm was never the lever; the geometry was.

Evaluation and Metrics

Clustering evaluation splits into three questions that get conflated constantly: is the partition internally coherent, is it reproducible, and does it separate on anything anyone cares about. Internal metrics answer only the first.

Silhouette (Rousseeuw, 1987) scores each point as (b - a) / max(a, b) where a is mean distance to points in its own cluster and b is mean distance to points in the nearest other cluster. It runs from -1 to 1. Above 0.5 means strong separation, 0.25 to 0.5 means real but overlapping structure, below 0.2 means essentially none. Retail behavioural data lives at 0.25 to 0.35 and that is normal, because customer behaviour is a continuum with density variations rather than six separate islands. Anyone reporting a silhouette of 0.8 on customer data has either found a data artefact or clustered on an ID column.

Two caveats on silhouette that matter in practice. It is O(n^2) in memory, so it must be computed on a subsample; 50,000 points gives a stable estimate here with a standard error of about 0.004. And it must be computed in the same space the clustering used. Computing silhouette on raw features for a model fitted on whitened components measures nothing.

Davies-Bouldin and Calinski-Harabasz are cheap alternatives, both biased toward the spherical equal-variance clusters that K-Means produces anyway, which makes them poor tools for comparing K-Means against a density-based method.

# The full evaluation battery: internal coherence, reproducibility, and
# held-out separation. The third is the only one a stakeholder should see.
import numpy as np
from sklearn.metrics import (adjusted_rand_score, calinski_harabasz_score,
                             davies_bouldin_score, silhouette_score)


def evaluate_segmentation(Z, labels, forward, sample=50_000, seed=11):
    rng = np.random.default_rng(seed)
    idx = rng.choice(len(Z), min(sample, len(Z)), replace=False)
    sizes = np.bincount(labels) / len(labels)
    fwd = forward["revenue_90d"].to_numpy()
    means = np.array([fwd[labels == s].mean() for s in range(labels.max() + 1)])
    return {
        "silhouette": round(float(silhouette_score(Z[idx], labels[idx])), 4),
        "davies_bouldin": round(float(davies_bouldin_score(Z[idx],
                                                           labels[idx])), 4),
        "calinski_harabasz": round(float(
            calinski_harabasz_score(Z[idx], labels[idx])), 1),
        "largest_share": round(float(sizes.max()), 4),
        "smallest_share": round(float(sizes.min()), 4),
        # The number that says the partition separates on something real:
        # between-segment variance in a window the model never saw, as a
        # share of total variance. This is R-squared of the segment label as
        # a one-hot predictor of forward revenue.
        "fwd_variance_explained": round(float(
            1 - ((fwd - means[labels]) ** 2).sum()
            / ((fwd - fwd.mean()) ** 2).sum()), 4),
        "fwd_spread_ratio": round(float(means.max() / max(means.min(), 0.01)),
                                  2),
    }

Baseline versus solution

Metric Workshop tiers K-Means raw (k=5) K-Means transformed (k=6)
Silhouette (own space) 0.09 0.106 0.312
Bootstrap ARI (50 resamples) 1.00 (rules are deterministic) 0.41 0.89
Largest segment share 46.8% 91.3% 28.4%
Smallest segment share 3.1% 0.01% 6.1%
Forward 90d revenue spread 6.2x 4.1x 30.1x
Forward revenue variance explained 0.031 0.019 0.094
Revenue per email (A/B, 6 weeks) $0.31 not shipped $0.38

The workshop tiers score a perfect bootstrap ARI, and that row is a useful reminder of what stability does and does not buy. Fixed thresholds are perfectly reproducible and still poor: stability is necessary, not sufficient, which is why it is read alongside the forward-window separation rather than on its own.

The revenue per email number is the only one that mattered to the business, and it came from a 6 week split test: 400,000 customers held on the incumbent tiers, 400,000 on the new segments, same send calendar, same creative budget. $0.31 to $0.38 is a 22.6% lift with a 95% interval of 14% to 31%. Note that this tests segments plus new creative together. Isolating the segmentation would need the same creative sent to both, which marketing declined, so the honest claim is that the bundle lifted revenue and the segmentation was a necessary part of the bundle.

Metric That Matters

The signal that catches a silent regression is month-over-month segment migration rate after centroid matching. Steady state on this data is 8.2% of customers changing segment per month, which is real behaviour: people lapse, people return. When a feature pipeline breaks (an upstream column starts arriving null, a currency changes, a tracking script drops sessions), migration jumps to 30% or more within one refit while silhouette, inertia, and every other internal metric stay completely normal, because the clustering is still perfectly coherent on the corrupted features. Migration rate is the only cheap metric that notices.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
One cluster holds 90% of customers Heavy-tailed monetary features dominate squared Euclidean distance after z-scoring Cluster size distribution; skewness above 3 on any input QuantileTransformer or log1p before scaling; cap or segment out wholesale accounts
Segments are just spend tiers Correlated spend features triple-count the same axis Correlation matrix of inputs; profile table ordered monotonically on every column PCA with whiten=True, or drop derived features that are products of others
Labels change meaning every refit K-Means label integers are arbitrary and reassigned on each fit Segment 3 is 28% of the base one month and 6% the next Match new centroids to old with the Hungarian algorithm on the cost matrix of centroid distances, then relabel
k chosen by elbow, unreproducible Inertia falls monotonically; the bend is in the reader’s eye Two analysts reading the same plot pick different k Bootstrap ARI curve plus a hard operational ceiling on k
Silhouette picks k=2 The strongest real separation is one-time versus repeat buyers Silhouette maximal at the smallest non-trivial k Treat k=2 as a known structural fact, exclude it from the search range, select on stability
Segment quality validated on training features Reporting that segments differ on the columns they were clustered on Reported separation is on the same window as the features Evaluate on a strictly forward window the clustering never saw
Outliers become their own segments K-Means minimises squared distance, so extreme points pull centroids hard Clusters with fewer than 0.1% of customers Filter B2B and wholesale upstream; winsorise at the 99.9th percentile before transforming
Recency dominates after a seasonal peak A December refit finds everyone recent; the recency axis collapses Recency variance drops sharply in the refit Compute recency relative to a seasonally adjusted baseline, or refit on a trailing 12 month window
Common Pitfall

The mistake that produces the most wasted quarters is trusting the narrative. A clustering always returns clusters, and a profile table always shows differences, so there is always a story: segment 2 is "the aspirational browser", segment 4 is "the loyal bargain hunter". These names feel like findings. Run the identical pipeline on shuffled features, where each column is independently permuted so all joint structure is destroyed, and you will still get six clusters with a profile table showing 2x index differences and a silhouette near 0.19. The shuffled control is a ten line change and it is the fastest way to find out whether the partition is structure or just geometry. Real structure on this data shows bootstrap ARI 0.89 against 0.22 on the shuffled control.

Scaling and Productionizing

The compute is trivial and the operations are not. Nothing about a monthly K-Means refit is hard except keeping the segments meaning the same thing as last month.

The label matching problem

K-Means assigns integer labels in whatever order the centroids happen to converge. Refit next month and “segment 3” is a different group. Every downstream artefact, the campaign calendar, the CRM audience definitions, the dashboards, breaks silently, because the labels are still valid integers.

# Match refitted centroids to the previous month's so labels keep meaning.
# Without this step a monthly refit is indistinguishable from a random
# relabelling as far as every downstream consumer is concerned.
import numpy as np
from scipy.optimize import linear_sum_assignment


def match_centroids(prev_centroids, new_centroids):
    # Cost is Euclidean distance in the shared whitened space. Requires the
    # transform to be FROZEN across refits, otherwise the two centroid sets
    # live in different spaces and the assignment is meaningless.
    cost = np.linalg.norm(new_centroids[:, None, :] - prev_centroids[None],
                          axis=2)
    new_idx, prev_idx = linear_sum_assignment(cost)
    mapping = {int(n): int(p) for n, p in zip(new_idx, prev_idx)}
    # Matched distance above this threshold means the segment genuinely moved
    # rather than being relabelled. Escalate rather than silently remap.
    drift = {mapping[int(n)]: float(cost[n, p])
             for n, p in zip(new_idx, prev_idx)}
    return mapping, drift

That code only works if the transform is frozen. This is the single most important production decision in the whole pipeline: refit the centroids monthly, refit the QuantileTransformer and PCA quarterly at most, and treat a transform refit as a version bump requiring a full reprofile. Refitting the transform every month means the space itself moves, centroid distances between months are not comparable, and the Hungarian matching silently produces nonsense.

Retraining cadence and cost

Feature build:     9.4M orders, 41M sessions   -> 6 min on Spark, 12 executors
Transform fit:     200k subsample x 15 cols     -> 11 s
MiniBatchKMeans:   2.1M x 7                     -> 47 s, single core
Assignment:        2.1M x 7 argmin over 6       -> 0.8 s
Stability check:   25 bootstraps x 150k         -> 14 min
Total refit:                                    -> ~22 min, monthly
Model artefact:    6 x 7 centroids + transform  -> 1.4 MB pickled

The stability check is 63% of the runtime and the first thing people cut. It is also the only part that would catch the pipeline having quietly broken, so it stays.

Monitoring

Four signals, in priority order:

  • Segment migration rate after centroid matching. Baseline 8.2% per month, alert above 18%.
  • Matched centroid drift distance, per segment. A segment whose matched centroid moves more than 0.4 units in the whitened space has changed meaning and needs a reprofile before campaigns go out.
  • Population share per segment, with a control chart. A segment drifting from 6.1% to 2% over four months fails the minimum size constraint before anyone notices the campaign it feeds is underpowered.
  • Input feature distribution drift, per column, by KS statistic against the transform’s fit window. This is the signal that fires first when an upstream table breaks, and it fires before migration rate does.

The failure mode none of these catch is a correct clustering of a changed business. After a subscription product launches, mean_interorder_days becomes bimodal and the six segments stay stable, coherent, and increasingly irrelevant, because the new axis of variation is subscription versus one-off and no feature encodes it. The only defence is the quarterly reprofile with a human reading the table and asking whether these are still the groups the business has.

Real World

Netflix has publicly described organising its members into roughly 2,000 "taste communities" rather than demographic segments, used for row ordering and artwork selection, and the interesting part for this problem is the k: 2,000 is only viable because the consumer of the segments is an algorithm, not a copywriter, so the operational ceiling that caps us at 6 does not apply. At the infrastructure end, faiss.Kmeans from Meta's FAISS library is the standard tool for the same algorithm at billion-vector scale, where it trains the coarse quantiser for IVF indexes; it implements exactly Lloyd's algorithm with k-means++ style seeding, on GPU, with the same spherical-cluster assumption and the same sensitivity to input scaling that this post is about.

Key Insight

In production the clustering model is the small half of the system. The centroids are 1.4 MB and fit in 47 seconds; the frozen transform, the Hungarian label matching, and the migration monitor are what make the segments usable for two consecutive quarters. Teams that ship the notebook and skip those three pieces do not get a worse segmentation, they get a segmentation that quietly stops meaning anything in month three.

Alternative Approaches

Approach Segment quality here Cost at 2.1M Interpretability Best-fit scenario
RFM quintile rules Weak: 6.2x forward spread, 78% in two cells Seconds, no fitting Highest: thresholds are readable Small teams, no data science support, need something today
K-Means on rank-transformed features Good: 30.1x spread, ARI 0.89 47 s High: centroids readable in original units Default choice for tabular behavioural segmentation
Gaussian mixture (full covariance) Comparable, ARI 0.81, elongated clusters found 4 min, 7x slower Medium: soft membership is honest but harder to brief When customers genuinely sit between segments and you want probabilities
Hierarchical (Ward, on 50k subsample) Comparable at the top of the tree, ARI 0.77 18 min on 50k, O(n^2) memory Highest: the dendrogram shows nesting When you need nested segments, or k is genuinely unknown
DBSCAN / HDBSCAN Poor: 61% marked noise at every eps tried 9 min Low: no centroids, eps unintuitive Arbitrary shapes and genuine outlier rejection, not continuum data
Deep embedded clustering (autoencoder plus K-Means) Marginal: ARI 0.84, spread 31.4x 40 min on GPU, plus tuning Lowest: latent dims not nameable Very high dimensional inputs such as sequences or images

K-Means on rank-transformed, whitened features is the right default and it is not close. The margin over the Gaussian mixture is small on quality and large on everything else: centroids translate back to “median discount rate 2.4x population”, a full-covariance GMM gives you a 7 by 7 matrix per component that no marketer will ever read, and the extra flexibility mostly buys the ability to fit elongated clusters that we do not have evidence exist here.

Two conditions would change the answer. If customers genuinely sit between segments and the business wants to act on that (targeting the 30% most confidently in segment 5 rather than all of segment 5), the GMM’s posterior probabilities are the right object and worth the interpretability cost. And if the segment consumer becomes a ranking or recommendation model rather than a human, the operational ceiling on k disappears, at which point a two-tower embedding model with thousands of implicit clusters dominates and this whole framing is the wrong one.

Key Takeaways

  • Stability replaces accuracy. With no ground truth, bootstrap ARI across resamples of the data is the closest thing to a validation metric, and it has to be measured by refitting the entire pipeline on resampled customers, not by reseeding the optimiser.
  • The geometry is the model. Rank transformation plus PCA whitening moved bootstrap ARI from 0.41 to 0.89 and forward revenue spread from 4.1x to 30.1x. The algorithm and k never changed. Feature space work dominates algorithm choice in clustering far more than in supervised learning.
  • Correlated features are a silent reweighting. K-Means cannot down-weight a feature. Putting monetary_total, frequency, and avg_order_value in together triple-counts one axis, and the output is a spend ladder that looks like a multi-dimensional segmentation.
  • Every k selection heuristic disagrees, so decide on the one tied to a constraint. Elbow says 4 to 9, silhouette says 2, gap says 6, stability says 6. Stability wins because “segments must survive a refit” is an actual operational requirement and “the plot has a bend” is not.
  • A 90% cluster means skew, not homogeneity. It is the most common clustering failure and it is nearly always fixed at the transform, not by changing algorithm.
  • Label matching is mandatory, not polish. Integer labels are arbitrary per fit. Without Hungarian matching against the previous centroids, every monthly refit is a random relabelling from the perspective of every downstream system.
  • Freeze the transform, refit the centroids. Refitting the QuantileTransformer and PCA monthly makes centroid distances incomparable between months and breaks the matching that keeps segments meaningful.
  • Validate on a forward window. Showing that segments differ on the features they were clustered on is a tautology. Showing they differ on the next 90 days of behaviour is a result.

The counter-intuitive lesson is that the shuffled-feature control is the most valuable ten lines in the project. Permute every column independently, destroying all joint structure, and K-Means still returns six clusters with a silhouette of 0.19 and a profile table full of 2x differences that any competent analyst could narrate into a strategy deck. The clustering literature spends its energy on better algorithms and better k heuristics. The practical risk on a real segmentation project is not choosing k=6 when the truth was 7; it is shipping a partition of noise with a compelling story attached, and the only reliable defence is a control that has no structure in it by construction.

Frequently Asked Questions

Q: Why not just use RFM quintiles? It is simpler and every retail team understands it.

A: For a team with no data science capacity, RFM is genuinely the right call and you should ship it this week. Its two real limits are that 125 cells is not an operating model, so somebody collapses them by hand into arbitrary tiers, and that quintiles are computed per feature independently, so RFM cannot represent an interaction. The discount-driven frequent segment and the full-price loyalist segment sit in overlapping RFM cells and got 6.2x forward spread from the tiers against 30.1x from the clustering, which is almost entirely that one distinction.

Q: Why not a Gaussian mixture model, given customer behaviour is a continuum rather than six islands?

A: The premise is right, and a GMM is the more honest model of a continuum because it returns posterior probabilities rather than hard assignments. It scored ARI 0.81 against K-Means’ 0.89 here and cost 7x the fit time. The reason we did not ship it is that nothing downstream could consume soft membership: the CRM takes one audience label per customer, so the first thing production would do is argmax the posterior and discard the information the GMM exists to provide. If the activation layer could use probabilities, the GMM becomes the better choice.

Q: Why is the silhouette only 0.31? That seems bad.

A: It is normal and slightly better than typical for retail behavioural data. Silhouette above 0.5 requires genuinely separated clusters with gaps between them, and customer behaviour does not have gaps; it has a continuous density with variations. A high silhouette on customer data is usually a warning sign that an identifier, a near-duplicate feature, or a hard business rule already baked into the data is being recovered. The metric to judge this partition on is the 0.89 bootstrap ARI and the 30.1x forward separation, not the silhouette.

Q: How do you know the segments are not just an artefact of choosing k=6?

A: Two checks. The stability curve is non-monotone, dipping at k=5 and recovering at k=6, which is the signature of a real group being forced to merge at the lower k rather than an arbitrary cut being made at the higher one. And the shuffled-feature control, where all joint structure is destroyed, gives ARI 0.22 at the same k=6 against 0.89 on real data. If k=6 were producing structure by construction, the control would score highly too.

Q: What breaks first in production, and how would you know?

A: An upstream feature silently changing, and you would know from the segment migration rate, not from any clustering metric. When the sessions table started dropping mobile events, sessions_per_order shifted for 40% of customers, migration jumped from 8.2% to 34% in one refit, and silhouette, inertia, and Davies-Bouldin were all completely normal, because the model was still perfectly coherent on the broken features. Migration rate after centroid matching plus per-column KS drift are the two monitors that matter.

Q: Should k be refit every month along with the centroids?

A: No. Refit centroids monthly, re-examine k quarterly with a human in the loop, and treat any change in k as a new model version with a full reprofile and a rebuilt campaign calendar. Letting an automated selection move k from 6 to 7 between months produces a seventh segment nobody has creative for, invalidates the Hungarian matching against the previous six centroids, and delivers no measurable benefit given the stability curve is flat between 4 and 6.

Interview Questions

Q: You run K-Means with k=5 on customer data and one cluster contains 91% of the rows. Walk me through your diagnosis.

Expected depth: Identify skew in monetary and count features as the first hypothesis, explain why squared Euclidean distance under StandardScaler lets a heavy tail dominate the objective, and name the fix order: inspect skewness and cluster size distribution, apply log1p or QuantileTransformer, remove B2B and wholesale outliers upstream. Strong answers note that switching to DBSCAN or a GMM does not help because the geometry, not the algorithm, is the problem, and that the same fix resolves all three.

Q: How do you choose k when the elbow plot is ambiguous and silhouette peaks at 2?

Expected depth: Enumerate elbow, silhouette, gap statistic (Tibshirani et al., comparison against a uniform reference distribution with the same bounding box), and resampling stability via bootstrap ARI. Explain why inertia falls monotonically in k so the elbow is not a criterion, and why silhouette favours the coarsest real split. The senior answer is that k is jointly a statistical and operational decision, and that a non-monotone stability curve, where ARI dips at k and recovers at k+1, is positive evidence for a genuine group at k+1.

Q: What breaks when you refit a K-Means segmentation monthly, and how do you fix it?

Expected depth: Cluster label integers are arbitrary per fit, so downstream audiences, dashboards, and campaign definitions break silently. Fix is bipartite matching of new centroids to old (Hungarian algorithm, scipy.optimize.linear_sum_assignment) on the centroid distance matrix. Critically, this requires the preprocessing transform to be frozen across refits, since otherwise the centroid sets live in different spaces. Best answers add that matched centroid drift distance is itself a monitoring signal, distinguishing a relabelled segment from a segment that genuinely moved.

Q: Your stakeholder asks whether the segments are real. There is no ground truth. What do you show them?

Expected depth: Three distinct evidence types. Reproducibility via bootstrap ARI on resampled customers with the full pipeline refit. Held-out separation on a forward time window the clustering never saw, so the separation is not circular. And a negative control: the same pipeline on independently permuted features, which should destroy stability (0.22 versus 0.89) while still producing a narratable profile table. Mentioning the negative control unprompted is the signal that someone has actually shipped a segmentation.

Q: When would you not use K-Means for segmentation?

Expected depth: Non-spherical or very unequal-variance clusters (K-Means assumes isotropic equal spread because centroids are means); genuine outlier rejection needed, which favours HDBSCAN; soft membership required downstream, which favours a GMM; mixed categorical and numerical features where Euclidean distance on one-hot columns is not meaningful, which favours k-prototypes or Gower distance with a medoid method; and very high dimensional inputs where distance concentration makes all points equidistant, which needs representation learning first. Strong answers note that K-Means’ equal-size bias means it will split one large cluster before isolating a small distinct one.

View full code for this problem