Sub topic 6
Creating segments with clustering
This chapter assumes you can read basic Python and pandas, know what RFM features are (recency, frequency and monetary value, covered in the previous chapter), and understand averages and standard deviation. Clustering groups customers by similarity without a person writing the rules. You then read each group and give it a business name.
What clustering does
Clustering is an unsupervised method. It has no labels to learn from. It looks at the features you give it and places customers with similar values in the same group. K-means is the usual starting point. You choose the number of clusters, k. The algorithm places k centres, assigns each customer to the nearest centre, moves each centre to the average of its members, and repeats until the assignments stop changing.
Scale before you cluster
K-means measures straight-line distance. If monetary value runs from 25 to 700 and frequency runs from 1 to 15, monetary value dominates the distance and frequency barely matters. StandardScaler rewrites each feature so it has a mean of 0 and a standard deviation of 1. Every feature then carries comparable weight.
A worked example
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())The code scales the three features, fits k-means with two clusters, and stores each customer's cluster number in a segment column. The final line averages the original, unscaled values per cluster, so you can read them in days, orders and currency.
Setting random_state makes the run repeatable. n_init=10 runs the algorithm from ten starting positions and keeps the best result, which reduces the chance of a poor start.
Interpret and name the groups
Cluster numbers mean nothing to a marketer. Read the averages and label each group by its behaviour. In this data, one cluster has recency near 3 to 5 days, frequency near 12 and monetary value above 400. Call it "loyal high spenders". The other has recency of 40 to 90 days, frequency of 1 to 3 and low spend. Call it "lapsed low spenders".
Cluster numbers can change between runs or after retraining. Store the business name, not the number, and map numbers to names after each fit.
Choosing k
Larger k gives finer groups but harder-to-use ones. Check these before you accept a value:
- Size. Every cluster should be large enough to market to and to measure in a test.
- Distinctness. The averages should differ in ways a person can describe.
- Fit scores. The elbow method plots within-cluster spread against k. The silhouette score measures how well separated the clusters are. Use both as guides, not as final answers.
- Actionability. If you cannot say what you would do differently for a cluster, merge it with another.
Common errors
- Clustering unscaled features, so one feature decides the result.
- Leaving heavily skewed features such as spend untreated. A few very large spenders can form their own cluster. A log transform often helps.
- Treating clusters as permanent truth. Customers change behaviour, so refit on a schedule.
- Including identifiers or features you lack consent to use.
Exercise
A teammate runs k-means on raw recency (days), frequency and monetary value (currency) and finds that the clusters split almost entirely by spend. What went wrong, and what is the fix?
Show answer
The features were not scaled. Monetary value has a much larger numeric range, so it dominates the distance calculation. Scale the features with StandardScaler before fitting, and consider a log transform if spend is heavily skewed.
Exercise
After retraining, your marketing tool shows "segment 0" now contains the lapsed customers, where last month it held the loyal ones. How do you prevent campaigns from targeting the wrong group?
Show answer
Cluster numbers are arbitrary and can change between fits. Profile each cluster after every fit, assign business names from the averages, and store and target the names rather than the numbers.