Gradient LabOpen in Gradient Lab

Lessons › Projects

Find customer segments with k-means

Customer groups discovered from shopping behaviour alone, with no labels, plus a chart of the segments.

No setup needed. Run every step in your browser on Gradient Lab, or download it.

Open the notebook

Level: Intermediate · Time: 30 min · You’ll practise: scaling, k-means, elbow method, describing clusters

Steps

1. 280 customers: visits per month and average spend

Generate 280 synthetic customers described by visits per month and average spend.

rng = np.random.default_rng(5)
groups = [(2, 300, 60), (12, 400, 100), (6, 2500, 120)]       # (visits, spend, how many)
rows = []
for visits, spend, count in groups:
    rows.append(np.column_stack([rng.normal(visits, 1.5, count).clip(0.5), rng.normal(spend, spend * 0.25, count).clip(50)]))
data = pd.DataFrame(np.vstack(rows), columns=["visits", "spend"]).round(1)
print(data.describe().round(0))

2. Scale, because spend (thousands) would drown out visits

Scale both columns. Otherwise spend (thousands) would drown out visits (tens).

X = StandardScaler().fit_transform(data)

3. The elbow method: try k = 1..8

Try k from 1 to 8 and watch how much tighter the clusters get. The “elbow” suggests a good k.

inertias = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_ for k in range(1, 9)]
for k, v in enumerate(inertias, 1):
    print(f"k = {k}: spread inside clusters {v:7.1f}")
print("Look for the 'elbow' where adding clusters stops helping much.")

4. Fit k = 3 and describe each segment

Fit k = 3 and describe each segment with its size and averages. Now give them names!

km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
data["segment"] = km.labels_
print(data.groupby("segment").agg(customers=("visits", "size"), visits=("visits", "mean"), spend=("spend", "mean")).round(1))

5. Plot

Save a scatter plot colored by segment.

plt.figure(figsize=(6, 4.5))
plt.scatter(data.visits, data.spend, c=data.segment, cmap="viridis", alpha=.7)
plt.xlabel("visits per month"); plt.ylabel("average spend"); plt.title("Customer segments (k = 3)")
plt.tight_layout(); plt.savefig("segments.png"); print("Saved segments.png")

Expected output

$ python segments.py
       visits   spend
count   280.0   280.0
mean      7.0  1276.0
std       4.0  1150.0
min       0.0   139.0
25%       4.0   330.0
50%       7.0   482.0
75%      11.0  2463.0
max      16.0  3757.0
k = 1: spread inside clusters   560.0
k = 2: spread inside clusters   261.5
k = 3: spread inside clusters    67.3
k = 4: spread inside clusters    44.9
k = 5: spread inside clusters    36.0
k = 6: spread inside clusters    29.4
k = 7: spread inside clusters    24.3
k = 8: spread inside clusters    20.2
Look for the 'elbow' where adding clusters stops helping much.
         customers  visits   spend
segment                           
0              102    12.1   405.4
1              116     6.1  2555.3
2               62     1.9   313.0
Saved segments.png

Stretch goals

Download p07-customer-segments.zip