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:
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.
# 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)