K-means divides $N$ vectors into $K$ clusters by alternating two steps: assign each vector to its nearest centroid, then move each centroid to the mean of its members. Neither step can raise the residual sum of squares, $\mathrm{RSS} = \sum_k \sum_{\vec{x} \in \omega_k} \lvert \vec{x} - \vec{\mu}(\omega_k) \rvert^2$, and the update lowers it by $n_k$ times the squared distance each centroid moves. With a consistent tie rule the algorithm therefore stops, but only at a local minimum: on six points in the plane, 8 of the 15 seed pairs end at RSS 10.67 against the optimum 7.875 (under the script's tie rule), and on a stretched rectangle the ratio is unbounded. Finding the optimum is NP-hard. Each iteration costs $O(KNM)$, and every cluster lies in a convex Voronoi cell.
The test of the cluster hypothesis split the 1,400 Cranfield abstracts into 10, 25 and 50 clusters with k-means, 30 times for each number, each run from different starting points drawn at random by a careful seeding rule, k-means++. What was each run trying to improve, and why is the procedure guaranteed to stop? Each run was lowering one number, the total squared distance from the documents to the centers of their clusters. It must stop because neither of its two steps can raise that number and there are only finitely many clusterings to pass through.
K-means is among the most widely used clustering algorithms, in text processing and well beyond it. It represents each cluster by a single point, its centroid, and alternates between two simple steps: assign every document to its nearest centroid, then move every centroid to the mean of its documents. The procedure is easy to state, fast enough for large collections, and guaranteed to stop.
Here is the route. First we state the objective, the residual sum of squares, which the later articles use without redefining it. Then we trace the algorithm by hand on six points. Next we prove that each step lowers the objective, which is why the algorithm stops. Finally we see that it can stop at the wrong answer, and what it costs. The article follows Manning, Raghavan, and Schütze (2008, §16.4).
The objective
Documents are represented as vectors, usually length-normalized TF-IDF vectors. Then the Euclidean distance between two documents reflects their cosine similarity. The goal is to divide $N$ document vectors $\vec{x}_1, \dots, \vec{x}_N$ into $K$ clusters $\omega_1, \dots, \omega_K$, where $K$ is chosen in advance. Each cluster has a centroid, the mean of its members:
$$\vec{\mu}(\omega_k) = \frac{1}{\lvert \omega_k \rvert} \sum_{\vec{x} \in \omega_k} \vec{x}.$$
A good clustering has members close to their centroids. K-means measures this with the residual sum of squares (RSS), the total squared distance from each document to its cluster's centroid:
$$\mathrm{RSS} = \sum_{k=1}^{K} \sum_{\vec{x} \in \omega_k} \lvert \vec{x} - \vec{\mu}(\omega_k) \rvert^2.$$
This is equation 16.7 of the course text. Each inner sum is the RSS of one cluster, written $\mathrm{RSS}_k$. Smaller RSS means tighter clusters, and k-means tries to minimize it. Divided by $N$, the RSS is the mean squared error of a quantizer that replaces each vector by its centroid, the measure that product quantization uses to compress vectors. The distances are squared, which has two consequences used below:
- the best single point to represent a cluster is exactly its mean;
- a document far from its centroid costs far more than one near it, so outliers pull hard on the result.
Why not simply search for the clustering with the smallest RSS? Because finding it is computationally hard. It is NP-hard even for two clusters in general dimensions (Aloise, Deshpande, Hansen, and Popat, 2009, Theorem 1). The number of candidate clusterings also grows explosively. The number of ways to divide $N$ objects into $K$ nonempty clusters is the Stirling number of the second kind,
$$S(N, K) = \frac{1}{K!} \sum_{j=0}^{K} (-1)^j \binom{K}{j} (K - j)^N.$$
Six points can be split into two nonempty clusters in $S(6, 2) = (2^6 - 2)/2 = 31$ ways. For the $N = 7{,}487$ news stories and $K = 6$ clusters of K-means in practice, the leading term $6^N / 6!$ dominates, and $S(7487, 6)$ is a number of 5,824 digits. No search can try them all. K-means settles for a heuristic that improves the clustering step by step.
The algorithm
The algorithm is usually credited to Stuart Lloyd, who described it in 1957 in a Bell Laboratories manuscript published only in 1982 (Lloyd, 1982), and to James MacQueen, who gave it the name k-means (MacQueen, 1967). The course text lists them among the authors often credited with it and gives the algorithm as its Figure 16.5 (Manning, Raghavan, and Schütze, 2008, §16.4, §16.6).
- Initialize. Choose $K$ starting centroids, for example $K$ documents picked at random. These are called the seeds.
- Assign. Assign each document to the cluster whose centroid is nearest.
- Update. Recompute each centroid as the mean of the documents now assigned to it.
- Repeat steps 2 and 3 until the assignments stop changing, or another stopping criterion is met: a fixed number of iterations, centroids that no longer move, or RSS that falls by less than a threshold.
The two steps solve two easier halves of the hard problem. With the centroids held fixed, the best assignment is obvious: send each document to its nearest centroid. With the assignment held fixed, the best centroids are obvious too: the means. K-means alternates between the two halves, each time solving one exactly while holding the other fixed.
Step 3 needs a rule for one case. The mean of a cluster is defined only if the cluster has members, and the assignment step can leave a cluster with none. Seeds chosen from the documents cannot be empty after the first assignment, provided no two seeds have the same vector, since each seed is at distance zero from itself and at a positive distance from the others. Later iterations can still empty a cluster, as Problem 2 below shows with seven points on a line. Common rules are to keep the empty cluster's old centroid, to drop the cluster, or to restart it from a document far from its current centroid. The scripts behind this unit keep the old centroid.
A worked example
Documents have thousands of dimensions, but the algorithm does exactly the same thing in two, where we can watch it. Six points in the plane, clustered into $K = 2$ clusters, with points $A$ and $B$ as the seeds:
| Point | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| Coordinates | (1, 1) | (1.5, 2) | (3, 4) | (5, 7) | (3.5, 5) | (4.5, 5) |
The table below gives, for each point and each iteration, the squared distance to the first centroid, then to the second, and the cluster the point is assigned to. Squared distances are enough for the assignment, since the nearer centroid is the same whether distances are squared or not. They are also what RSS adds up. All values are exact.
| Point | Iteration 1: centroids (1, 1), (1.5, 2) | Iteration 2: centroids (1, 1), (3.5, 4.6) | Iteration 3: centroids (1.25, 1.5), (4, 5.25) |
|---|---|---|---|
| A | 0 / 1.25 → 1 | 0 / 19.21 → 1 | 0.3125 / 27.0625 → 1 |
| B | 1.25 / 0 → 2 | 1.25 / 10.76 → 1 | 0.3125 / 16.8125 → 1 |
| C | 13 / 6.25 → 2 | 13 / 0.61 → 2 | 9.3125 / 2.5625 → 2 |
| D | 52 / 37.25 → 2 | 52 / 8.01 → 2 | 44.3125 / 4.0625 → 2 |
| E | 22.25 / 13 → 2 | 22.25 / 0.16 → 2 | 17.3125 / 0.3125 → 2 |
| F | 28.25 / 18 → 2 | 28.25 / 1.16 → 2 | 22.8125 / 0.3125 → 2 |
Iteration 1. With centroids at $A = (1, 1)$ and $B = (1.5, 2)$, point $A$ is nearest the first centroid. Every other point, including $B$ itself, is nearest the second. The clusters are $\{A\}$ and $\{B, C, D, E, F\}$. RSS, measured from the seeds, is the sum of each point's squared distance to its own centroid: $0 + 0 + 6.25 + 37.25 + 13 + 18 = 74.5$. Updating leaves the first centroid at $A$ and moves the second to the mean of its five points,
$$\left(\tfrac{1.5 + 3 + 5 + 3.5 + 4.5}{5},\ \tfrac{2 + 4 + 7 + 5 + 5}{5}\right) = (3.5,\ 4.6),$$
and RSS falls to 20.7.
Example (which point moves next). Point $B$ is the one point that changes cluster in the next assignment step. The second centroid has moved from $B$ to $(3.5, 4.6)$, among $C$, $D$, $E$ and $F$. So $B$'s own centroid has moved away from it, and the first centroid, at $A$, is now nearer.
Iteration 2. Point $B$ is now at squared distance 1.25 from $(1, 1)$ and 10.76 from $(3.5, 4.6)$, so it changes cluster. That single move lowers RSS by $10.76 - 1.25 = 9.51$, from 20.7 to 11.19. The clusters are $\{A, B\}$ and $\{C, D, E, F\}$. Updating moves the centroids to $(1.25, 1.5)$ and $(4, 5.25)$, and RSS falls to 7.875.
Iteration 3. No point changes cluster, so the centroids do not move, and the algorithm stops with RSS 7.875.
| Step | Clusters | RSS |
|---|---|---|
| Assignment 1 | {A}, {B, C, D, E, F} | 74.5 |
| Update 1 | same | 20.7 |
| Assignment 2 | {A, B}, {C, D, E, F} | 11.19 |
| Update 2 | same | 7.875 |
| Assignment 3 | no change: stop | 7.875 |
RSS fell at every step. That is not a coincidence, and the next section shows why. This clustering is also the best possible one: checking all 31 ways of splitting the six points in two, none has RSS below 7.875. The next best, $\{A, B, C\}$ and $\{D, E, F\}$, has 10.67, and it will reappear below.
Why k-means converges
RSS fell at every step of the trace. It never rises in any run, and with a consistent rule for ties that is enough to make the algorithm stop. Here is the plan of the argument, in three parts (Manning, Raghavan, and Schütze, 2008, §16.4):
- the assignment step never increases RSS;
- the update step never increases RSS;
- RSS cannot decrease forever.
The assignment step
RSS is a sum of one term per document, its squared distance to the centroid of the cluster it belongs to. With the centroids fixed, each term depends only on that document's own assignment. So the sum is smallest when each document is assigned to minimize its own term, which is exactly what the assignment step does. A document that moves goes from a centroid at squared distance $d_{\text{old}}$ to one at $d_{\text{new}} < d_{\text{old}}$, and RSS drops by $d_{\text{old}} - d_{\text{new}}$. Iteration 2 above shows this with $B$: $10.76 - 1.25 = 9.51$.
The update step
Here is the idea in one sentence. For numbers on a line, the point that minimizes the sum of squared distances to them is their mean, and the same holds in any number of dimensions, one coordinate at a time.
The formal version. With the assignment fixed, the clusters can be treated one at a time, since moving one cluster's centroid changes only that cluster's term. For cluster $\omega_k$ with $n_k$ members, consider its RSS as a function of where the centroid is put, a free point $\vec{v}$ with components $v_1, \dots, v_M$:
$$\mathrm{RSS}_k(\vec{v}) = \sum_{\vec{x} \in \omega_k} \lvert \vec{v} - \vec{x} \rvert^2 = \sum_{\vec{x} \in \omega_k} \sum_{m=1}^{M} (v_m - x_m)^2.$$
This is a sum of squares in each coordinate separately, so it can be minimized one coordinate at a time. Its partial derivative in $v_m$ is
$$\frac{\partial\, \mathrm{RSS}_k(\vec{v})}{\partial v_m} = \sum_{\vec{x} \in \omega_k} 2 (v_m - x_m) = 2 n_k v_m - 2 \sum_{\vec{x} \in \omega_k} x_m.$$
Setting it to zero gives $v_m = \frac{1}{n_k} \sum_{\vec{x} \in \omega_k} x_m$, the $m$th coordinate of the mean. The second derivative is $2 n_k > 0$, so this is a minimum, not a maximum. The mean is therefore the unique best position for the centroid. Replacing the old centroid with the mean can only lower $\mathrm{RSS}_k$ (Manning, Raghavan, and Schütze, 2008, §16.4, equations 16.8 to 16.10).
A second way to see the same fact also says how much RSS falls. Write $\vec{\mu}$ for the mean of the cluster and expand each squared distance around it:
$$\lvert \vec{x} - \vec{v} \rvert^2 = \lvert (\vec{x} - \vec{\mu}) + (\vec{\mu} - \vec{v}) \rvert^2 = \lvert \vec{x} - \vec{\mu} \rvert^2 + 2 (\vec{x} - \vec{\mu}) \cdot (\vec{\mu} - \vec{v}) + \lvert \vec{\mu} - \vec{v} \rvert^2.$$
Summing over the cluster, the middle term vanishes, because $\sum_{\vec{x}} (\vec{x} - \vec{\mu}) = n_k \vec{\mu} - n_k \vec{\mu} = \vec{0}$. What remains is
$$\mathrm{RSS}_k(\vec{v}) = \mathrm{RSS}_k(\vec{\mu}) + n_k \lvert \vec{\mu} - \vec{v} \rvert^2.$$
Moving a centroid from $\vec{v}$ to the mean lowers RSS by exactly $n_k$ times the squared distance it moves. Back to the six points. In the first update, the second centroid moved from $(1.5, 2)$ to $(3.5, 4.6)$, a squared distance of $2^2 + 2.6^2 = 10.76$, with five members. So RSS fell by $5 \times 10.76 = 53.8$, from 74.5 to 20.7.
Example (the second update). In the second update RSS falls by 3.315. The two centroids move by squared distances $0.3125$ and $0.6725$, with two and four members, so the drop is $2 \times 0.3125 + 4 \times 0.6725 = 0.625 + 2.69 = 3.315$, from 11.19 to 7.875, as in the trace. No distances to individual points are needed.
Termination
RSS therefore never increases. There are finitely many ways to assign $N$ documents to $K$ clusters, and each set of assignments determines its centroids and so its RSS. Suppose the algorithm changes the assignment only when RSS strictly falls. Then it can never return to a clustering it has left. So after finitely many steps it must reach a clustering where neither step changes anything.
That supposition holds when a tied document stays where it is. Under the other common rule, which sends a tied document to the cluster with the lowest index, a document can change cluster without lowering RSS, and the argument needs one more step. Write the cost of an assignment for its RSS measured from its own means. Suppose an iteration does not lower the cost. Then its assignment step lowered nothing and its update step lowered nothing, so the new means equal the centroids the iteration started with, because the mean is the unique minimizer. The next assignment step then uses the same centroids with the same deterministic rule. It reproduces the assignment, and the algorithm stops. So every iteration before the last strictly lowers the cost, no assignment recurs, and the algorithm stops under either rule.
The argument covers empty clusters under the rule above. RSS is a sum over documents, and an empty cluster contributes no term to it. Keeping its old centroid changes nothing in the update step, and a document that later moves to that centroid moves because it is nearer, which lowers RSS as before.
The finite count gives no useful bound on the number of iterations. Since clusters may become empty, it allows as many as the number of partitions into at most $K$ clusters, $\sum_{j=1}^{K} S(N, j)$, which is about $K^N / K!$. The worst case is known not to be polynomial in $N$. Arthur and Vassilvitskii (2006) constructed point sets and starting centroids on which k-means takes $2^{\Omega(\sqrt{N})}$ iterations. They showed that the time is still superpolynomial, with high probability, when the seeds are drawn at random from the data. Their constructions use a number of clusters and dimensions that grows with $N$. In most cases the algorithm quickly reaches convergence, or a clustering close enough to it that further iterations would move only a few documents (Manning, Raghavan, and Schütze, 2008, §16.4).
The proviso about strict decrease is why ties need care. A document equally close to two centroids contributes the same to RSS in either cluster. If ties were broken differently from one iteration to the next, the algorithm could cycle among clusterings of equal cost. The fix is a consistent rule. The course text suggests sending a tied document to the cluster with the lowest index (Manning, Raghavan, and Schütze, 2008, §16.4). Another common rule lets a tied document stay where it is.
The script behind this article uses a rule of its own that combines the two. A document tied between its current cluster and another stays where it is. In the first assignment step, when no document has a cluster yet, a tie goes to the cluster with the lower number, and the clusters are numbered in the order of their seeds. Under this rule the assignment changes only when RSS strictly falls, apart from the first step, which cannot be part of a cycle. So the first argument above covers it. One number below depends on this rule, and it is flagged there.
Local minima
A common misreading of the proof is "RSS falls at every step, so k-means finds the clustering with the lowest RSS." Convergence is guaranteed, but only to a local minimum: a clustering that neither step can improve, which may still be far from the best possible.
The same six points show it. Start from seeds $D = (5, 7)$ and $E = (3.5, 5)$ instead of $A$ and $B$. Every point except $D$ is nearer $E$, so the first clusters are $\{D\}$ and $\{A, B, C, E, F\}$. The second centroid moves to $(2.7, 3.4)$, which leaves $F$ nearer $D$, so $F$ switches in the second iteration. The centroids move again, and $E$ follows in the third. In the fourth iteration nothing changes, and the algorithm stops at $\{A, B, C\}$ and $\{D, E, F\}$, with centroids $(1.83, 2.33)$ and $(4.33, 5.67)$ (rounded). RSS fell through 37.5, 21.5, 19.95, 16.375 and 13.375 to 10.67. It decreased at every step exactly as the proof requires, and still ended higher than before.
The full trace, in the layout of the first one: squared distance to the first centroid, then to the second, then the cluster. The first three iterations are exact, and the fourth is rounded to two decimals.
| Point | Iteration 1: (5, 7), (3.5, 5) | Iteration 2: (5, 7), (2.7, 3.4) | Iteration 3: (4.75, 6), (2.25, 3) | Iteration 4: (4.33, 5.67), (1.83, 2.33) |
|---|---|---|---|---|
| A | 52 / 22.25 → 2 | 52 / 8.65 → 2 | 39.0625 / 5.5625 → 2 | 32.89 / 2.47 → 2 |
| B | 37.25 / 13 → 2 | 37.25 / 3.4 → 2 | 26.5625 / 1.5625 → 2 | 21.47 / 0.22 → 2 |
| C | 13 / 1.25 → 2 | 13 / 0.45 → 2 | 7.0625 / 1.5625 → 2 | 4.56 / 4.14 → 2 |
| D | 0 / 6.25 → 1 | 0 / 18.25 → 1 | 1.0625 / 23.5625 → 1 | 2.22 / 31.81 → 1 |
| E | 6.25 / 0 → 2 | 6.25 / 3.2 → 2 | 2.5625 / 5.5625 → 1 | 1.14 / 9.89 → 1 |
| F | 4.25 / 1 → 2 | 4.25 / 5.8 → 1 | 1.0625 / 9.0625 → 1 | 0.47 / 14.22 → 1 |
| Step | Clusters | RSS |
|---|---|---|
| Assignment 1 | {D}, {A, B, C, E, F} | 37.5 |
| Update 1 | same | 21.5 |
| Assignment 2 | {D, F}, {A, B, C, E} | 19.95 |
| Update 2 | same | 16.375 |
| Assignment 3 | {D, E, F}, {A, B, C} | 13.375 |
| Update 3 | same | 10.67 |
| Assignment 4 | no change: stop | 10.67 |
Neither step can improve this clustering:
- the only point near the boundary is $C$, at squared distance $149/36 \approx 4.14$ from the centroid of its own cluster $\{A, B, C\}$ and $41/9 \approx 4.56$ from the other, so it stays;
- the centroids are already the means.
So the algorithm stops, at an RSS 35 percent above the optimum of 7.875.
Every pair of seeds ends at one of these two clusterings. The table lists all 15 pairs, with the first-named seed as cluster 1. The last column counts assignment steps, including the final one that changes nothing.
| Seeds | Result | RSS | Assignment steps |
|---|---|---|---|
| A, B | {A, B}, {C, D, E, F} | 7.875 | 3 |
| A, C | {A, B}, {C, D, E, F} | 7.875 | 2 |
| A, D | {A, B, C}, {D, E, F} | 10.67 | 2 |
| A, E | {A, B}, {C, D, E, F} | 7.875 | 2 |
| A, F | {A, B}, {C, D, E, F} | 7.875 | 2 |
| B, C | {A, B}, {C, D, E, F} | 7.875 | 2 |
| B, D | {A, B, C}, {D, E, F} | 10.67 | 2 |
| B, E | {A, B}, {C, D, E, F} | 7.875 | 2 |
| B, F | {A, B}, {C, D, E, F} | 7.875 | 2 |
| C, D | {A, B, C}, {D, E, F} | 10.67 | 4 |
| C, E | {A, B, C}, {D, E, F} | 10.67 | 2 |
| C, F | {A, B, C}, {D, E, F} | 10.67 | 2 |
| D, E | {A, B, C}, {D, E, F} | 10.67 | 4 |
| D, F | {A, B, C}, {D, E, F} | 10.67 | 4 |
| E, F | {A, B, C}, {D, E, F} | 10.67 | 3 |
Seven pairs lead to the optimum and eight to the local minimum. One row depends on the tie rule. With seeds $A$ and $D$, point $C$ is at squared distance 13 from both. The rule sends it to cluster 1, which is $A$'s, and the run stops at the local minimum. If the tie went to $D$ instead, the first assignment would already be $\{A, B\}$, $\{C, D, E, F\}$, the optimum, and the count would be eight pairs to seven. No other pair has a tie that changes its result: the script gets the same outcome for each with the seeds in either order.
Example (seeds far apart). Seeding with two points far apart, $B$ and $D$, does not find the optimum either. $D$ and $E$ were close together, which seems to explain the bad result of the second trace. But seeded with $B$ and $D$, near opposite ends of the spread, the first assignment already gives $\{A, B, C\}$ and $\{D, E, F\}$, because $C$ is at squared distance 6.25 from $B$ and 13 from $D$. K-means stops there with RSS 10.67. The farthest pair, $A$ and $D$, ends at the same clustering under the script's tie rule, as the table shows. Seeds far apart avoid one kind of bad start, but here both the good and the bad clustering split the points into a lower-left and an upper-right group. Spreading the seeds does not choose between them. K-means in practice returns to this when it works out k-means++.
How much worse can a local minimum be? Without limit. Take four points at the corners of a rectangle 6 wide and 2 high, $(0, 0)$, $(0, 2)$, $(6, 0)$ and $(6, 2)$, with $K = 2$. The natural clustering pairs the two left corners and the two right corners, with RSS $4 \times 1^2 = 4$.
Now let both seeds be left corners. The first assignment pairs each left corner with the right corner at the same height. That gives top and bottom clusters with centroids $(3, 0)$ and $(3, 2)$. Every point is 3 from its own centroid and $\sqrt{13} \approx 3.6$ from the other, so nothing moves. K-means stops with RSS $4 \times 3^2 = 36$, nine times the optimum. Stretching the rectangle makes the ratio as large as desired.
The result depends on the starting centroids. Starting from points that lie in the same natural group can split that group in two and merge two others. The standard remedies are:
- run k-means several times from different starting points and keep the clustering with the lowest RSS;
- choose starting points more carefully.
K-means in practice works out how much careful seeding (k-means++) helps on these two examples and measures both remedies on Reuters news stories.
Stepping through k-means
The demo runs the algorithm one half-iteration at a time on the six points above, on the rectangle, or on three blobs of points. The shaded regions show which centroid is nearest each part of the plane, so they are the regions the next assignment step will use. Each region is convex, which limits the shapes k-means can find. Here is why. A point $\vec{x}$ is at least as near to centroid $\vec{\mu}_k$ as to $\vec{\mu}_j$ when $\lvert \vec{x} - \vec{\mu}_k \rvert^2 \le \lvert \vec{x} - \vec{\mu}_j \rvert^2$. Expanding both squares and canceling $\lvert \vec{x} \rvert^2$ leaves
$$2\, \vec{x} \cdot (\vec{\mu}_j - \vec{\mu}_k) \le \lvert \vec{\mu}_j \rvert^2 - \lvert \vec{\mu}_k \rvert^2,$$
which is linear in $\vec{x}$. So the set of such points is a half-space, bounded by the plane that bisects the segment between the two centroids at a right angle. The region of centroid $k$ is the intersection of these half-spaces over all $j \ne k$. A half-space is convex, and an intersection of convex sets is convex. Every cluster k-means produces is therefore the part of the data inside a convex cell, called a Voronoi cell. So no point of another cluster can lie inside the convex hull of a cluster. A ring around another group, or two interlocking crescents, cannot be separated by k-means. The same cells partition the vectors of an inverted file index, which answers a query from the few cells nearest to it.
Dragging a point, or clicking an empty spot to add one, restarts the run from the same seeds. With seeds A and B, the readout repeats the RSS sequence of the worked example; with seeds D and E it ends at 10.67.
Cost
Each iteration computes the distance from each of $N$ documents to each of $K$ centroids, in a space of $M$ dimensions, so the assignment step costs $O(KNM)$. The update step adds each document to one centroid, $O(NM)$. With $I$ iterations the total is $O(IKNM)$. That is linear in the number of documents, which is what makes k-means practical for large collections (Manning, Raghavan, and Schütze, 2008, §16.4).
For scale, the Reuters experiment in K-means in practice has $N = 7{,}487$ stories, $M = 3{,}000$ terms and $K = 6$. One assignment step is about 135 million multiply-adds, a fraction of a second on a laptop.
Text adds a wrinkle. Document vectors are sparse, but centroids, averages of many documents, are dense, since they contain every term that appears in any member. Distance computations with dense centroids lose the advantage of sparsity. Implementations often do one of two things:
- keep only each centroid's highest-weighted terms, which the course text reports hardly lowers cluster quality (Manning, Raghavan, and Schütze, 2008, §16.4);
- use the dot product between a sparse document and a dense centroid, which costs time proportional to the number of terms in the document rather than the vocabulary.
The dot product is enough because, for a unit-length document $\vec{x}$, $\lvert \vec{x} - \vec{\mu} \rvert^2 = 1 - 2\, \vec{x} \cdot \vec{\mu} + \lvert \vec{\mu} \rvert^2$, and $\lvert \vec{\mu} \rvert^2$ is computed once per centroid per iteration.
For collections too large to pass over in full at every iteration, mini-batch k-means (Sculley, 2010) updates the centroids from a small random sample of documents at each step. Each centroid moves toward the sampled documents assigned to it, by a step that shrinks as the centroid accumulates documents. The convergence proof above does not apply to it, since a step computed on a sample can raise the RSS of the whole collection.
Related algorithms
K-medoids restricts each cluster's center to be one of its documents. The course text defines the medoid of a cluster as the document vector closest to its centroid, and notes that medoids, being documents, are sparse, so distances to them are cheap (Manning, Raghavan, and Schütze, 2008, §16.4). In the general form of Kaufman and Rousseeuw (1990, chapter 2), the medoid is the member with the smallest total dissimilarity to the other members. With an unsquared distance as the dissimilarity, a far-off document pulls less on the center than it does on a mean.
K-means is also the limiting case of a more general method. The expectation-maximization (EM) algorithm fits a mixture of probability distributions, one per cluster, and gives a soft clustering: each document has a degree of membership in every cluster (Manning, Raghavan, and Schütze, 2008, §16.5). The 2-Poisson model of term frequency was fitted this way in that article. Take a mixture of spherical Gaussian clusters that share one variance, held fixed. As that variance goes to zero, each soft assignment tends to the hard assignment to the nearest centroid, provided the document has a unique nearest centroid. The update of the means then tends to the centroid update, and the scaled log-likelihood tends to RSS. Model-based clustering and the EM algorithm derives EM, proves that limit, and shows what the limit does not cover: at any positive variance the assignments stay soft, and a document tied between two centroids stays shared. The EM Algorithm gives the general theory, for models that are not mixtures as well.
The worked example, both local-minimum examples and the worked problems are recomputed by tools/experiments/clustering/lloyd_worked.py in the site repository.
Worked problems
Problems 1 to 3 are Exercises 16.5, 16.11 and 16.20 of the course text (Manning, Raghavan, and Schütze, 2008, §16.4.1 and §16.7), restated in our own words. Problem 4 is posed here on the six points.
Problem 1 (two stopping conditions). Two of the stopping conditions are (i) the assignment does not change between iterations and (ii) the centroids do not change between iterations. Does each imply the other?
Yes, provided ties are broken by a rule that depends only on the centroids and the current assignment. Number the steps: assignment $\gamma_t$ is computed from the centroids $\vec{\mu}_{t-1}$, and the centroids $\vec{\mu}_t$ are the means under $\gamma_t$.
(i) implies (ii). The centroids are a function of the assignment. If $\gamma_{t+1} = \gamma_t$, then $\vec{\mu}_{t+1} = \vec{\mu}_t$.
(ii) implies (i). Suppose $\vec{\mu}_t = \vec{\mu}_{t-1}$. The assignment $\gamma_t$ sent every document to a nearest centroid among $\vec{\mu}_{t-1}$. Step $t + 1$ uses the same centroids, so every document's current cluster is still a nearest one. Under the rule "a tied document stays where it is", no document moves, and $\gamma_{t+1} = \gamma_t$. Under the rule "a tie goes to the lowest index", $\gamma_{t+1}$ is computed from the same centroids by the same rule as $\gamma_t$, so it is the same.
The proviso matters in one direction only. Condition (ii) does not say that the assignment at step $t$ equals the one at step $t - 1$: two different assignments can have the same centroids. On the corners of a square, $(0, 0)$, $(2, 0)$, $(0, 2)$, $(2, 2)$, the two diagonals are different clusters with the same mean, $(1, 1)$. What (ii) guarantees is that the next assignment repeats the current one. The script runs all 30 ordered seed pairs on the six points for one iteration beyond the stop. In every run the centroids repeat for the first time at the same iteration at which the assignment first repeats.
Problem 2 (an empty cluster). (a) Give a set of points and three starting centroids for which k-means with $K = 3$ converges to a clustering with an empty cluster. (b) Can a clustering with an empty cluster be the global optimum of RSS?
(a) Take seven points on a line, 0, 4, 9, 24, 25, 26, 40, with starting centroids 0, 9 and 40. The first assignment gives $\{0, 4\}$, $\{9, 24\}$ and $\{25, 26, 40\}$: the point 4 is nearer 0 than 9, and 24 is at distance 15 from 9 and 16 from 40. The centroids move to 2, 16.5 and $91/3 \approx 30.33$. Now the middle cluster loses both members. The point 9 is at distance 7 from the first centroid and 7.5 from its own. The point 24 is at distance 7.5 from its own centroid and $19/3 \approx 6.33$ from the third. The clusters are $\{0, 4, 9\}$, an empty one, and $\{24, 25, 26, 40\}$, with centroids $13/3$ and $115/4$. The empty cluster keeps its centroid at 16.5, no point is nearer to it than to its own centroid, and the third assignment changes nothing. K-means has converged with RSS $122/3 + 683/4 = 211.42$.
(b) Only if the data have fewer than $K$ distinct points. Suppose a clustering has an empty cluster and RSS above zero. Then some cluster with $n \ge 2$ members and mean $\vec{m}$ contains a member $\vec{x} \ne \vec{m}$. Move $\vec{x}$ into the empty cluster, where it costs nothing. The rest of its old cluster has mean $\vec{m}' = (n\vec{m} - \vec{x})/(n - 1)$, so $\vec{m}' - \vec{m} = (\vec{m} - \vec{x})/(n - 1)$. By the decomposition proved above, applied to the remaining $n - 1$ members with $\vec{v} = \vec{m}$,
$$\sum_{\vec{y} \ne \vec{x}} \lvert \vec{y} - \vec{m} \rvert^2 = \sum_{\vec{y} \ne \vec{x}} \lvert \vec{y} - \vec{m}' \rvert^2 + (n - 1) \lvert \vec{m}' - \vec{m} \rvert^2 = \sum_{\vec{y} \ne \vec{x}} \lvert \vec{y} - \vec{m}' \rvert^2 + \frac{\lvert \vec{x} - \vec{m} \rvert^2}{n - 1}.$$
The left side is the old cluster's RSS minus $\lvert \vec{x} - \vec{m} \rvert^2$. So the move lowers RSS by $\frac{n}{n-1} \lvert \vec{x} - \vec{m} \rvert^2 > 0$, and the clustering was not optimal. In part (a), splitting 40 off the last cluster lowers its RSS by $\frac{4}{3} (40 - 28.75)^2 = 168.75$, from 211.42 to 42.67. If RSS is zero, every point coincides with its centroid, so there are at most $K - 1$ distinct points. Only then is a clustering with an empty cluster optimal.
Problem 3 (within-point scatter). The within-point scatter of a clustering is $\sum_k \frac{1}{2} \sum_{\vec{x}_i \in \omega_k} \sum_{\vec{x}_j \in \omega_k} \lvert \vec{x}_i - \vec{x}_j \rvert^2$. Show that minimizing RSS and minimizing within-point scatter are equivalent.
As stated, the claim is false in general. It is true when every cluster is required to have the same size, and its correct general form divides each cluster's scatter by the cluster's size. The scatter equals $\sum_k n_k\, \mathrm{RSS}_k$, and the version divided by the cluster size equals RSS exactly. For one cluster with $n$ members and mean $\vec{m}$, write $\vec{x}_i - \vec{x}_j = (\vec{x}_i - \vec{m}) - (\vec{x}_j - \vec{m})$ and expand:
$$\sum_i \sum_j \lvert \vec{x}_i - \vec{x}_j \rvert^2 = \sum_i \sum_j \Big( \lvert \vec{x}_i - \vec{m} \rvert^2 + \lvert \vec{x}_j - \vec{m} \rvert^2 - 2 (\vec{x}_i - \vec{m}) \cdot (\vec{x}_j - \vec{m}) \Big) = 2n\, \mathrm{RSS}_k - 2 \Big\lvert \sum_i (\vec{x}_i - \vec{m}) \Big\rvert^2 = 2n\, \mathrm{RSS}_k,$$
since the deviations from the mean sum to zero. Hence
$$\frac{1}{2} \sum_i \sum_j \lvert \vec{x}_i - \vec{x}_j \rvert^2 = n_k\, \mathrm{RSS}_k \qquad \text{and} \qquad \frac{1}{2 n_k} \sum_i \sum_j \lvert \vec{x}_i - \vec{x}_j \rvert^2 = \mathrm{RSS}_k.$$
Summed over clusters, the size-normalized scatter is RSS, so the two have the same minimizer. That is the correct form of the statement: k-means minimizes the squared distances between members of the same cluster, each cluster's total divided by its size, without ever computing a pairwise distance. The unnormalized scatter weights each cluster's RSS by its size and can prefer a different clustering. Take eight points on a line, 0, 1, 2, 3, 4, 5, 6 and 12, with $K = 2$. RSS is lowest for $\{0, \dots, 6\}$ and $\{12\}$: RSS 28, scatter $7 \times 28 = 196$. The scatter is lowest for $\{0, \dots, 4\}$ and $\{5, 6, 12\}$: scatter $5 \times 10 + 3 \times 86/3 = 136$, RSS $10 + 86/3 = 38.67$. On the six points of this article the two criteria agree: $\{A, B\}$, $\{C, D, E, F\}$ has the lowest RSS, 7.875, and the lowest scatter, 30.25.
Problem 4 (the best clustering for every K). For the six points, find the lowest RSS for each $K$ from 1 to 6.
There are 203 ways to divide six points into nonempty clusters, and the script tries them all.
| $K$ | Best clustering | RSS |
|---|---|---|
| 1 | {A, B, C, D, E, F} | 36.71 |
| 2 | {A, B}, {C, D, E, F} | 7.875 |
| 3 | {A, B}, {C, E, F}, {D} | 2.458 |
| 4 | {A, B}, {C}, {D}, {E, F} | 1.125 |
| 5 | {A}, {B}, {C}, {D}, {E, F} | 0.5 |
| 6 | six singletons | 0 |
Each step from $K = 2$ on can be checked with the formula of Problem 2, since each splits one point off a cluster. Going from two clusters to three splits $D$ off $\{C, D, E, F\}$, whose mean is $(4, 5.25)$. $D$ is at squared distance $1^2 + 1.75^2 = 4.0625$ from it, so RSS falls by $\frac{4}{3} \times 4.0625 = 5.417$, from 7.875 to 2.458. The lowest RSS falls at every step. K-means in practice proves that it must, which is why RSS alone cannot choose $K$.
What we have learned
K-means minimizes the residual sum of squares by alternating two steps, each solving half the problem exactly. The update step moves each centroid to the mean and lowers RSS by $n_k$ times the squared distance moved. Since RSS never rises and there are finitely many clusterings, the algorithm stops. On the six points it reached the optimum, 7.875, from seeds $A$ and $B$, and a local minimum, 10.67, from 8 of the 15 seed pairs under the script's tie rule. On the rectangle a local minimum costs nine times the optimum.
The algorithm settles nothing about where to start, how many clusters to ask for, or which vectors to cluster. K-means in practice works out careful seeding exactly on the six points and the rectangle, then measures how much each choice matters on Reuters news stories. Model-based clustering and the EM algorithm then replaces the centroids with probability distributions and recovers k-means as a limit.
References
- Aloise, D., Deshpande, A., Hansen, P., and Popat, P. (2009). NP-hardness of Euclidean sum-of-squares clustering. Machine Learning, 75(2), 245–248. record
- Arthur, D., and Vassilvitskii, S. (2006). How slow is the k-means method? In Proceedings of the Twenty-Second Annual Symposium on Computational Geometry (SCG), 144–153. record
- Kaufman, L., and Rousseeuw, P. J. (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley. record
- Lloyd, S. P. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2), 129–137. record
- MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. In Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, 281–297. record
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 16.4–16.7. Cambridge University Press. record · 102 pages
- Sculley, D. (2010). Web-scale k-means clustering. In Proceedings of the 19th International Conference on World Wide Web (WWW), 1177–1178. record
Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 13 revisions