Lesson 8 of 8 · Project
Project: Customer Segmentation
Segment customers in Python step by step: RFM features, scaling, choosing k with silhouette and inertia, k-means profiles, a PCA view and IsolationForest.
- 16 min read
- Intermediate
- Reviewed
- Build RFM-style customer features and prepare them for clustering with a log transform and scaling
- Choose the number of segments with inertia, the silhouette score and business sense
- Profile each k-means cluster with averages and give the segments useful names
- Check the segments in a 2-D PCA view and flag unusual customers with IsolationForest
- Turn segments into business actions, and know the limits of the method
The task
An online shop has about a thousand customers who bought something in the last year. The marketing team sends all of them the same emails and the same discounts, and wants to treat different kinds of customers differently. Nobody has labelled the customers, and nobody knows which kinds exist. That makes it a clustering problem: group customers who behave alike, describe each group, and decide what to do for each one.
The features follow a classic recipe called RFM, plus two more:
- Recency: days since the customer's last order. Small is good.
- Frequency: number of orders in the last year.
- Monetary value: total spend in the last year.
- Tenure: months since the customer's first order.
- Discount share: the share of their orders placed with a discount code.
Step 1: build and explore the data
There are no data files in this course, so the program creates 1,005 customers with a seeded NumPy random generator. The generator builds them from five hidden kinds of customers plus five unusual ones, but the rest of the project never looks at that: it has to find the groups, as you would with real customers.
import numpy as np
# ---- 1,005 customers of an online shop (seeded, so everyone gets the same data) ----
rng = np.random.RandomState(7)
# Five hidden groups: share of customers, typical days since the last order, orders in a year,
# spend per order, months as a customer, share of orders with a discount code
groups = [(0.10, 10, 22, 85, 40, 0.1), (0.30, 30, 9, 55, 30, 0.2), (0.15, 20, 1, 50, 2, 0.5),
(0.20, 35, 7, 30, 24, 0.8), (0.25, 220, 2, 50, 36, 0.25)]
parts = [[[2, 150, 21000, 30, 0.02], [1, 180, 26000, 40, 0], [3, 120, 15000, 20, 0.05],
[5, 1, 4800, 1, 0], [300, 60, 4000, 50, 0.9]]] # 5 unusual customers
for share, days, per_year, per_order, months, discount in groups:
n = int(1000 * share)
recency = np.clip(rng.gamma(4, days / 4, n), 1, 365).round() # days since last order
orders = 1 + rng.poisson(max(per_year - 1, 0.3), n) # orders in the last year
spend = (orders * per_order * rng.lognormal(0, 0.3, n)).round(2) # spend in the last year
tenure = np.clip(rng.normal(months, months / 4 + 1, n), 1, 72).round() # months as a customer
disc = np.clip(rng.normal(discount, 0.1, n), 0, 1).round(2) # share of orders with a code
parts.append(np.column_stack([recency, orders, spend, tenure, disc]))
X = np.vstack(parts)[rng.permutation(1005)] # shuffle the rows
columns = ["recency (days)", "orders", "spend", "tenure (months)", "discount share"]
print(f"{len(X)} customers. The first one:", ", ".join(f"{name} {value:g}" for name, value in zip(columns, X[0])))
print(f"\n{'':<16}{'min':>9}{'median':>9}{'mean':>9}{'max':>9}")
for name, values in zip(columns, X.T):
print(f"{name:<16}{values.min():9.1f}{np.median(values):9.1f}{values.mean():9.1f}{values.max():9.1f}")1005 customers. The first one: recency (days) 33, orders 9, spend 473.66, tenure (months) 35, discount share 0.25
min median mean max
recency (days) 1.0 30.0 72.9 365.0
orders 1.0 6.0 7.5 180.0
spend 22.4 214.8 499.2 26000.0
tenure (months) 1.0 28.0 26.8 72.0
discount share 0.0 0.3 0.4 1.0Two things matter for clustering:
- Long tails. Spend has a median of 214.8 but a mean of 499.2 and a maximum of 26,000: a few customers spend far more than everyone else. Orders (median 6, maximum 180) and recency (median 30, mean 72.9) are skewed too.
- Very different units. Spend runs into thousands, while the discount share stays between 0 and 1.
k-means groups customers by distance, so both problems would let a few columns, and a few customers, decide everything.
Step 2: prepare the features and choose k
Two fixes come first:
- Log transform the three skewed columns with
np.log1p, which computes log(1 + x) and so also works for zero. A log turns ratios into equal steps: going from 100 to 200 counts about as much as going from 1,000 to 2,000, so the biggest spenders no longer stretch the scale for everyone. - Scale every column with
StandardScalerto a mean of 0 and a spread of 1, so that each feature has an equal say in the distances.
Then fit k-means for k = 2 to 8 and record two numbers for each, as in Clustering Overview: inertia, the total squared distance from each customer to its cluster centre (lower means tighter clusters), and the silhouette score, from −1 to 1, which says how much closer customers are to their own cluster than to the next one (higher means better separated).
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
rng = np.random.RandomState(7) # the same 1,005 customers as in Step 1
groups = [(0.10, 10, 22, 85, 40, 0.1), (0.30, 30, 9, 55, 30, 0.2), (0.15, 20, 1, 50, 2, 0.5),
(0.20, 35, 7, 30, 24, 0.8), (0.25, 220, 2, 50, 36, 0.25)]
parts = [[[2, 150, 21000, 30, 0.02], [1, 180, 26000, 40, 0], [3, 120, 15000, 20, 0.05],
[5, 1, 4800, 1, 0], [300, 60, 4000, 50, 0.9]]]
for share, days, per_year, per_order, months, discount in groups:
n = int(1000 * share)
recency = np.clip(rng.gamma(4, days / 4, n), 1, 365).round()
orders = 1 + rng.poisson(max(per_year - 1, 0.3), n)
spend = (orders * per_order * rng.lognormal(0, 0.3, n)).round(2)
tenure = np.clip(rng.normal(months, months / 4 + 1, n), 1, 72).round()
disc = np.clip(rng.normal(discount, 0.1, n), 0, 1).round(2)
parts.append(np.column_stack([recency, orders, spend, tenure, disc]))
X = np.vstack(parts)[rng.permutation(1005)]
# ---- Prepare the features ----
features = X.copy()
features[:, :3] = np.log1p(features[:, :3]) # log(1 + x) shrinks the long tails of recency, orders, spend
X_scaled = StandardScaler().fit_transform(features) # then every column gets mean 0 and spread 1
print("spread before:", " ".join(f"{s:.1f}" for s in X.std(axis=0)))
print("spread after: ", " ".join(f"{s:.1f}" for s in X_scaled.std(axis=0)))
# ---- Choose k: fit k-means for k = 2 to 8 ----
print(f"\n{'k':>2}{'inertia':>9}{'drop':>7}{'silhouette':>12}")
previous = None
for k in range(2, 9):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
drop = "" if previous is None else f"{previous - km.inertia_:7.0f}"
print(f"{k:>2}{km.inertia_:9.0f}{drop:>7}{silhouette_score(X_scaled, km.labels_):12.3f}")
previous = km.inertia_spread before: 93.7 10.4 1285.9 13.7 0.3 spread after: 1.0 1.0 1.0 1.0 1.0 k inertia drop silhouette 2 3208 0.338 3 1974 1234 0.446 4 1345 629 0.497 5 1014 331 0.484 6 936 78 0.416 7 864 72 0.355 8 825 39 0.341
Inertia always falls as k grows, because more centres always sit closer to the customers, so its lowest value is not the goal. Look at the drop instead: each extra cluster up to k = 5 removes a lot of inertia (331 for the fifth), and after that very little (78, 72, 39). The bend, often called the elbow, is at k = 5. The silhouette score is highest at k = 4 (0.497), with k = 5 close behind (0.484), and falls quickly after that.
After scaling, every column has a spread of 1.0, where spend's spread used to be thousands of times that of the discount share. The two measures disagree slightly, as they often do on real data, so let the business break the tie. In Step 3, try k = 4: you get one segment of 398 customers that mixes the shop's best customers with ordinary regulars, a group no marketing team could act on. With k = 5 they are separate. The measures narrow the choice; usefulness decides it. We choose k = 5.
Step 3: fit k-means and profile the segments
Now fit k-means with k = 5 and describe each cluster by its averages in the original units, next to the average of all customers:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
rng = np.random.RandomState(7) # the same 1,005 customers as in Step 1
groups = [(0.10, 10, 22, 85, 40, 0.1), (0.30, 30, 9, 55, 30, 0.2), (0.15, 20, 1, 50, 2, 0.5),
(0.20, 35, 7, 30, 24, 0.8), (0.25, 220, 2, 50, 36, 0.25)]
parts = [[[2, 150, 21000, 30, 0.02], [1, 180, 26000, 40, 0], [3, 120, 15000, 20, 0.05],
[5, 1, 4800, 1, 0], [300, 60, 4000, 50, 0.9]]]
for share, days, per_year, per_order, months, discount in groups:
n = int(1000 * share)
recency = np.clip(rng.gamma(4, days / 4, n), 1, 365).round()
orders = 1 + rng.poisson(max(per_year - 1, 0.3), n)
spend = (orders * per_order * rng.lognormal(0, 0.3, n)).round(2)
tenure = np.clip(rng.normal(months, months / 4 + 1, n), 1, 72).round()
disc = np.clip(rng.normal(discount, 0.1, n), 0, 1).round(2)
parts.append(np.column_stack([recency, orders, spend, tenure, disc]))
X = np.vstack(parts)[rng.permutation(1005)]
features = X.copy()
features[:, :3] = np.log1p(features[:, :3])
X_scaled = StandardScaler().fit_transform(features)
k = 5 # the number of segments chosen in Step 2
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
# k-means numbers its clusters in no particular order. Renumber them by average spend,
# highest first, so that the numbers (and the names below) stay the same on every run.
spend = [X[km.labels_ == c, 2].mean() for c in range(k)]
segment = np.zeros(len(X), dtype=int)
for rank, c in enumerate(np.argsort(spend)[::-1]):
segment[km.labels_ == c] = rank
# ---- Profile: the average customer in each segment, in the original units ----
print(f"{'segment':<9}{'customers':>10}{'recency':>9}{'orders':>8}{'spend':>8}{'tenure':>8}{'discount':>10}")
for s in range(k):
r, o, m, t, d = X[segment == s].mean(axis=0)
print(f"{s:<9}{(segment == s).sum():>10}{r:9.0f}{o:8.1f}{m:8.0f}{t:8.0f}{d:10.2f}")
r, o, m, t, d = X.mean(axis=0)
print(f"{'all':<9}{len(X):>10}{r:9.0f}{o:8.1f}{m:8.0f}{t:8.0f}{d:10.2f}")segment customers recency orders spend tenure discount 0 104 10 26.1 2459 39 0.11 1 301 31 8.9 530 30 0.19 2 195 35 7.4 253 25 0.80 3 249 213 2.0 106 35 0.26 4 156 20 1.4 70 3 0.51 all 1005 73 7.5 499 27 0.37
k-means hands out cluster numbers in no particular order, and a re-run can shuffle them, so the program renumbers the segments by average spend. To name a segment, compare its row with the "all" row, ask what stands out most, and choose a short name that describes behaviour and means something to the people who will use it:
| Segment | Name | What stands out |
|---|---|---|
| 0 | VIPs | 104 customers: last order 10 days ago, 26 orders and about 2,500 spent a year, rarely use codes |
| 1 | Regulars | 301 steady customers: about 9 orders and 530 a year, last order a month ago |
| 2 | Bargain hunters | 195 customers who use a code on 80% of their orders and spend only about 34 per order |
| 3 | Lapsed | 249 customers whose last order was 213 days ago on average, after only 2 orders |
| 4 | Newcomers | 156 customers who joined about 3 months ago and have ordered 1.4 times |
Step 4: a 2-D view, and customers who fit nowhere
To see the segments, PCA squeezes the five scaled features into two, as in Principal Component Analysis. The program prints each customer as the first letter of their segment's name. It also fits an IsolationForest (Anomaly Detection) with contamination=0.01, which flags the 1% of customers that are easiest to isolate, and marks them with !:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
rng = np.random.RandomState(7) # the same 1,005 customers as in Step 1
groups = [(0.10, 10, 22, 85, 40, 0.1), (0.30, 30, 9, 55, 30, 0.2), (0.15, 20, 1, 50, 2, 0.5),
(0.20, 35, 7, 30, 24, 0.8), (0.25, 220, 2, 50, 36, 0.25)]
parts = [[[2, 150, 21000, 30, 0.02], [1, 180, 26000, 40, 0], [3, 120, 15000, 20, 0.05],
[5, 1, 4800, 1, 0], [300, 60, 4000, 50, 0.9]]]
for share, days, per_year, per_order, months, discount in groups:
n = int(1000 * share)
recency = np.clip(rng.gamma(4, days / 4, n), 1, 365).round()
orders = 1 + rng.poisson(max(per_year - 1, 0.3), n)
spend = (orders * per_order * rng.lognormal(0, 0.3, n)).round(2)
tenure = np.clip(rng.normal(months, months / 4 + 1, n), 1, 72).round()
disc = np.clip(rng.normal(discount, 0.1, n), 0, 1).round(2)
parts.append(np.column_stack([recency, orders, spend, tenure, disc]))
X = np.vstack(parts)[rng.permutation(1005)]
features = X.copy()
features[:, :3] = np.log1p(features[:, :3])
X_scaled = StandardScaler().fit_transform(features)
km = KMeans(n_clusters=5, n_init=10, random_state=0).fit(X_scaled)
spend = [X[km.labels_ == c, 2].mean() for c in range(5)]
segment = np.zeros(len(X), dtype=int)
for rank, c in enumerate(np.argsort(spend)[::-1]):
segment[km.labels_ == c] = rank
names = ["VIPs", "Regulars", "Bargain hunters", "Lapsed", "Newcomers"]
# ---- Unusual customers: the 1% that IsolationForest finds easiest to isolate ----
unusual = IsolationForest(contamination=0.01, random_state=0).fit(X_scaled).predict(X_scaled) == -1
# ---- A 2-D view: PCA squeezes the 5 scaled features into 2, drawn as text ----
pca = PCA(n_components=2).fit(X_scaled)
xy = pca.transform(X_scaled)
print(f"the 2 PCA axes keep {pca.explained_variance_ratio_.sum():.0%} of the variation")
cols, rows = 60, 14
low, high = xy.min(axis=0), xy.max(axis=0)
grid = [[" "] * cols for _ in range(rows)]
for (a, b), s, odd in zip(xy, segment, unusual):
col = int((a - low[0]) / (high[0] - low[0]) * (cols - 1))
row = int((b - low[1]) / (high[1] - low[1]) * (rows - 1))
if grid[rows - 1 - row][col] != "!": # never hide an unusual customer
grid[rows - 1 - row][col] = "!" if odd else names[s][0]
print("\n".join("".join(line).rstrip() for line in grid))
print(f"\n{unusual.sum()} unusual customers:")
print(f"{'segment':<17}{'recency':>8}{'orders':>7}{'spend':>8}{'tenure':>7}{'discount':>9}")
for row, s in zip(X[unusual], segment[unusual]):
print(f"{names[s]:<17}{row[0]:8.0f}{row[1]:7.0f}{row[2]:8.0f}{row[3]:7.0f}{row[4]:9.2f}")
vip = segment == 0
print(f"\nVIP average spend: {X[vip, 2].mean():.0f} with the unusual customers, "
f"{X[vip & ~unusual, 2].mean():.0f} without them")the 2 PCA axes keep 80% of the variation
!
L
L LLLLLL L LL
LLLLLLLLLLLL L L
L LLLLLLLLLLLLLLLL
LLLLLLLLLLLLLL L RR R RRR V
LLLLLLLL LLLR RRRRRRRRR RR V! VV!V!
LL LL RRRRRRRRRRRRRRR V VVVVV
N B BRRRRRRRRRRRRRVVVVVVVVV
B BBBBBBRBBBRRRRRRRRRR VVVVVVVV!
NNNNNNNNNBBBBBBBBBBBBBRR RR R VVVV V !
NNNNNNNNNBNBBBBBBBBBBB ! V V ! !
NNNNNNNNBNNBBBBBBB B ! !
NNNNN N NB N B
11 unusual customers:
segment recency orders spend tenure discount
Lapsed 365 4 193 55 0.01
VIPs 3 35 2257 34 0.00
VIPs 3 120 15000 20 0.05
VIPs 2 150 21000 30 0.02
VIPs 7 23 1003 63 0.10
VIPs 1 180 26000 40 0.00
Bargain hunters 300 60 4000 50 0.90
VIPs 5 29 3046 47 0.30
Regulars 5 1 4800 1 0.00
VIPs 3 27 2892 20 0.25
VIPs 3 18 1292 64 0.05
VIP average spend: 2459 with the unusual customers, 1909 without themThe map. Two PCA axes keep 80% of the variation, so the picture is a fair summary of all five features. Each segment has its own region: Lapsed customers at the top left, Newcomers at the bottom left with the Bargain hunters next to them, Regulars in the middle and VIPs on the right. Neighbouring segments touch, though: where Regulars meet Bargain hunters, k-means drew a line through a continuum, and customers on either side of it are not very different. (The sign of a PCA axis is arbitrary, so such a map can come out mirrored.)
The unusual customers. IsolationForest flags 11 customers, most of them on the right of the map, around and beyond the VIPs:
- Three customers placed 120 to 180 orders worth 15,000 to 26,000: almost certainly resellers or businesses, not households.
- One customer spent 4,800 in a single order in their first month. k-means must put everyone somewhere, so they count as a Regular, which they clearly aren't. It could be a big gift, a company, or fraud.
- A bargain hunter with 60 orders worth 4,000 hasn't ordered for 300 days. The others are extreme but believable: very active VIPs, and one customer who last ordered a year ago.
They also distort the profiles. Eight of them sit inside the VIPs, whose average spend is 2,459 with them and 1,909 without them, and the three big buyers cause almost all of that difference. Set unusual customers aside, or check medians, before you describe a segment, and give them a human look before any campaign: a sales call or a business account for the resellers, a fraud check for the one-off order.
Step 5: from segments to actions
A segmentation is only worth something if each segment gets different treatment. Each campaign also needs a random control group in its segment that gets nothing, as in the churn project of Supervised Learning; otherwise nobody can tell whether the actions work. One plan:
| Segment | Customers | Action |
|---|---|---|
| VIPs | 104 | Thank and protect them: early access, free delivery, a referral programme. They rarely use codes, so don't train them to wait for discounts. |
| Regulars | 301 | Grow them towards VIP: loyalty points, recommendations for products they haven't tried. |
| Bargain hunters | 195 | Reach them during sales and with clearance items, and watch the profit on every order. |
| Lapsed | 249 | A win-back offer and a short survey about why they stopped. Stop spending on those who don't respond. |
| Newcomers | 156 | A welcome series that leads to a second order, the step that turns a first try into a habit. |
| Unusual | 11 | A person reviews them before any automated campaign. |
Limitations and next steps
- Real customers are fuzzier. This data was built from five clear groups. Real customers blend into each other, so expect lower silhouette scores and harder choices of k.
- k-means has assumptions. It looks for round groups of similar spread and must put every customer in some segment, as the 4,800 one-order customer showed. Gaussian mixtures and DBSCAN, which you met in Clustering Overview, relax these assumptions, and the Clustering Algorithms course covers them in depth.
- The features decide the segments. Different features, or a different transform, give different segments. Choose features that match the decisions the business will make.
- Segments drift. Re-run the segmentation every month or quarter, and track customers who move: a Regular sliding towards Lapsed is an early churn warning, and a churn model, as in Supervised Learning, can score that risk directly.
- Check stability. Re-fit with other values of
random_state, or on random halves of the customers. Segments that change a lot between runs aren't solid enough to build campaigns on.
Common mistakes
Practice
Put new customers into segments the way km.predict does: scale them with the training customers' mean and spread, then find the nearest centre. Customer B spent 900 but last ordered 300 days ago; without scaling, they would land among the Regulars.
import numpy as np
# A simplified model with three features: recency (days), orders, spend
mean = np.array([70, 7, 500]) # what the scaler learned from the training customers
std = np.array([90, 6, 600])
centres = { # k-means centres, in scaled units
"VIPs": [-0.8, 1.8, 1.9], "Regulars": [-0.4, 0.2, 0.1],
"Lapsed": [1.9, -0.6, -0.5], "Newcomers": [-0.6, -1.0, -0.8],
}
new_customers = {"A": [5, 20, 1700], "B": [300, 3, 900], "C": [15, 1, 40]}
# Scale each new customer, then print the name of the nearest centre, like: customer A -> VIPs
for name, values in new_customers.items():
nearest = "?"
print(f"customer {name} -> {nearest}")
Why does this project take the log of recency, orders and spend, and then scale every column, before running k-means?
Summary
- Segmentation is clustering with a business purpose: build behaviour features such as RFM, tame long tails with a log, and scale before k-means.
- Choose k with the inertia elbow and the silhouette score, then let usefulness break ties; here k = 5 kept the VIPs apart from the regulars.
- Profile each segment with averages in the original units, compared with all customers, and give it a short name that describes behaviour.
- A PCA map shows how segments sit next to each other, and IsolationForest finds customers who fit no segment and would distort its profile.
- Each segment needs its own action and a control group, and the segmentation needs regular re-runs and stability checks.
This is the last lesson of the course.
Finished reading? Tick it off to track your progress.