0369369visits / month →spend (KD)1.418.49model = the centresc1 (x, y)c2 (x, y)inertia1cs = [pts[0], pts[2]]2while True:3 g = assign(pts, cs)4 new = means(pts, g)5 if new == cs: break6 cs = newk =123483852c1c2
Standing map: six customers · khaki = no group yet · blue = c1's group, orange = c2's groupTeal block: the model, which is just the two centres, and the inertiaRound markers: the centres · spokes: which centre each customer is nearestAt the back, six café customers on a map of visits per month and spend per visit; nobody has labelled them. Beside it, the model of k-means: just its centres, and the inertia, the total squared distance from each customer to its centre. k-means repeats two moves: every customer joins its nearest centre (the spokes and colours), then every centre moves to the mean of its customers. From a poor start one customer switches, the centres settle at (2, 2) and (7, 7), and the inertia falls 102, 29, 15.5, 8. In front: the loop in Python, and the best inertia for k = 1 to 4, whose elbow at k = 2 is how you pick k.

The data

  1. Six café customers, each a dot: visits per month across, spend per visit up. Nobody labelled them. Clustering, a kind of unsupervised learning, finds groups of similar points by itself. We use the classic algorithm, k-means.

The k-means loop

Using it well

What happens

;; step 1/10 · task
customer   visits/month   spend/visit (KD)
  0        1              2
  1        2              1
  2        3              3
  3        6              6
  4        7              8
  5        8              7

no labels: nobody says which group a customer is in
clustering = unsupervised learning: find the groups

Distance mixes the features, so features in different units are usually scaled first (for example to mean 0 and standard deviation 1); otherwise the feature with the biggest numbers decides the groups. The elbow numbers are the best inertia over every possible split of the six customers into k groups, found by checking them all. On real data you run k-means for each k and plot its inertia.