MyMisPal
← Practical AI lessons
Lesson 7 of 11

Customer segments: k-means clustering

Nakhla's marketing team sends the same offer to every customer, with poor results. Better to split them into similar segments and speak to each one differently. The catch: there are no ready answers (no “segment” column). That's where clustering comes in.

k-means is the best-known clustering algorithm. You choose the number of segments k, then it repeats two steps until nothing changes: (1) assign: each customer joins the nearest centre. (2) update: each centre moves to the average of its customers. Try it step by step:

0100200300024681012Visits per monthAverage basket (SAR)

The centres (✚) start in arbitrary places. Press “Assign customers”.

The model doesn't name the segments; you, the analyst, interpret them: “many visits, small basket” = daily grocery buyers; “few visits, big basket” = occasions and gifts. Then the decision: volume offers for the first, gift packaging for the second.

PYTHON
# customers: [visits per month, basket in tens of SAR]
customers = [[2, 4], [3, 5], [2, 5], [9, 6], [10, 4], [8, 7], [4, 21], [3, 19], [5, 23]]
centers = [[2, 5], [9, 5], [4, 20]]

def nearest(p):
    best, best_d = 0, None
    for i, c in enumerate(centers):
        d = ((p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2) ** 0.5
        if best_d is None or d < best_d:
            best, best_d = i, d
    return best

for p in customers:
    print(p, "-> segment", nearest(p) + 1)
Watch outIn marketing you'll often meet RFM: recency (last purchase), frequency and monetary value. These three make excellent k-means features, and you can build them with SQL from the orders table.

Exercises

Exercise 1 · Ordering

Put the k-means steps in order:

  1. 1Choose k and place starting centres
  2. 2Assign each customer to the nearest centre
  3. 3Repeat assign and update until nothing changes
  4. 4Interpret the segments and turn them into decisions
  5. 5Move each centre to the average of its customers
Exercise 2 · Multiple choice

What's the key difference between clustering and classification?

Exercise 3 · Python · graded by running

You have 3 segment centres. Write a function nearest(p) that returns the index (0, 1 or 2) of the centre closest to customer p.

Spotted a mistake on this page, or have an idea to improve the site?