k-means clustering: group what is close

Split points into k groups with no answer sheet. Take turns between "join the nearest center" and "move each center to the mean of its group", and the sum of squared distances falls with every step. Press one step at a time and see why.

Short answer. k-means groups points into k clusters of nearby points, with no answers given. Put down k centers, then repeat until nothing changes: (1) every point joins the cluster of its nearest center, and (2) every center moves to the mean position of the points in its cluster. The score J = the sum, over all points, of the squared distance to their own center goes down or stays the same at every step, so it always stops. But depending on where the centers start, it can stop at a worse answer.

J (sum of squared distances)

Each press of "One step" does the next of the two steps: assign, then move the centers, then assign again. The letter in a circle names that center, and each point is drawn as the letter of the cluster it is in. Faint lines are the distances from points to their centers, and dashed arrows show where a center just moved. Changing k or pressing "New starting centers" starts over. The 30 points are made up with a fixed-seed random generator (three groups of 10), so they are the same every time you open the page. "Two long ones", "Two sizes" and "Two crescents" are made-up data for the shapes in section 9 (two true groups, starting at k = 2). A point's shape (circle ●, triangle ▲) is its true group and its color is the cluster k-means gave it.

Try this. (1) At the start (k = 3), keep pressing "One step". J goes 282.1 → 109.1 → 50.45 → 32.28, and on the fifth step (an assign step) no point changes cluster, so it stops. Each cluster has 10 points. (2) Press "New starting centers" once. All three starting centers land in the bottom group. Press on to the end and it stops after 9 steps at J = 173.34. The two upper groups become one cluster (20 points) and the bottom group is split into 8 and 2. J only went down at every step, yet the answer is bad. Press it once more and it stops at 32.28 again. (3) Reload the page, set k to 2, 3, 4, 5, 6 and press to the end each time. The final J is 177.66, 32.28, 26.8, 24.67, 21.97. It drops a lot until 3, then only a little.

Definitions

The text below uses 2D points and a few numbers. These are the textbook definitions. We split n points x₁, …, xₙ into k clusters C₁, …, Cₖ, and cⱼ is the center of cluster Cⱼ. Distance is the Euclidean distance ‖·‖.

k-means clustering
A clustering method that splits the points into k clusters that do not overlap, looking for the split with the smallest within-cluster sum of squares J below. k is chosen in advance. It is unsupervised learning: there are no answers (labels).
within-cluster sum of squares
The objective of k-means: the sum, over all points, of the squared distance from each point to the center of its own cluster. scikit-learn calls it inertia.

J=∑j=1k∑𝐱i∈Cj‖𝐱i−𝐜j‖2

centroid
The mean of the points in a cluster. When the clusters are fixed, this mean is the center position that makes J smallest. |Cⱼ| is the number of points in Cⱼ.

𝐜j=1|Cj|∑𝐱i∈Cj𝐱i

Lloyd's algorithm
The usual way to solve k-means: repeat the assignment step and the update step until no cluster changes. The assignment step puts every point into the cluster of its nearest center (formula below). The update step moves every center to the centroid of its cluster. Neither step raises J, so it always stops, but there is no guarantee that it stops at the smallest possible J.

𝐱i∈Cj*,j*=argminj‖𝐱i−𝐜j‖2

k-means++ initialization
A way to pick the starting centers. The first center is one point picked with equal chance. Each later center is a point x picked with probability proportional to D(x)², where D(x) is the distance from x to the nearest center already picked.

p(𝐱)=D(𝐱)2∑i=1nD(𝐱i)2

silhouette coefficient
For one point, let a be the mean distance to the other points in its own cluster and b the mean distance to the points of the nearest other cluster. The coefficient is the value below. It is between −1 and 1, and the mean over all points is used as the score of a clustering.

s=b−amax(a,b)

1. What k-means is: grouping with no answers

When every example comes with an answer (is this email spam or not?) and the model learns to predict it, that is supervised learning (logistic regression is one). Looking only at the data, with no answers, to find its shape is unsupervised learning. Clustering, putting nearby things into groups, is the classic example.

In k-means a person chooses the number of clusters k, and each cluster has one center. A point belongs to the cluster of its nearest center. "Near" is usually the straight-line (Euclidean) distance. The number of dimensions does not matter. 2D points and embedding vectors with hundreds of numbers are grouped the same way. Naming a cluster ("summer clothes") is a person's job. k-means only groups.

2. The procedure: two steps, repeated

start     pick k points as the centers c₁, …, c_k
repeat    (1) assign: every point joins the cluster of its nearest center
          (2) move:   every center moves to the mean of the points in its cluster
stop      when no point changes cluster in (1)

objective  J = the sum over all points of (distance to its own center)²

J measures how tight the clusters are. The closer the points sit to their own centers, the smaller it is. k-means looks for a split that makes J small, and each of the two steps only moves in a direction that does not raise J (section 4). This loop is also called Lloyd's algorithm. One step measures the distance from every point to k centers, so its cost grows with points × k × dimensions.

3. How the formula is built: why the center is the mean

Once the clusters are fixed, where should a center sit to make J as small as possible? Take three numbers in one cluster: 2, 3, 7. Call a guess for the center c. This cluster's share of J is J(c) = (2 − c)² + (3 − c)² + (7 − c)². Press "Next" and the formula grows one piece at a time (the orange piece is new), while the picture and the explanation change.

  1. Three numbers and a guess: J(c) = (2 − c)² + (3 − c)² + (7 − c)². With c = 6 it is 16 + 9 + 1 = 26. With c = 5 it is 9 + 4 + 4 = 17, with c = 4 it is 4 + 1 + 9 = 14, and with c = 3 it is 1 + 0 + 16 = 17. Somewhere near 4 looks smallest. Why: the "move the centers" step is a search for the place that makes this sum smallest.
  2. Open the brackets: J(c) = 3c² − 24c + 62. There are 3 numbers, so c² appears 3 times. Then −2c × (2 + 3 + 7) = −24c, and 2² + 3² + 7² = 62. Why: the number in front of c² is positive, so the graph is a U with exactly one lowest point.
  3. The slope: J′(c) = 6c − 24. The derivative gives the slope. It is −12 at c = 2 and 12 at c = 6. Why: at the bottom of a U the slope is 0. To the left the curve goes down (negative), to the right it goes up (positive). This is the same slope that gradient descent uses.
  4. Done: 6c − 24 = 0 → c = (2 + 3 + 7) ÷ 3 = 4. The bottom is the mean of the three numbers. With n numbers, J′(c) = 2n·c − 2(x₁ + … + xₙ) = 0, so c = (x₁ + … + xₙ) ÷ n, the mean. For 2D points, the squared distance is (difference across)² + (difference up)², so you solve across and up separately and get the mean across and the mean up.

Try this. (1) In the first step, move c to 6, 5, 4, 3. J is 26, 17, 14, 17, and each place you try leaves a gray dot on the graph. (2) In the second step, see the U-shaped curve pass through those dots. (3) In the third step, set c to 2 and the slope is −12. Set it to 4 and the slope is 0. (4) The bottom in the last step, c = 4 and J = 14, is the mean of the three numbers and the sum there.

4. Why J never goes up, and so it always stops

5. Work it out by hand: five numbers, k = 2

Group the numbers 1, 2, 4, 8, 9 into two clusters. The starting centers are the numbers 1 and 4 (center A = 1, B = 4).

StepCluster ACluster BCenters A, BJ
(1) assign1, 24, 8, 91, 40 + 1 + 0 + 16 + 25 = 42
(2) move1, 24, 8, 91.5, 70.25 + 0.25 + 9 + 1 + 4 = 14.5
(3) assign1, 2, 48, 91.5, 70.25 + 0.25 + 6.25 + 1 + 4 = 11.75
(4) move1, 2, 48, 92.33, 8.51.78 + 0.11 + 2.78 + 0.25 + 0.25 = 5.17
(5) assign1, 2, 48, 92.33, 8.55.17, nothing changed: stop
  1. (1) Assign. 2 is 1 away from 1 and 2 away from 4, so it goes to A. 8 and 9 are closer to 4, so they go to B. J is each point's squared distance to its own center: 0² + 1² + 0² + 4² + 5² = 42.
  2. (2) Move. A goes to (1 + 2) ÷ 2 = 1.5, B goes to (4 + 8 + 9) ÷ 3 = 7. J falls to 14.5.
  3. (3) Assign. 4 is 2.5 from 1.5 and 3 from 7, so it moves to A. J = 11.75.
  4. (4) Move. A goes to (1 + 2 + 4) ÷ 3 = 7 ÷ 3 ≈ 2.33, B goes to (8 + 9) ÷ 2 = 8.5. J ≈ 5.17.
  5. (5) Assign. 4 is 1.67 from 2.33 and 4.5 from 8.5, so it stays in A. Nothing changed, so it stops. J went 42 → 14.5 → 11.75 → 5.17 and never went up.

6. Properties worth knowing

PropertyIn plain wordsIn the experiment
J goes down or staysNeither step raises J, so it always stopsThe J history never goes up
The start changes the answerWhere it stops is not guaranteed to be the best answerTry this (2): 173.34 versus 32.28
A center is the mean of its clusterOnce the clusters are fixed, the mean is the place that makes J smallestc = 4 in section 3
Borders are straight linesThe border between two neighboring centers is where they are equally far. So it suits round clusters of similar sizeSection 9
It uses distance, so scale mattersAn axis with big units takes over the distance. Put the axes on the same scale firstSection 9, normalization

7. Starting centers and k-means++

The experiment picks its starting centers at random from the points. As in "Try this" (2), several centers can then land in one group and it stops at a bad answer. There are two common fixes. One is to run it from several starts and keep the result with the smallest J. The other is k-means++. The first center is a random point. Each later center is a point picked with probability proportional to "the squared distance to the nearest center already picked". Far points are more likely to be picked, so the starting centers spread out. scikit-learn's KMeans uses k-means++ by default.

p(x) = D(x)² ÷ (D(x₁)² + D(x₂)² + … + D(xₙ)²)

Each press of "Next" picks one more center (k = 3). The size of a point is its probability of being picked in that step, drawn on the same scale in all three steps. The picks use a fixed-seed random generator, so they are the same every time you open the page.

8. Choosing k: the elbow and the silhouette

The elbow. Plot the smallest J you can get for each k. More clusters means points are closer to a center, so J only goes down, and it reaches 0 when k equals the number of points. So do not pick "the k with the smallest J". Pick the place where the drop suddenly gets small (where the line bends like an elbow). With this page's 30 points, running 20 different starts for each k and keeping the smallest J gives 149.14, 32.28, 25.66, 20.44, 16.75 for k = 2, 3, 4, 5, 6. The bend is at 3.

050100150 23456number of clusters k smallest J 149.1432.2825.6620.4416.75 the bend: k = 3
The elbow. The same numbers as the paragraph above. From k = 2 to 3, J drops by 116.86. From 3 to 4 it drops by only 6.62.

The silhouette. For each point, let a = the mean distance to the other points in its own cluster and b = the mean distance to the points of the nearest other cluster, then compute s = (b − a) ÷ (the larger of a and b). It runs from −1 to 1, and closer to 1 means the point sits well inside its own cluster. Pick the k with the highest average over all points.

9. Shapes k-means gets wrong

In k-means the border between two clusters is where the two centers are equally far: a straight line that cuts the segment between the centers at a right angle, through its middle. So k-means quietly assumes the clusters are round blobs of similar size and spread, and it does poorly on the following.

10. When to use what

OptionGoodBadUse it when
k-meansSimple and fast. One step costs points × k × dimensions, so it works on big dataYou must choose k. It assumes round clusters of similar size. The start and outliers can throw it offThe clusters are roughly round blobs. You want to boil many vectors down to a few representatives (IVF, PQ)
Hierarchical clusteringMerges the closest groups one by one, and you can see the whole merge history as a tree (dendrogram). You choose k later by where you cut the treeIt works with the distance between every pair of points, so it gets slow and uses a lot of memory with many points. A merge is never undoneThere are not too many points, and you want to see groups inside groups
DBSCANNo k needed. It follows dense areas, so it finds crescents and rings. Points that belong nowhere are set aside as noiseYou must choose a radius and a minimum number of neighbors. If clusters differ in density, one radius cannot fit them allThe shapes are irregular and noise points are mixed in
Gaussian mixtureLearns a separate ellipse for each cluster, with its own shape, tilt and size. Gives each point "the probability it belongs to this cluster"Slower than k-means, with more numbers to fit. You must choose k, and the start can throw it offClusters are tilted or stretched ellipses of different sizes. You want probabilities, not a hard split

The experiment below takes "Two crescents" from section 9 (40 points) and puts k-means (k = 2) on the left and DBSCAN on the right. DBSCAN has four rules.

core point    at least m points within radius ε (itself included)
border point  not a core point, but within radius ε of some core point
noise         not within radius ε of any core point
cluster       a point within radius ε of a core point is in the same cluster as it, so clusters spread from neighbor to neighbor
Minimum points m = 4 (fixed)

Left: color is the k-means cluster, the dashed line is the straight border. Right: ● core point, ○ border point, × noise. Gray points are not in a cluster yet, and arrows show where a cluster spread in this step.

Try this. (1) At ε = 0.8, press "Next" to the end (11 waves). It ends with two clusters and 2 noise points, one crescent per cluster. On the left, k-means grouped 11 points wrongly. (2) Raise ε to 1 and the two crescents join into one cluster. (3) Lower ε to 0.6 and you get three clusters and 23 noise points.

Where it is used

Frequently asked questions

Are k-means and k-nearest neighbors (kNN) the same thing?

No. Only the names are alike. k-nearest neighbors takes points that already have answers, finds the k closest to a new point, and uses their answers to decide the new point's answer. There k is the number of neighbors. k-means groups points into k clusters with no answers at all, and k is the number of clusters.

I get a different result every run. Is it broken?

It is not broken. k-means starts from its starting centers, only moves in ways that do not raise J, and stops when nothing changes. A different start can stop somewhere else. Run it from several starts and keep the result with the smallest J, and pick the starts with k-means++ so the result moves around less. To get the same result again, fix the random seed.

How do I choose the number of clusters k?

There is no single right answer. Try several k and look for the point where J suddenly stops dropping much (the elbow), or for the k with the highest silhouette score. Sometimes the use decides it. If you only make clothes in three sizes, k = 3.

Words

Words used hereWhat books call it
learning with no answers · learning from answersunsupervised learning · supervised learning
grouping what is close, a groupclustering, a cluster
centercentroid
assign · move the centersassignment step · update step
the two steps, repeatedLloyd's algorithm
sum of squared distances Jobjective, within-cluster sum of squares, inertia (scikit-learn)
straight-line distanceEuclidean distance
stopping because nothing changesconvergence
lowest only in its neighborhoodlocal minimum
spreading out the starting centersk-means++ initialization
elbow · silhouetteelbow method · silhouette coefficient
grouping by merging, the tree picturehierarchical clustering, dendrogram
grouping by following dense areasdensity-based clustering, DBSCAN
grouping where each cluster learns an ellipseGaussian mixture model (GMM)
searching by splitting into cellsinverted file index (IVF)

Sources

← k-nearest neighborsSupport vector machines →