The data
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.
k-means measures similarity as straight-line distance. From (1, 2) to (2, 1) is √2 ≈ 1.41: similar customers. From (1, 2) to (7, 8) is √72 ≈ 8.49: very different. Close points belong together.
The k-means loop
We ask for k = 2 groups. k-means starts with k centres, here two of the customers: c1 = (1, 2) and c2 = (3, 3). A centre (centroid) is the point that stands for its group. This start is poor, on purpose.
Each customer joins its nearest centre. (2, 1) is 1.41 from c1 but 2.24 from c2, so it joins c1. (3, 3) is c2 itself, and the three on the right are nearer c2: c2's group has four.
Each centre moves to the mean (average) of its group. c1: mean of (1, 2) and (2, 1) is (1.5, 1.5). c2: mean of its four is (6, 6). The inertia, the total squared distance to the centres, falls from 102 to 29.
Same rule, new centres. (3, 3) is now √4.5 ≈ 2.12 from c1 but √18 ≈ 4.24 from c2, so it switches to c1. Every other customer keeps its centre. The inertia drops to 15.5.
c1 moves to the mean of (1, 2), (2, 1) and (3, 3): (2, 2). c2 moves to the mean of the other three: (7, 7). The inertia falls to 8.
One more pass: every customer keeps its centre, so the means stay put and the loop stops. k-means has converged: occasional small spenders and frequent big spenders. No step ever raises the inertia: 102, 29, 15.5, 8.
Using it well
k-means does not choose k for you. The best inertia for k = 1, 2, 3, 4 is 83, 8, 5, 2. It keeps falling as k grows, so look for the elbow, where it stops falling fast: here, k = 2.
k-means only finds a local best: a different start can end in worse groups. So it is often run several times from different starts, keeping the lowest inertia. The k-means++ start spreads the first centres apart.
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.