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.
- 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ⱼ.
- 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.
- 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.
- 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.
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)²
k: the number of clusters, chosen by a person.c₁, …, c_k: the centers, one for each cluster.J: the objective, 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.
- 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. - 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. - 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. - 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, soc = (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
- Assigning never raises J. A point that changes cluster moves to a closer center, so its share shrinks. A point that stays keeps the same share.
- Moving never raises J either. As section 3 showed, the mean is the place inside a cluster that makes J smallest. The old position was one of the candidates, so moving to the mean lowers J or keeps it the same.
- So it stops. When clusters change, J really drops (apart from the rare case of exactly equal distances), so it never comes back to a split it has already left. There are only finitely many ways to split n points into k clusters, so it must stop. Experiment 1 stopped after five steps.
- Where it stops is not guaranteed to be the best answer. It is just a place where neither step changes anything. In "Try this" (2) it stopped at J = 173.34, while the same points can be grouped with J = 32.28. Such a place is called a local minimum.
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).
| Step | Cluster A | Cluster B | Centers A, B | J |
|---|---|---|---|---|
| (1) assign | 1, 2 | 4, 8, 9 | 1, 4 | 0 + 1 + 0 + 16 + 25 = 42 |
| (2) move | 1, 2 | 4, 8, 9 | 1.5, 7 | 0.25 + 0.25 + 9 + 1 + 4 = 14.5 |
| (3) assign | 1, 2, 4 | 8, 9 | 1.5, 7 | 0.25 + 0.25 + 6.25 + 1 + 4 = 11.75 |
| (4) move | 1, 2, 4 | 8, 9 | 2.33, 8.5 | 1.78 + 0.11 + 2.78 + 0.25 + 0.25 = 5.17 |
| (5) assign | 1, 2, 4 | 8, 9 | 2.33, 8.5 | 5.17, nothing changed: stop |
- (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) Move. A goes to (1 + 2) ÷ 2 = 1.5, B goes to (4 + 8 + 9) ÷ 3 = 7. J falls to 14.5.
- (3) Assign. 4 is 2.5 from 1.5 and 3 from 7, so it moves to A. J = 11.75.
- (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) 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
| Property | In plain words | In the experiment |
|---|---|---|
| J goes down or stays | Neither step raises J, so it always stops | The J history never goes up |
| The start changes the answer | Where it stops is not guaranteed to be the best answer | Try this (2): 173.34 versus 32.28 |
| A center is the mean of its cluster | Once the clusters are fixed, the mean is the place that makes J smallest | c = 4 in section 3 |
| Borders are straight lines | The border between two neighboring centers is where they are equally far. So it suits round clusters of similar size | Section 9 |
| It uses distance, so scale matters | An axis with big units takes over the distance. Put the axes on the same scale first | Section 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ₙ)²)
x: one point.x₁, …, xₙare all the points andnis how many there are (30 in the experiment below).D(x): the distance from point x to the nearest center picked so far. A point that is already a center has 0, so it is never picked again.p(x): the probability that point x is picked as the next center. The p of all points add up to 1. For the first center every point has the same 1/n.
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.
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.
- Long, thin clusters. If two long clusters lie side by side, it may cut across their length and mix the two, instead of following each one. That cut can give a smaller J. In the top experiment, pick "Two long ones" and press to the end: it cuts the two bands into a left and a right half, stops at J = 61.12, and groups 13 of the 30 points wrongly. Splitting along the bands gives a bigger J, 124.59.
- Clusters of different sizes. If a small cluster sits next to a big, spread-out one, the border is halfway between the two centers, so the edge points of the big cluster spill into the small one. Pick "Two sizes" (a big group of 30 and a small group of 8) and press to the end: 3 points of the big group end up with the small one, and it stops at J = 89.87. Splitting by the true groups gives J = 97.61.
- Axes on different scales. If one axis is in dollars and the other in centimeters, the dollars decide almost all of the distance. Standardize the axes first.
- Rings, crescents and outliers. Shapes that are not round get cut into blobs, and one far-away point pulls the mean toward it. Pick "Two crescents" and press to the end: 11 of the 40 points are grouped wrongly (J = 80.33, versus 122.35 for the true groups). The experiment in section 10 groups the same points with DBSCAN.
10. When to use what
| Option | Good | Bad | Use it when |
|---|---|---|---|
| k-means | Simple and fast. One step costs points × k × dimensions, so it works on big data | You must choose k. It assumes round clusters of similar size. The start and outliers can throw it off | The clusters are roughly round blobs. You want to boil many vectors down to a few representatives (IVF, PQ) |
| Hierarchical clustering | Merges 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 tree | It 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 undone | There are not too many points, and you want to see groups inside groups |
| DBSCAN | No k needed. It follows dense areas, so it finds crescents and rings. Points that belong nowhere are set aside as noise | You must choose a radius and a minimum number of neighbors. If clusters differ in density, one radius cannot fit them all | The shapes are irregular and noise points are mixed in |
| Gaussian mixture | Learns 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 off | Clusters 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
ε(epsilon): the radius that counts as "neighbor". Change it with the slider.m: the smallest number of points a core point needs. Fixed at 4 here.
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
- Indexes for vector search (IVF). Group the vectors with k-means ahead of time, and when a query comes in, open only the few nearest clusters. The representatives that PQ uses to shorten vectors are also made with k-means. See section 5 of vector search (that page writes the number of clusters as c so it is not confused with k, the number of results).
- Grouping embeddings. Cluster the embeddings of documents or products to find topics of similar items. For vectors scaled to length 1, the squared distance is
2 − 2 × cosine similarity, so ranking by straight-line distance gives the same order as ranking by cosine. - Reducing colors. Replace the pixel colors of an image with k representative colors. The representative colors are the cluster centers.
- Splitting customers or records. Split customers into a few groups by numbers such as purchase history and treat each group differently. Put the axes on the same scale first.
- Together with PCA. With many dimensions, shrink them with principal component analysis before clustering, or flatten the clustered result to 2D to look at it.
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 here | What books call it |
|---|---|
| learning with no answers · learning from answers | unsupervised learning · supervised learning |
| grouping what is close, a group | clustering, a cluster |
| center | centroid |
| assign · move the centers | assignment step · update step |
| the two steps, repeated | Lloyd's algorithm |
| sum of squared distances J | objective, within-cluster sum of squares, inertia (scikit-learn) |
| straight-line distance | Euclidean distance |
| stopping because nothing changes | convergence |
| lowest only in its neighborhood | local minimum |
| spreading out the starting centers | k-means++ initialization |
| elbow · silhouette | elbow method · silhouette coefficient |
| grouping by merging, the tree picture | hierarchical clustering, dendrogram |
| grouping by following dense areas | density-based clustering, DBSCAN |
| grouping where each cluster learns an ellipse | Gaussian mixture model (GMM) |
| searching by splitting into cells | inverted file index (IVF) |
Sources
- Stuart P. Lloyd, Least squares quantization in PCM, IEEE Transactions on Information Theory. The loop "assign to the nearest representative, then move each representative to the mean".
- scikit-learn documentation: Clustering (k-means and inertia, k-means++, hierarchical clustering, DBSCAN, and how they compare).
- scikit-learn documentation: KMeans (the default way to pick starting centers, running several starts).
- scikit-learn documentation: silhouette_score (the definition of the silhouette coefficient).