TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 3: Customer Segmentation

Project 3: Customer Segmentation

An online shop's marketing team wants to stop sending the same newsletter to everyone. They have no labels, only the order history: who bought what, when, and for how much. The question is unsupervised: which groups of customers behave alike, how many such groups are there, and how do customers move between them over time? The level is beginner; the main skills are building features from a raw transaction log with pandas, transforming skewed features, choosing the number of clusters with silhouette scores and a stability check, comparing k-means with a Gaussian mixture, naming segments from their profiles, assigning new customers, and tracking segment movement from one half-year to the next.

You clustered customers before, in part B of the algorithms mini project: a ready-made table of customer features and k-means on it. Here the table does not exist yet. You build it from individual orders, decide what each feature means, check whether the clusters are real or an artefact of a random start, and use the segments the way a marketing team would: month after month, on customers who did not exist when the model was fitted.

Goal and success criteria

Clustering has no test set with right answers, so the criteria are about usefulness and reliability, agreed with the marketing team:

Criterion
Features recency, frequency and average basket per customer over a fixed 182-day window (RFM)
Number of segments between 3 and 6 (the team can run that many campaigns)
Separation mean silhouette of at least 0.35 on the chosen k (cluster evaluation)
Stability mean adjusted Rand index (ARI) of at least 0.9 between the full fit and fits on bootstrap samples
Interpretability every segment can be described in one sentence from its median recency, frequency and basket
Use the fitted model assigns customers in the next half-year without refitting; movements are reported

The data

Real order data comes from the shop's own database. It is personal data even without names (a customer id links to an account), so segmentation needs a purpose the customers were told about (the privacy notice), must respect opt-outs from marketing, and should not use sensitive attributes or infer them; see privacy, consent and licensing. A public example of a real log is the UCI Online Retail data set (a UK online gift retailer, December 2010 to December 2011, CC BY 4.0).

The generator writes a log of about 18,000 orders in 2024 for 870 customers of five hidden kinds, which the analysis does not see: regulars (about one order every two weeks), big occasional spenders (a few large orders), bargain hunters (frequent small orders), customers who stop buying at the end of April, and customers who join in September. Each customer has their own rate and basket size around their kind's average.

Step 1: from orders to one row per customer

One row per order is the wrong shape for clustering customers. The classic summary is RFM: recency (days since the last order), frequency (number of orders) and monetary value. Two choices matter:

  • A fixed window. Counting orders "since the customer joined" makes old customers look more frequent. Every snapshot uses the 182 days before its date, so that two snapshots are comparable.
  • Average basket instead of total spend. Total spend is roughly frequency times basket, so it would count frequency twice. The average basket adds new information: how much a customer spends per order.

Customers without an order in the window are not clustered: they are inactive, a business rule rather than a cluster.

python · try it yourself
import numpy as np
import pandas as pd

def make_transactions(seed=0):
    """Orders in 2024. Hidden kinds: (customers, orders per 30 days, log basket, first day, last day)."""
    rng = np.random.default_rng(seed)
    kinds = {"regular": (300, 2.2, 3.7, 0, 366), "big spender": (120, 0.5, 5.3, 0, 366),
             "bargain": (200, 3.0, 2.5, 0, 366), "lapsing": (150, 2.0, 3.8, 0, 120), "new": (100, 2.5, 3.8, 245, 366)}
    rows, truth, cid = [], {}, 1000
    for kind, (n, rate, mu, start, end) in kinds.items():
        for _ in range(n):
            cid += 1
            truth[cid] = kind
            k = rng.poisson(rate * rng.gamma(6, 1 / 6) * (end - start) / 30)
            day = rng.integers(start, end, k)
            basket = np.round(rng.lognormal(mu + rng.normal(0, 0.15), 0.35, k), 2)
            rows += zip([cid] * k, day, basket)
    tx = pd.DataFrame(rows, columns=["customer_id", "day", "amount"])
    tx["date"] = pd.Timestamp("2024-01-01") + pd.to_timedelta(tx.pop("day"), unit="D")
    return tx.sample(frac=1, random_state=seed, ignore_index=True), pd.Series(truth)

def rfm(tx, asof, days=182):
    asof = pd.Timestamp(asof)
    w = tx[(tx.date < asof) & (tx.date >= asof - pd.Timedelta(days=days))]
    g = w.groupby("customer_id").agg(last=("date", "max"), frequency=("amount", "size"), basket=("amount", "mean"))
    g["recency"] = (asof - g.pop("last")).dt.days
    return g[["recency", "frequency", "basket"]]

tx, truth = make_transactions()
print(f"{len(tx)} orders, {tx.customer_id.nunique()} customers, {tx.date.min().date()} to {tx.date.max().date()}")
print(tx.head(3).to_string(index=False))

r = rfm(tx, "2024-07-01")                                  # window: 1 Jan to 30 Jun
print(f"\nsnapshot 2024-07-01: {len(r)} active customers, {tx.customer_id.nunique() - len(r)} without an order in the window")
print(r.describe().round(1).to_string())
skew = lambda s: float(((s - s.mean()) ** 3).mean() / s.std() ** 3)
print("\nskewness raw:", {c: round(skew(r[c]), 2) for c in r})
print("skewness log:", {c: round(skew(np.log1p(r[c])), 2) for c in r})
18251 orders, 866 customers, 2024-01-01 to 2024-12-31
 customer_id  amount       date
        1589   10.02 2024-08-30
        1039   36.43 2024-04-04
        1360  204.64 2024-11-23

snapshot 2024-07-01: 759 active customers, 107 without an order in the window
       recency  frequency  basket
count    759.0      759.0   759.0
mean      34.3       12.0    62.0
std       37.1        7.8    70.1
min        1.0        1.0     8.0
25%        6.0        6.0    16.8
50%       17.0       11.0    42.3
75%       64.0       16.5    52.9
max      180.0       40.0   355.3

skewness raw: {'recency': 1.35, 'frequency': 0.76, 'basket': 2.19}
skewness log: {'recency': -0.1, 'frequency': -0.61, 'basket': 0.51}

The log has 18,251 orders from 866 customers (four of the 870 never ordered). On 1 July, 759 customers have at least one order in the window; the 107 others joined later in the year and do not exist yet for this snapshot. All three features are right-skewed: the median basket is 42.3 EUR but the mean is 62.0, pulled up by a few baskets above 300. On a log scale the skewness drops from 1.35, 0.76 and 2.19 to between −0.61 and 0.51. The log matters for clustering, because k-means would otherwise spend its clusters on the long tails (log and power transforms).

Step 2: how many segments?

Before running it on 800 customers, recall what k-means does on a small picture: two features of a toy set, three clusters, started from three points that sit in the same group. Step through: the centroids move to the means, points change sides, the inertia (the sum of squared distances to the centroids) falls until nothing changes. The result depends on where it starts, which is why the real fit uses several starts (n_init) and why Step 2 checks stability.

For the real data, the features are log-transformed (they are skewed) and standardised (k-means measures plain distances, so a feature with a larger spread would dominate; see which models need scaling). Then, for k from 2 to 7: the inertia (it always falls with k, so look for an elbow), the silhouette (how much closer each customer is to its own cluster than to the next one, from −1 to 1), and stability: refit on 15 bootstrap samples of the customers, assign everyone, and compare with the full fit by the adjusted Rand index (1 = the same partition, 0 = no better than chance). A k that is real gives the same clusters on resampled data; an arbitrary k cuts a blob differently each time.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler

def make_transactions(seed=0):
    rng = np.random.default_rng(seed)
    kinds = {"regular": (300, 2.2, 3.7, 0, 366), "big spender": (120, 0.5, 5.3, 0, 366),
             "bargain": (200, 3.0, 2.5, 0, 366), "lapsing": (150, 2.0, 3.8, 0, 120), "new": (100, 2.5, 3.8, 245, 366)}
    rows, truth, cid = [], {}, 1000
    for kind, (n, rate, mu, start, end) in kinds.items():
        for _ in range(n):
            cid += 1
            truth[cid] = kind
            k = rng.poisson(rate * rng.gamma(6, 1 / 6) * (end - start) / 30)
            day = rng.integers(start, end, k)
            basket = np.round(rng.lognormal(mu + rng.normal(0, 0.15), 0.35, k), 2)
            rows += zip([cid] * k, day, basket)
    tx = pd.DataFrame(rows, columns=["customer_id", "day", "amount"])
    tx["date"] = pd.Timestamp("2024-01-01") + pd.to_timedelta(tx.pop("day"), unit="D")
    return tx.sample(frac=1, random_state=seed, ignore_index=True), pd.Series(truth)

def rfm(tx, asof, days=182):
    asof = pd.Timestamp(asof)
    w = tx[(tx.date < asof) & (tx.date >= asof - pd.Timedelta(days=days))]
    g = w.groupby("customer_id").agg(last=("date", "max"), frequency=("amount", "size"), basket=("amount", "mean"))
    g["recency"] = (asof - g.pop("last")).dt.days
    return g[["recency", "frequency", "basket"]]

tx, _ = make_transactions()
r = rfm(tx, "2024-07-01")
Z = make_pipeline(FunctionTransformer(np.log1p), StandardScaler()).fit_transform(r)

rng = np.random.default_rng(0)
print(f"{'k':>2} {'inertia':>8} {'silhouette':>10} {'stability ARI':>14}")
for k in range(2, 8):
    full = KMeans(n_clusters=k, n_init=10, random_state=0).fit(Z)
    aris = []
    for b in range(15):
        idx = rng.integers(0, len(Z), len(Z))
        boot = KMeans(n_clusters=k, n_init=4, random_state=b).fit(Z[idx])
        aris.append(adjusted_rand_score(full.labels_, boot.predict(Z)))
    print(f"{k:>2} {full.inertia_:8.0f} {silhouette_score(Z, full.labels_):10.3f} "
          f"{np.mean(aris):8.3f} (min {np.min(aris):.2f})")
 k  inertia silhouette  stability ARI
 2     1181      0.415    0.971 (min 0.94)
 3      832      0.401    0.968 (min 0.92)
 4      646      0.391    0.987 (min 0.98)
 5      554      0.344    0.812 (min 0.68)
 6      476      0.346    0.747 (min 0.57)
 7      408      0.347    0.757 (min 0.53)

The inertia falls steadily with no sharp elbow, as usual. The silhouette is highest for k = 2 (0.415) and declines slowly to 0.391 at k = 4, then drops to about 0.345 from k = 5. Stability tells the clearest story: k = 4 gives the same partition on every bootstrap sample (mean ARI 0.987, never below 0.98), while from k = 5 the fits disagree (0.812, as low as 0.68): the fifth cluster cuts an existing group in a different place each time.

k = 2 is outside the team's range (3 to 6 campaigns). Of the rest, k = 4 has the best stability and a silhouette above the 0.35 criterion, so it is chosen.

Step 3: k-means or a Gaussian mixture, and what the segments are

k-means draws round clusters of similar size. A Gaussian mixture allows elongated, tilted clusters of different sizes and gives each customer a probability per segment. Fit both with the chosen k, compare them by ARI, and look at the BIC of the mixture for other k (lower is better; it penalises extra parameters). Then the step that makes segments useful: a profile of each one in the original units (median recency in days, orders, basket in euros), and a name.

Because the data is generated, there is one extra check you never have in practice: the ARI against the hidden kinds. It is printed last, and nothing is chosen with it.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.mixture import GaussianMixture
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler

def make_transactions(seed=0):
    rng = np.random.default_rng(seed)
    kinds = {"regular": (300, 2.2, 3.7, 0, 366), "big spender": (120, 0.5, 5.3, 0, 366),
             "bargain": (200, 3.0, 2.5, 0, 366), "lapsing": (150, 2.0, 3.8, 0, 120), "new": (100, 2.5, 3.8, 245, 366)}
    rows, truth, cid = [], {}, 1000
    for kind, (n, rate, mu, start, end) in kinds.items():
        for _ in range(n):
            cid += 1
            truth[cid] = kind
            k = rng.poisson(rate * rng.gamma(6, 1 / 6) * (end - start) / 30)
            day = rng.integers(start, end, k)
            basket = np.round(rng.lognormal(mu + rng.normal(0, 0.15), 0.35, k), 2)
            rows += zip([cid] * k, day, basket)
    tx = pd.DataFrame(rows, columns=["customer_id", "day", "amount"])
    tx["date"] = pd.Timestamp("2024-01-01") + pd.to_timedelta(tx.pop("day"), unit="D")
    return tx.sample(frac=1, random_state=seed, ignore_index=True), pd.Series(truth)

def rfm(tx, asof, days=182):
    asof = pd.Timestamp(asof)
    w = tx[(tx.date < asof) & (tx.date >= asof - pd.Timedelta(days=days))]
    g = w.groupby("customer_id").agg(last=("date", "max"), frequency=("amount", "size"), basket=("amount", "mean"))
    g["recency"] = (asof - g.pop("last")).dt.days
    return g[["recency", "frequency", "basket"]]

K = 4
tx, truth = make_transactions()
r = rfm(tx, "2024-07-01")
Z = make_pipeline(FunctionTransformer(np.log1p), StandardScaler()).fit_transform(r)

print("Gaussian mixture BIC:", {k: round(GaussianMixture(k, n_init=3, random_state=0).fit(Z).bic(Z)) for k in range(2, 8)})
km = KMeans(n_clusters=K, n_init=10, random_state=0).fit(Z)
gm = GaussianMixture(K, n_init=3, random_state=0).fit(Z)
print(f"k = {K}: ARI k-means vs mixture {adjusted_rand_score(km.labels_, gm.predict(Z)):.3f}; "
      f"mixture customers with max probability < 0.8: {(gm.predict_proba(Z).max(axis=1) < 0.8).mean():.1%}")
rng = np.random.default_rng(0)
boots = [GaussianMixture(K, n_init=3, random_state=b).fit(Z[rng.integers(0, len(Z), len(Z))]) for b in range(15)]
aris = [adjusted_rand_score(gm.predict(Z), m.predict(Z)) for m in boots]
print(f"mixture stability over 15 bootstraps: mean ARI {np.mean(aris):.3f} (min {np.min(aris):.2f}); "
      f"silhouette of its labels {silhouette_score(Z, gm.predict(Z)):.3f}")

def profile(labels):
    g = r.assign(segment=labels).groupby("segment")
    out = g.agg(customers=("recency", "size"), recency_days=("recency", "median"),
                orders=("frequency", "median"), basket_eur=("basket", "median"))
    out["recency_p10"] = g.recency.quantile(0.1)
    out["revenue_share"] = (r.frequency * r.basket).groupby(labels).sum() / (r.frequency * r.basket).sum()
    return out.round(2).to_string()

print("\nk-means profiles (medians, 182-day window to 2024-07-01):\n" + profile(km.labels_))
print("\nmixture profiles:\n" + profile(gm.predict(Z)))

hidden = truth.loc[r.index].to_numpy()
print("\nonly possible on generated data -- hidden kind by segment (k-means | mixture):")
print(pd.concat([pd.crosstab(hidden, km.labels_), pd.crosstab(hidden, gm.predict(Z))], axis=1,
                keys=["k-means", "mixture"]).to_string())
print(f"ARI with the hidden kinds: k-means {adjusted_rand_score(hidden, km.labels_):.3f}, "
      f"mixture {adjusted_rand_score(hidden, gm.predict(Z)):.3f}")
Gaussian mixture BIC: {2: 5733, 3: 5280, 4: 4722, 5: 4762, 6: 4799, 7: 4781}
k = 4: ARI k-means vs mixture 0.745; mixture customers with max probability < 0.8: 1.3%
mixture stability over 15 bootstraps: mean ARI 0.992 (min 0.96); silhouette of its labels 0.343

k-means profiles (medians, 182-day window to 2024-07-01):
         customers  recency_days  orders  basket_eur  recency_p10  revenue_share
segment
0              233          68.0     8.0       44.38         29.2           0.24
1              114          43.0     3.0      215.17          6.3           0.22
2              224           6.0    14.0       42.70          1.0           0.41
3              188           8.0    18.0       12.87          2.0           0.13

mixture profiles:
         customers  recency_days  orders  basket_eur  recency_p10  revenue_share
segment
0              201           9.0    17.0       12.90          2.0           0.13
1              112          38.0     3.0      216.03          6.0           0.22
2              276           9.0    13.0       42.95          2.0           0.47
3              170          74.0     7.0       46.64         63.0           0.17

only possible on generated data -- hidden kind by segment (k-means | mixture):
            k-means                mixture
col_0             0    1    2    3       0    1    2    3
row_0
bargain          12    0    1  187     200    0    0    0
big spender       0  109    2    0       0  111    0    0
lapsing         145    4    0    0       0    1    0  148
regular          76    1  221    1       1    0  276   22
ARI with the hidden kinds: k-means 0.688, mixture 0.913

Both methods prefer four groups: the mixture's BIC is lowest at k = 4 (4722). They agree on three segments (bargain hunters with about 13 EUR baskets, big occasional spenders around 215 EUR, regulars with frequent mid-size orders) but differ on the fourth. In k-means it holds 233 customers with a median recency of 68 days, but its 10th percentile is 29 days: it also takes in regulars who just had a quiet month. In the mixture it holds 170 customers whose recency is at least 63 days for 90 % of them, a group that is easy to describe in one sentence: "used to order every few weeks, nothing for over two months". The mixture is also stable (mean ARI 0.992 over 15 bootstraps) and confident (only 1.3 % of customers have no segment above 0.8 probability).

Its silhouette is 0.343, just under the 0.35 criterion. Silhouette rewards round, well-separated clusters, which is k-means's own objective, so the mixture is at a disadvantage by construction. The criterion is not quietly dropped: the write-up recommends the mixture, states that it misses the silhouette criterion by 0.007 and why, and the marketing team signs off on the deviation. (The hidden kinds, which you would not have, agree: ARI 0.913 for the mixture against 0.688 for k-means, which put 76 regulars into the "slipping" group.)

The names come from the profiles, segment by segment: bargain hunters (0: 201 customers, 17 orders, 12.90 EUR, 13 % of revenue), big occasional (1: 112 customers, 3 orders, 216 EUR, 22 %), regulars (2: 276 customers, 13 orders, 43 EUR, 47 % of revenue) and slipping away (3: 170 customers, last order 74 days ago). The segment numbers are arbitrary; the names live in code next to the fitted model and must be checked again after every refit.

Step 4: assign the next half-year, and follow the movements

The model is fitted once, on the July snapshot, and kept: the pipeline (log, scaler fitted on July, k-means) assigns customers in the January snapshot without refitting, so a segment means the same thing in both. Customers are then followed: where did July's segments go by January, who became inactive, and where do customers who did not exist in July land? Refitting every half-year would renumber and reshape the segments, and no movement could be read from that.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.mixture import GaussianMixture
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler

def make_transactions(seed=0):
    rng = np.random.default_rng(seed)
    kinds = {"regular": (300, 2.2, 3.7, 0, 366), "big spender": (120, 0.5, 5.3, 0, 366),
             "bargain": (200, 3.0, 2.5, 0, 366), "lapsing": (150, 2.0, 3.8, 0, 120), "new": (100, 2.5, 3.8, 245, 366)}
    rows, truth, cid = [], {}, 1000
    for kind, (n, rate, mu, start, end) in kinds.items():
        for _ in range(n):
            cid += 1
            truth[cid] = kind
            k = rng.poisson(rate * rng.gamma(6, 1 / 6) * (end - start) / 30)
            day = rng.integers(start, end, k)
            basket = np.round(rng.lognormal(mu + rng.normal(0, 0.15), 0.35, k), 2)
            rows += zip([cid] * k, day, basket)
    tx = pd.DataFrame(rows, columns=["customer_id", "day", "amount"])
    tx["date"] = pd.Timestamp("2024-01-01") + pd.to_timedelta(tx.pop("day"), unit="D")
    return tx.sample(frac=1, random_state=seed, ignore_index=True), pd.Series(truth)

def rfm(tx, asof, days=182):
    asof = pd.Timestamp(asof)
    w = tx[(tx.date < asof) & (tx.date >= asof - pd.Timedelta(days=days))]
    g = w.groupby("customer_id").agg(last=("date", "max"), frequency=("amount", "size"), basket=("amount", "mean"))
    g["recency"] = (asof - g.pop("last")).dt.days
    return g[["recency", "frequency", "basket"]]

NAMES = ["bargain hunters", "big occasional", "regulars", "slipping away"]   # from the Step 3 profiles
tx, _ = make_transactions()
july, january = rfm(tx, "2024-07-01"), rfm(tx, "2025-01-01")
model = make_pipeline(FunctionTransformer(np.log1p), StandardScaler(),
                      GaussianMixture(len(NAMES), n_init=3, random_state=0)).fit(july)

everyone = pd.Index(sorted(tx.customer_id.unique()))
before = pd.Series("not yet a customer", index=everyone)
first_order = tx.groupby("customer_id").date.min()
before[first_order < "2024-07-01"] = "inactive"
before[july.index] = [NAMES[c] for c in model.predict(july)]
after = pd.Series("inactive", index=everyone)
after[january.index] = [NAMES[c] for c in model.predict(january)]    # same model, no refit

print("segment sizes, July -> January:")
print(pd.DataFrame({"July": before.value_counts(), "January": after.value_counts()}).fillna(0).astype(int).to_string())
print("\nmovement (rows: July, columns: January):")
print(pd.crosstab(before, after).to_string())

new = pd.DataFrame([{"recency": 3, "frequency": 14, "basket": 38.0}, {"recency": 40, "frequency": 2, "basket": 310.0},
                    {"recency": 150, "frequency": 1, "basket": 25.0}])
print("\nthree customers entered by hand:", [NAMES[c] for c in model.predict(new)])
segment sizes, July -> January:
                    July  January
bargain hunters      201      200
big occasional       112      112
inactive               0      154
not yet a customer   107        0
regulars             276      380
slipping away        170       20

movement (rows: July, columns: January):
col_0               bargain hunters  big occasional  inactive  regulars  slipping away
row_0
bargain hunters                 199               0         0         1              1
big occasional                    0             106         6         0              0
not yet a customer                0               6         0       100              1
regulars                          1               0         0       259             16
slipping away                     0               0       148        20              2

three customers entered by hand: ['regulars', 'big occasional', 'slipping away']

The movement table is what the marketing team actually uses:

  • Slipping away was the right warning. Of the 170 customers in that segment in July, 148 placed no order at all in the second half-year; 20 came back as regulars. A win-back campaign in July would have targeted exactly the right group, and its success can be measured as the share that comes back (20 of 170 without any campaign is the baseline to beat).
  • Regulars mostly stay (259 of 276); 16 start slipping, and they are the next win-back list.
  • Bargain hunters and big occasional spenders are stable (199 of 201 and 106 of 112); 6 big spenders became inactive, which for customers with three orders in six months may simply be a long gap.
  • The 107 new customers from autumn land almost all in regulars (100), with 6 big spenders. The model had never seen them, and it does not need to: it assigns any RFM row.

The three hand-entered customers go to regulars, big occasional and slipping away, as their numbers suggest. Note what the model cannot do: it describes behaviour inside the window, not its causes, and it says nothing about whether a campaign changes anything. That needs an experiment (see the extensions).

Extensions

  • Add a fourth feature, such as the share of orders with a discount code or the number of product categories, and check whether silhouette and stability improve or the segments only get harder to name.
  • Try hierarchical clustering with Ward linkage on the same features and compare by ARI; read the dendrogram for a natural k.
  • Use DBSCAN to find customers that fit no segment (noise points), and look at who they are.
  • Measure whether segments are useful: send a different campaign per segment to a random half of each and compare with the other half (an A/B test), rather than trusting the profiles.
  • Schedule the snapshot monthly and track segment sizes as a dashboard; a sudden shift is a data problem or a market change (data drift).

Write-up template

text
Project: customer segments, <shop>, snapshot <date>
Data: order log <period>, <n> orders, <n> customers; privacy notice and opt-outs respected
Features: <window>, <features and why>, transforms
Choice of k: inertia <...>, silhouette <...>, stability ARI <...>; chosen k = <k> because <...>
Method: k-means vs mixture, ARI <x>; chosen <method>
Segments: <name>: <n> customers, <median recency, orders, basket>, <share of revenue>, <one-sentence description>
Movement: <main flows between snapshots>, inactive <n>, new <n>
Limits: segments describe behaviour in the window only; not causes; check usefulness with an A/B test

Practice

  1. Why does the project use a fixed 182-day window instead of each customer's full history?
Answer

With full histories, a customer who joined last month has few orders only because they are new, and old customers look more frequent and valuable simply because they have been around longer. The segments would partly measure tenure. A fixed window makes every customer's frequency, recency and basket comparable, and makes two snapshots comparable too, which the movement table needs.

  1. A colleague refits the clustering on the January snapshot and compares the labels with July's to measure movement. What goes wrong?
Answer

A new fit numbers the segments arbitrarily and places their boundaries differently (the scaler is refitted too), so "segment 2 in July" and "segment 2 in January" need not mean the same thing. Movements would partly be relabelling. Keep one fitted pipeline for the comparison; when you do refit (for example once a year), map the new segments to the old ones by their profiles and report the change.

  1. Remove the log transform (use only StandardScaler) in Step 2 and rerun. What do you expect, and why?
Answer

The basket has a long right tail (a few above 300 EUR), so in raw units the big spenders sit far from everyone else and dominate the distances. Expect clusters that split the tails (very large baskets, very high recency) and lump the bulk of customers together, a different silhouette profile, and less interpretable segments. Run it and compare the profiles with the table above.

Test yourself

Why is the average basket used instead of total spend?

  1. Total spend is not available in the log
  2. Total spend is roughly frequency times basket, so it would count frequency twice
  3. Averages are always more stable than sums
  4. k-means cannot use sums

For k = 5 the mean stability ARI over bootstrap samples drops to 0.812 (as low as 0.68), against 0.987 for k = 4. What does that indicate?

  1. k = 5 is better because it changes more
  2. The fifth cluster is not a stable structure in the data: it splits a group differently on each resample
  3. The bootstrap samples are too small
  4. ARI cannot be compared across k

The mixture is recommended although its silhouette (0.343) misses the 0.35 criterion. What makes this acceptable?

  1. Nothing; criteria can be changed whenever needed
  2. The deviation is reported with its reason (silhouette favours round clusters), the other criteria are met, and the team signs off
  3. The mixture has a higher BIC
  4. Silhouette does not apply to mixtures

Of 170 customers in 'slipping away' in July, 148 placed no order in the next six months. How should a win-back campaign be evaluated?

  1. By the share of customers who order again, compared with a similar group that did not receive the campaign
  2. By the silhouette of the segment
  3. By how many customers are in the segment
  4. It cannot be evaluated