Sub topic 5
Finding segments in data with clustering
This chapter assumes you know the basic segmentation vocabulary from earlier chapters (segmentation bases, the five tests for a usable segment). It also assumes you can read a simple table of averages and follow short Python code. Clustering is the step where you stop choosing segments by hand and let customer data suggest them.
Why use clustering
Rule-based segmentation starts with a base you pick in advance: "customers under 30", "customers in the north region". That is easy to explain, but you can miss groups that cut across your categories. A group of 25-year-olds and 65-year-olds who both buy rarely and spend little would never appear if you split only by age.
Clustering is a family of methods that sort records into groups so that records in the same group are similar to each other and records in different groups are less similar. You choose which attributes count as "similar". The algorithm finds the grouping. This is called data-driven (or a posteriori) segmentation, because the segments appear after you analyze the data.
Clustering produces candidate groups, not finished segments. A cluster only becomes a segment once it passes the usability tests and a person can describe it in marketing terms.
How k-means works
k-means is the most common clustering method in marketing work. It needs you to choose k, the number of clusters, before it runs. The algorithm then repeats two steps:
- Place k centers in the data. Assign every customer to the nearest center.
- Move each center to the average position of the customers assigned to it. Repeat step 1 with the new centers.
The loop stops when assignments no longer change. Each final center is the average customer of its cluster, which is why the output is easy to read as a segment description.
"Nearest" means ordinary straight-line distance across all the attributes. This detail drives most of the practical problems below.
A worked example
The table below lists six customers with three attributes: age, annual spend in dollars, and purchases per year.
| Customer | Age | Annual spend | Purchases per year |
|---|---|---|---|
| 1 | 22 | 300 | 4 |
| 2 | 25 | 350 | 5 |
| 3 | 41 | 1500 | 14 |
| 4 | 45 | 1600 | 16 |
| 5 | 63 | 700 | 6 |
| 6 | 67 | 650 | 5 |
The code standardizes the columns, runs k-means with three clusters, and prints the average customer of each cluster.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Columns: age, annual spend, purchases per year
customers = np.array([
[22, 300, 4],
[25, 350, 5],
[41, 1500, 14],
[45, 1600, 16],
[63, 700, 6],
[67, 650, 5],
])
scaled = StandardScaler().fit_transform(customers)
model = KMeans(n_clusters=3, n_init=10, random_state=0)
labels = model.fit_predict(scaled)
for label in sorted(set(labels)):
members = customers[labels == label]
print(label, members.mean(axis=0))Each printed line shows a cluster number and the average age, spend and purchase count of its members. The cluster numbers themselves are arbitrary, so cluster 0 on your machine may not match the cluster 0 in someone else's run. Read the averages, not the numbers.
With this data you should see three groups: young, light buyers; middle-aged, heavy buyers; and older, moderate buyers. Those are the starting points for profiling, which the next chapter covers.
Why standardize first
Annual spend runs into the thousands, while purchases per year run in the tens. Without scaling, distance would be decided almost entirely by spend, and the other attributes would barely matter. StandardScaler rewrites each column so that it has an average of 0 and a standard deviation of 1. Every attribute then has a comparable pull on the result.
Note that scaling is a judgment too. If you believe spend matters twice as much as age, you can multiply that scaled column by a weight. Record such choices, because they change the segments.
Choosing the number of clusters
k-means does not tell you how many segments exist. You have to test several values of k and combine statistics with business judgment.
A useful statistic is the silhouette score. For each customer it compares how close they are to their own cluster against how close they are to the next nearest cluster. The score runs from -1 to 1. Values near 1 mean tight, well-separated clusters. Values near 0 mean clusters overlap.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
customers = np.array([
[22, 300, 4],
[25, 350, 5],
[41, 1500, 14],
[45, 1600, 16],
[63, 700, 6],
[67, 650, 5],
])
scaled = StandardScaler().fit_transform(customers)
for k in range(2, 6):
model = KMeans(n_clusters=k, n_init=10, random_state=0)
labels = model.fit_predict(scaled)
print(k, round(silhouette_score(scaled, labels), 2))The loop starts at 2 because a silhouette score needs at least two clusters. It stops at 5 because it needs fewer clusters than customers.
A second common check is the elbow method. You plot the model's inertia_ (the total squared distance from customers to their centers) against k. Inertia always falls as k rises, so you look for the point where the drop levels off.
Neither statistic settles the question. Use them to shortlist two or three values of k. Then choose using the criteria you already know:
- Can you name and describe each cluster in a sentence?
- Is each cluster large enough to be worth serving (substantiality)?
- Would you really treat the clusters differently in marketing (actionability)?
A statistically tidy solution with eight clusters is useless if the company can only run three campaigns.
Common errors and edge cases
| Problem | What happens | What to do |
|---|---|---|
| Attributes not scaled | One large-unit attribute dominates the clusters | Standardize before clustering |
| Outliers | One very large customer pulls a center toward itself, or forms a cluster of one | Inspect extreme values. Cap, remove, or analyze them separately |
| Categorical data | Straight-line distance is meaningless for labels such as region or plan type | Use methods built for mixed data, such as k-prototypes, or cluster on numeric behavior and profile the categories afterward |
| Correlated attributes | Two attributes that measure the same thing count twice | Drop one, or combine them |
| Different results on each run | Random starting centers lead to different groupings | Set `random_state` and use `n_init=10` or more |
| Clusters that are not round | k-means finds compact, similar-sized groups and splits long or uneven shapes badly | Try another method, such as hierarchical clustering or a Gaussian mixture model |
| Data changes over time | Segments built from last year's data drift | Re-run on fresh data and compare |
Which attributes to include
The clustering result depends mostly on which attributes you feed in, more than on the algorithm. Two principles help.
First, cluster on attributes that relate to the buying decision, such as purchase frequency, spend, product mix, price sensitivity or survey answers about needs. These are the bases that tend to make segments actionable. Demographics like age are easier to reach but often predict behavior weakly.
Second, keep the clustering inputs separate from the profiling variables. You can cluster on behavior, then check afterward how age, region and channel differ across clusters. That tells you how to reach the segments without having forced the groups to look demographically neat.
Sample size
The six-customer example is for teaching. Real projects typically use hundreds or thousands of customers, and the cluster averages become stable only with enough records per cluster. As a rough guide, a cluster of a few dozen customers is too thin for reliable conclusions, so check cluster sizes every time.
From clusters to candidate segments
The output of clustering is a label per customer and a set of averages per cluster. Before this counts as segmentation, run through these steps:
- Name each cluster from its averages, for example "frequent high spenders".
- Check each against the five tests: measurable, accessible, substantial, differentiable and actionable.
- Merge or drop clusters that fail, then re-run if needed.
- Pass the survivors to profiling, where you describe who they are and how to reach them.
Clustering narrows the options. It does not choose the target market. That choice comes later, after the segments are evaluated for size, growth, profitability and fit.
Exercise
A analyst clusters customers on annual spend (in dollars, range 50 to 20,000) and number of store visits per year (range 1 to 60) without scaling either column. The clusters turn out to differ only by spend. What went wrong, and what is the fix?
Show answer
k-means uses straight-line distance, and spend has a far larger numeric range than visits, so spend decides the distances and visits has almost no effect. The fix is to standardize both columns (for example with StandardScaler) before clustering so each contributes comparably. Then re-run and check that the clusters now differ on both attributes.
Exercise
Silhouette scores for k = 2, 3, 4 and 5 are 0.61, 0.48, 0.52 and 0.31. The k = 2 solution gives "big spenders" and "everyone else". The k = 4 solution gives four groups the sales team can each describe and target differently, and each holds more than 10% of customers. Which would you take forward, and why?
Show answer
Take k = 4 forward, or at least keep it alongside k = 2. The silhouette score is a guide, not a decision rule. k = 4 is still reasonably separated (0.52), and it yields groups that are describable, substantial and actionable, which the k = 2 split does not. A final choice should also be checked for stability on a random subset of customers.