Sub topic 6
Creating segments with clustering
This chapter shows how to turn customer behaviour into segments with k-means clustering. You will scale RFM features, choose the number of clusters, read the results and give each cluster a name that marketers can use. It assumes you can read basic pandas and scikit-learn code and know what recency, frequency and monetary value (RFM) features are from the previous chapter.
Why cluster at all
A rule-based segment such as "bought in the last 30 days and spent over 200" encodes what you already believe. A clustering algorithm looks at the data and proposes groups you did not define. This is called unsupervised learning, because there is no target column to predict. The algorithm only sees how similar customers are to each other.
Clustering suits three situations:
- You do not know how many natural groups exist.
- Behaviour spans many features, so hand-written thresholds are hard to maintain.
- You want a starting point to refine with business knowledge.
Clustering does not give you meaning. It returns numeric labels such as 0, 1 and 2. Interpretation, naming and the decision to use the segments are your job.
How k-means works
K-means is the most common clustering method for customer segmentation. You choose k, the number of clusters. The algorithm then repeats two steps:
- Assign every customer to the nearest centroid, which is the mean point of a cluster, using straight-line (Euclidean) distance.
- Move each centroid to the mean of the customers assigned to it.
It stops when assignments no longer change. The result depends on the starting centroids, so scikit-learn runs several starts (n_init) and keeps the best one. Fixing random_state makes your run repeatable.
Two properties of this method matter in practice:
- Distance drives everything. A feature with large numbers dominates the distance. Monetary value in the hundreds would swamp frequency in single digits unless you scale the features.
- Clusters are roughly round and similar in size. K-means struggles with long, thin or very uneven groups, and every customer must belong to some cluster, even outliers.
A first segmentation
The example below scales three RFM features and groups six customers into two clusters. It then averages each feature per cluster so you can read what each group looks like.
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
customers = pd.DataFrame({
"customer_id": [1, 2, 3, 4, 5, 6],
"recency_days": [3, 5, 40, 60, 2, 90],
"frequency": [12, 9, 3, 2, 15, 1],
"monetary": [540.0, 410.0, 120.0, 80.0, 700.0, 25.0],
})
features = customers[["recency_days", "frequency", "monetary"]]
scaled = StandardScaler().fit_transform(features)
model = KMeans(n_clusters=2, n_init=10, random_state=42)
customers["segment"] = model.fit_predict(scaled)
print(customers.groupby("segment")[["recency_days", "frequency", "monetary"]].mean())StandardScaler subtracts each column's mean and divides by its standard deviation, so every feature has mean 0 and spread 1. The customers fall into two groups: customers 1, 2 and 5, and customers 3, 4 and 6. Which group gets label 0 and which gets label 1 can change between runs and library versions.
| Group | Customers | Mean recency (days) | Mean frequency | Mean monetary |
|---|---|---|---|---|
| A | 1, 2, 5 | 3.3 | 12 | 550 |
| B | 3, 4, 6 | 63.3 | 2 | 75 |
Group A bought recently, often and for a lot of money. Group B has not bought for two months and spent little. A sensible name for A is "Active high-value" and for B is "Lapsing low-value".
Six rows is only a teaching example. In practice you need hundreds or thousands of customers per cluster you hope to find.
Prepare features before clustering
Poor input is the most common reason clustering fails. Check these points first.
Fix skewed distributions
Spend and frequency usually have a long right tail: most customers spend little and a few spend a great deal. K-means treats those extreme values as far-away points and may dedicate a whole cluster to a handful of them. A log transform reduces this. Use np.log1p, which handles zeros.
Scale every feature
Use StandardScaler after any transform. Fit the scaler on the data you segment. Keep the fitted scaler object, because you will need the same scaling to assign new customers later.
Avoid redundant features
If frequency and monetary value are almost perfectly correlated, the pair counts that behaviour twice and pulls clusters toward it. Check the correlation matrix and drop or combine near-duplicates.
Keep only features you can act on
Every feature should connect to a decision. If marketing cannot do anything differently based on a feature, leave it out. Never include consent flags or sensitive attributes as clustering inputs unless your privacy review has approved it.
Choosing the number of clusters
K-means does not tell you the right k. Two common diagnostics help:
- Inertia is the sum of squared distances from each customer to its centroid. It always falls as
kgrows, so you look for an "elbow" where the improvement flattens. - Silhouette score compares how close a customer is to its own cluster against the nearest other cluster. It ranges from -1 to 1. Higher means better separated clusters.
The script below builds a synthetic customer base with three behaviour patterns, applies the transforms from the previous section, and prints both diagnostics for k from 2 to 6.
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(7)
patterns = [ # (customers, recency, frequency, monetary)
(150, 5, 12, 500),
(200, 45, 3, 100),
(100, 100, 1, 30),
]
frames = []
for n, rec, freq, mon in patterns:
frames.append(pd.DataFrame({
"recency_days": rng.normal(rec, rec * 0.3, n).clip(1),
"frequency": rng.poisson(freq, n) + 1,
"monetary": rng.lognormal(np.log(mon), 0.3, n),
}))
data = pd.concat(frames, ignore_index=True)
data["frequency"] = np.log1p(data["frequency"])
data["monetary"] = np.log1p(data["monetary"])
scaled = StandardScaler().fit_transform(data)
for k in range(2, 7):
model = KMeans(n_clusters=k, n_init=10, random_state=42).fit(scaled)
score = silhouette_score(scaled, model.labels_)
print(f"k={k} inertia={model.inertia_:.1f} silhouette={score:.3f}")Because the data were built from three patterns, you should see the silhouette score peak at or near k=3 and the inertia curve bend there. Exact numbers depend on your library version.
Real data is rarely this clean. When the diagnostics are ambiguous, let usability decide. A team that can only create three email journeys gains little from eight segments. Choose the smallest k whose clusters you can describe in a sentence and treat differently.
Profile and name the clusters
A cluster is useful only when someone can say who is in it and what to do about it. For each cluster, compute:
- Size, as a count and a share of customers. Very small clusters may be outliers, not segments.
- Feature means or medians in the original units, not the scaled ones.
- Outcome rates not used for clustering, such as email click rate or return rate. Differences here suggest the segments matter.
Then name each cluster with a business label and a one-line action. For example:
| Cluster profile | Name | Likely action |
|---|---|---|
| Recent, frequent, high spend | Champions | Early access, loyalty rewards |
| Moderate recency, low frequency | Occasional buyers | Category recommendations |
| Long gap, low spend | Lapsed | Win-back offer, basket reminder |
Names should describe behaviour, not judge people. "Lapsed" is a behaviour. "Low-value" can lead to neglecting customers who could grow.
Check that segments are stable
A segmentation that changes whenever you rerun it cannot drive campaigns. Test stability before you publish:
- Refit with different
random_statevalues and compare the assignments using the adjusted Rand index (sklearn.metrics.adjusted_rand_score). Values near 1 mean the groupings agree. - Refit on a random 80 percent sample and check that centroids stay close.
- Refit on next month's data and see how many customers change segment.
Some movement is healthy, because customers change behaviour. Large unexplained shifts point to unstable clusters or a weak choice of features. The chapter on segment operations covers refresh and drift in more detail.
Assigning new customers
New customers arrive daily, and you should not refit the model each time. Keep the fitted scaler and the fitted KMeans model. Apply scaler.transform and then model.predict to the new rows. Store the model version next to each assignment so that you can explain why a customer was in a segment on a given date.
Common errors
- Forgetting to scale. The cluster with the largest numeric feature dominates and the result mirrors spend alone.
- Clustering IDs or dates. Identifiers and raw timestamps carry no behavioural meaning. Convert dates to recency first.
- Reading cluster numbers as rankings. Cluster 2 is not "better" than cluster 1. The labels are arbitrary.
- Trusting a high silhouette score alone. A score can be high because one tiny cluster of outliers is far from everyone else.
- Refitting without versioning. After a refit, label 0 may refer to a different group, which breaks downstream rules that referenced the number.
Exercise
You cluster customers on raw (unscaled) recency in days, frequency and monetary value in pounds. One resulting cluster contains almost every customer, and the others are tiny groups of very high spenders. Name two changes that would likely improve the result, and explain why.
Show answer
First, scale the features, for example with StandardScaler, so monetary value in the hundreds or thousands does not dominate the distance calculation over frequency and recency. Second, apply a log transform (such as np.log1p) to skewed features like monetary value and frequency before scaling, so a few extreme spenders do not pull centroids toward themselves and form their own clusters. After refitting, check silhouette scores and profile the clusters to confirm they are balanced and describable.
Exercise
A silhouette analysis shows k=5 scores slightly higher than k=3, but your team can only run three distinct journeys. Which k do you choose, and what do you do about the difference in score?
Show answer
Choose k=3, because a segment is only valuable if the business can treat it differently. The small score difference means five clusters are only marginally better separated, so merging them costs little. Profile the five-cluster solution to see which clusters could be combined, check that the three-cluster version is stable across random seeds, and record the decision so you can revisit it if the team gains capacity for more journeys.