A food wholesaler sells to 440 businesses: hotels, restaurants, cafés and shops. The sales team treats them all alike, with the same catalogue, the same calls and the same offers. If the customers fall into a few groups that buy differently, each group could get its own offers. Nobody has labelled the customers with such groups, so this is a job for clustering. A customer segmentation project with K-means turns a table of spending into a handful of named segments that a business can act on, and, just as important, checks that those segments are real and not an accident of the method.
What you need first: K-means clustering explained, K-means from scratch, feature scaling and log transforms from feature engineering basics.
Key terms
- Customer segmentation: dividing customers into groups that behave alike, so each group can be treated differently.
- Segment profile: a description of a cluster in business terms, such as "big fresh-food buyers".
- Log transform: replacing each value with its logarithm, so that huge spenders don't dominate the distances.
- Silhouette score: how much closer points are to their own cluster than to the nearest other one, from −1 to 1.
- Cluster stability: whether the same segments appear when the data is resampled or K-means restarts.
The goal, the metric and the baseline
- Goal: segments of customers who buy differently, which the sales team can describe in a sentence and target with different offers.
- Metrics: there's no right answer to score against, so use three checks together. The silhouette score (are the groups well separated?), stability (does K-means find the same groups from different starts?) and usefulness (can each segment be described and acted on?).
- Baseline: the business already splits customers into two channels: hotels, restaurants and cafés ("HoReCa") and retail shops. A segmentation must say something that split doesn't.
Step 1: load the data
The Wholesale customers dataset from the UCI repository: a year's spending by 440 clients of a food distributor in Portugal, in six product categories, in an unnamed currency unit.
Download the data: wholesale-customers.csv (15 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("wholesale-customers.csv").
from pathlib import Path
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
url = ("https://archive.ics.uci.edu/ml/machine-learning-databases/"
"00292/Wholesale%20customers%20data.csv")
path = Path("wholesale_customers.csv")
if not path.exists():
urllib.request.urlretrieve(url, path)
pd.set_option("display.width", 140)
pd.set_option("display.max_columns", 20)
customers = pd.read_csv(path)
spending = ["Fresh", "Milk", "Grocery", "Frozen", "Detergents_Paper", "Delicassen"]
print(customers.shape)
print(customers["Channel"].value_counts().rename({1: "HoReCa", 2: "Retail"}))
(440, 8)
Channel
HoReCa 298
Retail 142
Name: count, dtype: int64
The two set_option lines let pandas print wide tables in full instead of hiding middle columns behind "...". Channel is 1 for hotels, restaurants and cafés and 2 for retail. Region (Lisbon, Porto or other) and Channel are labels the business already has; they are not used for clustering, only to compare with afterwards. Delicassen means delicatessen goods, and Detergents_Paper cleaning products and paper goods.
Step 2: look at the spending
print(customers[spending].describe().T[["min", "50%", "mean", "max"]].round(0))
min 50% mean max
Fresh 3.0 8504.0 12000.0 112151.0
Milk 55.0 3627.0 5796.0 73498.0
Grocery 3.0 4756.0 7951.0 92780.0
Frozen 25.0 1526.0 3072.0 60869.0
Detergents_Paper 3.0 816.0 2881.0 40827.0
Delicassen 3.0 966.0 1525.0 47943.0
describe() summarises each column; .T turns the table so each category is a row.
Every category is heavily skewed. The typical (median) customer spends 4,756 on groceries, but the mean is 7,951 and the largest customer spends 92,780, nearly 20 times the median. In every column, the mean is well above the median: a few very large customers pull it up.
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].hist(customers["Grocery"], bins=40)
axes[0].set_title("Grocery spending")
axes[1].hist(np.log1p(customers["Grocery"]), bins=40, color="tab:green")
axes[1].set_title("log(1 + Grocery spending)")
plt.tight_layout()
plt.show()
np.log1p(x) computes log(1 + x), which works even when x is 0.
Raw spending piles up near zero with a long tail; on a log scale it forms a rounded hill. A log scale also matches how a business thinks: a customer spending twice as much is "twice as big" whether that's 1,000 against 2,000 or 40,000 against 80,000, and on a log scale both gaps are the same size. One customer stands far to the left: someone who bought almost no groceries.
Step 3: see it fail on raw spending
Predict first: what happens if you just scale the raw spending and run K-means, as in the earlier lessons?
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
Z_raw = StandardScaler().fit_transform(customers[spending])
for k in [2, 4, 6]:
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(Z_raw)
print(f"k = {k}: silhouette {silhouette_score(Z_raw, labels):.3f}, cluster sizes {np.bincount(labels)}")
k = 2: silhouette 0.567, cluster sizes [ 49 391]
k = 4: silhouette 0.346, cluster sizes [316 10 110 4]
k = 6: silhouette 0.374, cluster sizes [276 10 98 53 2 1]
On raw spending, k = 2 scores a high silhouette, 0.567, but its clusters are 49 customers against 391: the biggest spenders against everyone else. At k = 6, two clusters hold just 2 customers and 1 customer. K-means minimises squared distances, and a few customers spending 10 to 20 times the median produce enormous squared distances, so the cheapest way to lower the inertia is to give the giants their own clusters. The high silhouette only says that giants are far from everyone else, which the sales team already knew.
Step 4: choose k on log spending
Log-transform, then scale, then try k from 2 to 8:
Z = StandardScaler().fit_transform(np.log1p(customers[spending]))
ks = range(2, 9)
inertias, silhouettes = [], []
for k in ks:
model = KMeans(n_clusters=k, n_init=10, random_state=0).fit(Z)
inertias.append(model.inertia_)
silhouettes.append(silhouette_score(Z, model.labels_))
print(f"k = {k}: inertia {model.inertia_:7.1f} silhouette {silhouettes[-1]:.3f} sizes {np.bincount(model.labels_)}")
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].plot(ks, inertias, marker="o")
axes[0].set_title("Inertia")
axes[1].plot(ks, silhouettes, marker="o", color="tab:orange")
axes[1].set_title("Silhouette score")
for ax in axes:
ax.set_xlabel("k")
plt.tight_layout()
plt.show()
k = 2: inertia 1844.1 silhouette 0.290 sizes [252 188]
k = 3: inertia 1553.3 silhouette 0.259 sizes [ 81 147 212]
k = 4: inertia 1386.9 silhouette 0.188 sizes [132 61 118 129]
k = 5: inertia 1268.1 silhouette 0.195 sizes [ 59 104 107 55 115]
k = 6: inertia 1174.7 silhouette 0.193 sizes [ 90 113 84 82 20 51]
k = 7: inertia 1086.4 silhouette 0.196 sizes [ 37 49 19 124 41 87 83]
k = 8: inertia 1022.9 silhouette 0.196 sizes [ 19 41 46 44 82 120 76 12]
The inertia curve has no clear elbow: it bends gently all the way. The silhouette score is highest at k = 2 (0.290) and drops sharply at k = 4 (0.188). These scores are low, well below the 0.85 of the clean blobs in the earlier lessons: real customers don't fall into neat, separate groups; they shade into each other. The clusters are all reasonably sized now, though: no more single-customer clusters.
Step 5: two segments, compared with the baseline
two = KMeans(n_clusters=2, n_init=10, random_state=0).fit(Z)
print(pd.crosstab(two.labels_, customers["Channel"].map({1: "HoReCa", 2: "Retail"}),
rownames=["segment"], colnames=["channel"]))
print("silhouette of the business's own channel split:", round(silhouette_score(Z, customers["Channel"]), 3))
channel HoReCa Retail
segment
0 244 8
1 54 134
silhouette of the business's own channel split: 0.231
pd.crosstab counts how many customers fall in each combination of segment and channel. .map turns 1 and 2 into readable names.
The two segments mostly rediscover the business's own channels. Segment 0 is 244 HoReCa businesses and 8 shops; segment 1 is 134 shops and 54 HoReCa businesses. So, from spending alone, K-means finds the restaurant-or-shop split, and it separates customers slightly better than the channel labels themselves do (silhouette 0.290 against 0.231). The 54 HoReCa businesses in segment 1 are interesting: they buy like shops. But two segments mostly tell the business what it knows, so they don't beat the baseline in the way that matters.
Step 6: are the segments stable?
A segmentation is only useful if K-means finds it again from a different start. The adjusted Rand index (ARI) measures how well two groupings agree: 1 means identical (whatever the cluster numbers), 0 means no better than chance. Experiment: compare the n_init=10 result for each k with five single-start runs. Predict first: which k will be least stable?
from sklearn.metrics import adjusted_rand_score
for k in [2, 3, 4]:
reference = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(Z)
agreement = [adjusted_rand_score(reference, KMeans(n_clusters=k, n_init=1, random_state=s).fit_predict(Z))
for s in range(5)]
print(f"k = {k}: agreement with the reference run {np.round(agreement, 2)}")
k = 2: agreement with the reference run [0.99 1. 1. 1. 0.99]
k = 3: agreement with the reference run [0.95 0.97 1. 0.36 0.36]
k = 4: agreement with the reference run [0.81 1. 0.98 0.99 0.44]
k = 2 is rock solid: every single-start run finds the same split (agreement 0.99 to 1.0). k = 3 is the least stable: two of five starts find a very different split (0.36). k = 4 is mostly stable, with one bad start (0.44); with n_init=10, which keeps the best of ten starts, it settles reliably. Note that k = 3 scored a higher silhouette than k = 4, yet it's the less trustworthy choice. Stability is a separate check, and it can overrule the score.
Step 7: profile and name four customer segments
Four segments give the sales team more to work with. Describe each by its median spending; medians resist the few huge customers.
four = KMeans(n_clusters=4, n_init=10, random_state=0).fit(Z)
customers["segment"] = four.labels_
profile = customers.groupby("segment")[spending].median().round(0)
profile["customers"] = customers["segment"].value_counts().sort_index()
profile["share retail"] = customers.groupby("segment")["Channel"].apply(lambda c: (c == 2).mean()).round(2)
print(profile)
fig, ax = plt.subplots(figsize=(9, 3.5))
relative = profile[spending] / customers[spending].median()
im = ax.imshow(np.log2(relative), cmap="RdBu_r", vmin=-3, vmax=3)
ax.set_xticks(range(len(spending)), spending, rotation=30, ha="right")
ax.set_yticks(range(4), [f"segment {i}" for i in range(4)])
for i in range(4):
for j in range(len(spending)):
dark = abs(np.log2(relative.iloc[i, j])) > 1.8
ax.text(j, i, f"{relative.iloc[i, j]:.1f}×", ha="center", va="center", color="white" if dark else "black")
fig.colorbar(im, ax=ax, label="log2 of median vs all customers")
plt.tight_layout()
plt.show()
Fresh Milk Grocery Frozen Detergents_Paper Delicassen customers share retail
segment
0 7814.0 1114.0 1820.0 1390.0 224.0 435.0 132 0.01
1 1073.0 6964.0 10518.0 340.0 4508.0 295.0 61 0.66
2 7832.0 8482.0 12272.0 1347.0 4644.0 1682.0 118 0.80
3 17023.0 3086.0 3445.0 4324.0 529.0 1404.0 129 0.05
relative divides each segment's median by the median of all customers, so 2.0× means twice the typical spend. The colour uses log2 of that ratio, so 2× and ½× are the same distance from white. imshow draws the table as coloured squares, and ax.text writes each ratio in its square, in white on the darkest squares so it stays readable.
Each row now reads as a kind of customer, and the share of retail customers backs up the names:
| Segment | Customers | What they buy | Name |
|---|---|---|---|
| 0 | 132 | Below typical in everything; fresh and frozen near typical | Small food-service customers (1% retail) |
| 1 | 61 | 5.5× the typical detergents and paper, about 2× milk and grocery, almost no fresh or frozen | Grocery and household shops (66% retail) |
| 2 | 118 | High milk, grocery, detergents and paper, and delicatessen; fresh and frozen typical | Large all-round shops (80% retail) |
| 3 | 129 | 2× the typical fresh food, 2.8× frozen; low grocery and detergents | Fresh-food kitchens (5% retail) |
This splits each channel in two in a useful way. Shops split into those that sell fresh food and those that don't; food-service customers split into small ones and big fresh-and-frozen buyers. Each segment suggests a different offer: fresh-produce deals for segment 3, household-goods bundles for segment 1, a starter catalogue for the small customers in segment 0.
Step 8: error analysis: customers who don't fit
K-means puts every customer in a segment, even those who fit none. Their distance to their own centroid shows them:
distance = np.linalg.norm(Z - four.cluster_centers_[four.labels_], axis=1)
customers["distance"] = distance.round(2)
print(customers.sort_values("distance", ascending=False)[spending + ["segment", "distance"]].head(5))
Fresh Milk Grocery Frozen Detergents_Paper Delicassen segment distance
75 20398 1137 3 4407 3 975 0 6.02
338 3 333 7021 15601 15 550 0 5.79
154 622 55 137 75 7 8 0 5.67
142 37036 7152 8253 2995 20 3 0 4.61
183 36847 43950 20170 36534 239 47943 3 4.41
four.cluster_centers_[four.labels_] gives each customer their own segment's centroid; np.linalg.norm(..., axis=1) measures the straight-line distance for each row.
The customers farthest from their centroid have odd spending patterns. Customer 75 bought 20,398 of fresh food but just 3 of groceries and 3 of detergents; customer 338 bought just 3 of fresh food and 15 of detergents, but 15,601 of frozen. Near-zero amounts in a category that every similar business buys may be recording errors, or specialist businesses. Customer 183 is the largest delicatessen buyer in the data, 47,943. These customers don't really belong to any segment; the sales team should hear about them separately rather than receive a segment's standard offer.
Step 9: put a new customer in a segment
The fitted pipeline can place a new customer straight away. Keep the scaler, because new data must be transformed exactly as the training data was:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
segmenter = make_pipeline(FunctionTransformer(np.log1p), StandardScaler(),
KMeans(n_clusters=4, n_init=10, random_state=0)).fit(customers[spending])
new_customer = pd.DataFrame([[2000, 9000, 15000, 300, 6000, 400]], columns=spending)
print("segment:", segmenter.predict(new_customer)[0])
print("same segments as before:", adjusted_rand_score(four.labels_, segmenter.predict(customers[spending])) == 1.0)
segment: 1
same segments as before: True
FunctionTransformer(np.log1p) wraps the log transform as a pipeline step, so log, scaling and K-means travel together.
A new customer who buys a lot of milk, grocery and detergents but little fresh or frozen food lands in segment 1, the grocery and household shops, as the profile table predicts. Fitting the pipeline on the raw columns gives exactly the same segments as before (ARI 1.0), so nothing changed by packaging the steps together.
Limitations
- Spending only. The segments describe what customers buy, not why. Margins, order frequency or location might matter more for sales.
- One year, one country. Buying patterns change with seasons and years; segments need refreshing.
- Round blobs assumed. K-means looks for compact, round groups. Real segments can be elongated or overlap, and the silhouette scores here (under 0.3) say the groups overlap a lot.
- k is a business choice. The data supports two segments most clearly; four are more useful but less sharply separated. Neither is "the" answer.
Take it further
- Try another algorithm. Cluster the same log-scaled data with agglomerative clustering. Hint:
AgglomerativeClustering(n_clusters=4), then compare with ARI. - Shares, not amounts. Cluster each customer's share of spending per category instead of the amounts. Hint: divide each row by its total; do big and small customers now mix?
- Add the region. Do segments differ between Lisbon, Porto and elsewhere? Hint:
pd.crosstab(customers["segment"], customers["Region"]). - Plot the segments in 2D. Hint: PCA, later in this course, reduces the 6 columns to 2 for a scatter plot.
- Find the outliers first. Remove customers with the largest distances, re-cluster, and check whether the segments change.
Practice
- Without running code: why is
Channelleft out of the clustering, when it's clearly informative?
Show the answer
The goal is to find structure the business doesn't already know. Including Channel would make K-means rediscover it, partly by construction. Keeping it out and comparing afterwards shows how much of the existing split the spending alone recovers.
- How many customers in each segment are HoReCa and how many retail?
Show the answer
print(pd.crosstab(customers["segment"], customers["Channel"].map({1: "HoReCa", 2: "Retail"})))
Channel HoReCa Retail
segment
0 131 1
1 21 40
2 24 94
3 122 7
Segments 0 and 3 are almost entirely HoReCa (131 of 132 and 122 of 129), and segment 2 mostly retail (94 of 118). Segment 1 is the mixed one: 40 shops and 21 food-service businesses that buy like shops, which is worth a conversation with the sales team.
- Why use medians, not means, to profile the segments?
Show the answer
Spending is heavily skewed: a few customers spend 10 or 20 times the typical amount, and they pull a segment's mean far above what a typical member spends. The median describes the typical member.
- A colleague reports "silhouette 0.57 with k = 2 on the raw data, much better than your 0.29". What do you say?
Show the answer
Look at the cluster sizes: the raw-data clusters separate a few huge customers from everyone else, which scores well on silhouette but tells the sales team nothing new. A higher score doesn't mean more useful segments; always check sizes and profiles.
- Why must the new customer go through the same log transform and scaler as the training data?
Show the answer
The centroids live in the transformed space. Raw spending of 15,000 would be compared with centroids around −2 to 2 and land in the wrong segment. The pipeline guarantees the same steps, with the same fitted scaling, every time.
Interview questions
How would you build a customer segmentation?
Define the business goal, choose behavioural features, handle skew (log transform) and scale, try several k with inertia and silhouette, check stability across runs, profile segments with medians and name them, validate against known labels or business sense, and deploy as a pipeline that assigns new customers.
How do you evaluate a clustering when there are no labels?
With internal measures such as the silhouette score and inertia, stability across random starts or bootstrap samples (for example with the adjusted Rand index), comparison with any labels you held back, and above all whether the clusters are interpretable and useful for the decision at hand.
Why log-transform spending data before K-means?
Spending is right-skewed, so a few large values dominate the squared distances K-means minimises, and clusters end up isolating them. The log transform compresses large values and makes ratios, such as twice as much, count equally at every scale.
Key takeaways
- Clustering has no answer key, so judge segments by separation, stability and usefulness together.
- Skewed spending must be log-transformed before scaling, or K-means just isolates the biggest customers.
- Two segments on log spending largely rediscover the business's own HoReCa/retail split; four segments add something new.
- Check stability: some values of k give different answers from different starts.
- Profile segments with medians, name them in plain words, and keep the whole transform in one pipeline for new customers.
Frequently asked questions
How many segments should a business use?
As many as it can act on differently, usually three to six. More segments are only worth it if each gets a distinct offer, message or service.
Can K-means use categorical data such as region?
Not directly, because averages of categories don't make sense. Encode them carefully, or use a method built for mixed data, such as K-prototypes.
How often should segments be recalculated?
When behaviour changes: often yearly, or after big changes in products or prices. Check how many customers would change segment before switching, so the sales team isn't confused by constant reshuffles.
What to learn next
- Find clusters of any shape, and outliers, with DBSCAN, later in this course.
- Revisit how the algorithm works in K-means clustering explained.
- Compare with a supervised project in the customer churn prediction project.