On 7,487 Reuters stories in six categories, clustered with $K = 6$, the choices k-means leaves to its user change the result more than the algorithm does. Ten random starts gave RSS within about one percent of each other but purity from 0.703 to 0.803. Over 30 seeds, k-means++ did not lower RSS (median 6,571 against 6,559 for random seeds) but raised median NMI from 0.459 to 0.486. Keeping the best of five runs lowered RSS and also lowered NMI, and across 300 runs RSS and NMI were positively correlated (Spearman's $\rho = 0.30$). Neither the RSS curve nor AIC with variance 1 points to six clusters. Spherical k-means had the higher NMI in 27 of 30 paired starts. Features in different units need standardizing.
Run k-means ten times on the same 7,487 Reuters news stories, asking each time for six clusters. The ten results have nearly the same residual sum of squares, within about one percent of each other. Yet in one run 80 percent of the stories share their cluster's majority category, and in another only 70 percent do. The algorithm and the data were the same every time, so where does that difference come from, and which choices control it? It comes from the starting centroids, the one thing that changed between runs. Many different clusterings of this collection have nearly the same residual sum of squares, and the start decides which of them is found.
The k-means algorithm is fully specified only once three things are fixed:
- the starting centroids;
- the number of clusters $K$;
- the vectors being clustered.
The algorithm makes none of these choices itself, and each one changes the result.
Here is the route. First we set up the Reuters experiment. Then we compare random starting points with careful seeding (k-means++), worked out exactly on the small examples of the k-means algorithm and measured on Reuters over 30 seeds. Next we look inside the clustering k-means found, name its clusters, and take up the choice of $K$. Finally we turn to the vectors themselves: feature scaling and spherical k-means. The article assumes the algorithm, its objective RSS, and its local minima from that article.
The experiment
The test collection is the Reuters-21578 newswire collection (Lewis, 1997) used in text classification, in the ApteMod version of 10,788 stories distributed with NLTK. Here it is restricted to stories with exactly one category from six:
earn(earnings reports);acq(acquisitions);crude(oil);trade;money-fx(currency markets);interest(interest rates).
That leaves 7,496 stories, from the training and test portions together. The 9 of them that contain none of the feature terms below are set aside, which leaves 7,487. The categories are very unequal in size: 3,918 earn stories and 2,292 acq, against 271 to 373 for each of the other four.
Each story was lowercased, split into alphabetic tokens, filtered against a short stop list, and stemmed with the Porter stemmer. Tokens of one letter were dropped. The 3,000 most widespread terms appearing in at least three stories became the features. They were weighted by TF-IDF with logarithmic term frequency, and each vector was normalized to unit length. On unit vectors, squared Euclidean distance is $2 - 2\cos\theta$, so k-means distances follow cosine similarity.
The categories play no part in the clustering. They are used afterward to judge it, with purity, normalized mutual information (NMI), and the Rand index (RI), which evaluating clusterings defines. All three range from 0 to 1, higher meaning closer agreement with the categories. Purity is the easiest to read: the share of stories that belong to their cluster's majority category.
Starting centroids and restarts
K-means converges to a local minimum of the residual sum of squares (RSS), and which minimum it reaches depends on where it starts. The simplest initialization picks $K$ documents at random as the starting centroids. Running it ten times with $K = 6$, each from a different random start:
| Measure | Lowest of 10 runs | Highest of 10 runs |
|---|---|---|
| RSS | 6,532.6 | 6,594.7 |
| Purity | 0.703 | 0.803 |
| NMI | 0.372 | 0.496 |
| Rand index | 0.659 | 0.721 |
| Iterations to converge | 16 | 69 |
RSS varies by only about one percent, but the clusterings differ a great deal. Purity ranges over ten points and NMI over twelve. Many quite different partitions of the collection have nearly the same RSS, and the starting point decides which one is found.
The standard remedy is restarts: run k-means several times and keep the result with the lowest RSS. This is sound, since RSS is the quantity k-means is trying to minimize and the only one available when there are no labels. It does not guarantee the clustering a person would prefer. Of the ten random runs, the one with the lowest RSS had purity 0.788, good but not the best of the ten.
k-means++
The other remedy is to choose better starting points. Random starting points can fall close together, in one dense region, leaving other regions without a centroid. k-means++ (Arthur and Vassilvitskii, 2007) spreads them out. It picks the first centroid uniformly at random. Each later centroid is chosen at random with probability proportional to $D(x)^2$, the squared distance from a document $x$ to the nearest centroid already chosen:
$$P(x \text{ is chosen next}) = \frac{D(x)^2}{\sum_{x'} D(x')^2}.$$
Points far from all existing centroids are therefore likely to be picked. A point that is already a centroid has $D(x) = 0$ and cannot be picked again. Arthur and Vassilvitskii (2007, Theorem 3.1) proved that the expected RSS of this seeding alone, before any k-means iterations, is at most $8(\ln K + 2)$ times the optimum. Random initialization has no such guarantee, and the iterations that follow the seeding can only lower RSS.
The bound is on an expectation, taken over the random choices of the seeding, and it holds for every dataset. It says nothing about a single run, and it is loose. For $K = 2$ it is $8(\ln 2 + 2) \approx 21.5$ times the optimum. The rectangle below shows how far the actual expectation can sit under it.
k-means++ on the small examples
The k-means algorithm gives two small cases where the starting points decide the outcome, and k-means++ can be worked out exactly on both.
The rectangle. Four points at $(0, 0)$, $(0, 2)$, $(6, 0)$ and $(6, 2)$, with $K = 2$. K-means ends in the bad top-and-bottom clustering (RSS 36, against 4 for the left-and-right one) exactly when both seeds are on the same side. Random seeding picks two of the four points, and 2 of the 6 possible pairs are on the same side, so it fails with probability $1/3$.
Example (ten restarts on the rectangle). Ten runs from random seeds all fail with probability $(1/3)^{10} \approx 1.7 \times 10^{-5}$. Restarts are the first remedy: run k-means ten times and keep the lowest RSS. One good run is enough, and the lowest RSS picks it out. On the rectangle, restarts work because the two outcomes differ so much in RSS.
Careful seeding fixes the rectangle in a single run. With k-means++, suppose the first seed is $(0, 0)$. The squared distances to the other points are
| Candidate | $(0, 2)$ | $(6, 0)$ | $(6, 2)$ | Total |
|---|---|---|---|---|
| $D(x)^2$ | 4 | 36 | 40 | 80 |
| Probability | 0.05 | 0.45 | 0.50 | 1 |
so the second seed lands on the same side with probability $4/80 = 0.05$. By symmetry the same holds whichever corner comes first, and k-means++ fails with probability 0.05 instead of 0.33.
The same table gives the expected RSS of the seeds themselves, before any iteration. If the second seed is on the same side, the two far corners are each at squared distance 36 from their nearest seed, a cost of 72. Otherwise the two corners that are not seeds are each at squared distance 4 from one, a cost of 8. The expectation is $0.05 \times 72 + 0.95 \times 8 = 11.2$, which is 2.8 times the optimum of 4. The guarantee allows 21.5 times.
Example (a wider rectangle). Widening the rectangle makes k-means++ fall into the bad clustering less often, although the bad clustering then costs far more. With width $w$ and height 2, the three candidates for the second seed are at squared distances 4, $w^2$ and $w^2 + 4$ from the first, a total of $2w^2 + 8$. Only the first is on the same side, so the failure probability is $4/(8 + 2w^2)$. At $w = 20$ that is $4/808 \approx 0.005$, against 0.05 at width 6, while the bad clustering's RSS, $w^2$, grows from 36 to 400. That is the idea behind the guarantee: the seeding is most careful exactly where a mistake would cost most.
The six points. On the six points $A$ to $F$ of that article, 7 of the 15 seed pairs lead to the optimum (RSS 7.875) and 8 to the local minimum $\{A, B, C\}$, $\{D, E, F\}$ (RSS 10.67). So random seeding succeeds with probability $7/15 = 0.47$. For k-means++, each row of the next table takes one first seed. It lists the squared distance from that seed to each other point, which is the weight with which the point is drawn as the second seed, and marks in bold the second seeds that lead to the optimum.
| First seed | A | B | C | D | E | F | Total | P(optimum) |
|---|---|---|---|---|---|---|---|---|
| A | 1.25 | 13 | 52 | 22.25 | 28.25 | 116.75 | 0.555 | |
| B | 1.25 | 6.25 | 37.25 | 13 | 18 | 75.75 | 0.508 | |
| C | 13 | 6.25 | 13 | 1.25 | 3.25 | 36.75 | 0.524 | |
| D | 52 | 37.25 | 13 | 6.25 | 4.25 | 112.75 | 0 | |
| E | 22.25 | 13 | 1.25 | 6.25 | 1 | 43.75 | 0.806 | |
| F | 28.25 | 18 | 3.25 | 4.25 | 1 | 54.75 | 0.845 |
For the first row, $(1.25 + 13 + 22.25 + 28.25)/116.75 = 64.75/116.75 = 0.555$. Each first seed has probability $1/6$, so the success probability is the mean of the last column, 0.54. That is only a little better than random seeding.
Both figures depend on one tie. Seeded with $A$ and $D$, point $C$ is at squared distance 13 from each, and the k-means algorithm shows that the tie decides the outcome: with $C$ in $A$'s cluster the run ends at the local minimum, with $C$ in $D$'s at the optimum. The script behind both articles breaks a first-step tie in favor of the lower-numbered cluster and numbers the clusters alphabetically by seed, so $C$ goes with $A$. That is the rule behind 7 of 15 and 0.54. If the tie went to the seed drawn first, the pair would succeed when $D$ is drawn first. The $D$ row would then read $52/112.75 = 0.461$ and the k-means++ probability would be 0.62. If the tie always went to $D$, random seeding would succeed for 8 of the 15 pairs, 0.53, and k-means++ with probability 0.69. Under every rule k-means++ does somewhat better than random seeding and far from perfectly.
The gain is small because the two outcomes have similar RSS and both kinds of seed pair are spread out. The two farthest points, $A$ and $D$, are themselves a pair whose result hangs on a tie. So spreading the seeds does not separate good starts from bad ones. k-means++ protects against seeds bunched in one group, not against every poor start.
Ten runs on Reuters
Reuters could be a case like the rectangle, where careful seeding helps greatly, or like the six points, where it barely helps. It turns out closer to the six points, as the next section establishes with 30 seeds. First, the same ten runs with k-means++ seeding:
| Measure | Lowest of 10 runs | Highest of 10 runs |
|---|---|---|
| RSS | 6,528.7 | 6,582.7 |
| Purity | 0.713 | 0.839 |
| NMI | 0.352 | 0.586 |
| Rand index | 0.652 | 0.778 |
| Iterations to converge | 15 | 54 |
In these ten runs k-means++ found a slightly lower RSS, both at best and at worst, and needed at most 54 iterations against 69. Its range of purity and NMI was, if anything, wider. Its lowest-RSS run had purity 0.744, NMI 0.382, and RI 0.652, lower on all three than the lowest-RSS random run. Ten runs are too few to say whether those differences are real, which the next section tests with more.
Thirty seeds: seeding and restarts measured
The comparison above rests on ten runs of each kind, and the extremes of ten runs are noisy. So the comparison was repeated with 30 seeds for each seeding method. The table reports the median and interquartile range (the middle half of the 30 values), rounded as shown:
| Measure | Random seeds | k-means++ |
|---|---|---|
| RSS | 6,559 (6,549 to 6,575) | 6,571 (6,563 to 6,583) |
| Purity | 0.784 (0.740 to 0.803) | 0.782 (0.742 to 0.828) |
| NMI | 0.459 (0.401 to 0.509) | 0.486 (0.433 to 0.553) |
| Rand index | 0.703 (0.662 to 0.737) | 0.730 (0.700 to 0.763) |
| Adjusted Rand index | 0.305 (0.215 to 0.395) | 0.374 (0.301 to 0.455) |
| Iterations | 28.5 (21 to 39) | 26.5 (21 to 47) |
On this collection, k-means++ does not find tighter clusterings than random seeding. Its median RSS over these 30 runs is slightly higher. Over a larger set of 150 runs of each kind, the two RSS distributions are practically identical: medians 6,567 and 6,568, and a Mann-Whitney test finds no difference ($p = 0.72$). Both methods reached the same lowest RSS, 6,526.9, in some run.
So Reuters behaves more like the six points than like the rectangle. The guarantee of Arthur and Vassilvitskii bounds how bad the seeding can be in expectation. It does not promise an improvement on a collection where random seeds already do well, as they evidently do here, with six clusters and categories of very unequal size. What k-means++ did change here is the kind of local minimum found. Its median NMI and adjusted Rand index are higher, so its clusterings agree somewhat better with the categories at the same RSS.
Restarts were measured the same way. For each of 30 replicates, k-means was run $r$ times from different seeds and the lowest-RSS result kept:
| Seeding | Restarts $r$ | RSS | NMI | Adjusted Rand |
|---|---|---|---|---|
| Random | 1 | 6,559 (6,549 to 6,575) | 0.459 (0.401 to 0.509) | 0.305 (0.215 to 0.395) |
| Random | 3 | 6,548 (6,533 to 6,554) | 0.425 (0.397 to 0.490) | 0.276 (0.205 to 0.337) |
| Random | 5 | 6,544 (6,533 to 6,550) | 0.425 (0.397 to 0.479) | 0.273 (0.205 to 0.328) |
| k-means++ | 1 | 6,571 (6,563 to 6,583) | 0.486 (0.433 to 0.553) | 0.374 (0.301 to 0.455) |
| k-means++ | 3 | 6,549 (6,541 to 6,556) | 0.457 (0.404 to 0.503) | 0.293 (0.243 to 0.365) |
| k-means++ | 5 | 6,542 (6,533 to 6,547) | 0.435 (0.397 to 0.474) | 0.286 (0.207 to 0.341) |
Example (what the best of five buys). Keeping the best of five runs lowers RSS and lowers agreement with the six categories. Restarts do their job on RSS: the median RSS falls by about 15 to 30 and its spread narrows. But with either seeding, the best of five has lower NMI and adjusted Rand index than a single run.
A common assumption is "lower RSS means a better clustering." On Reuters it fails for a specific reason. The lowest-RSS clusterings are the ones that split the large earn category into several tight groups and merge the small categories. So minimizing RSS harder moves the result away from the editors' categories. Across all 300 runs, RSS and NMI are positively correlated: Spearman's $\rho = 0.30$, with a 95 percent interval of 0.20 to 0.40 by Fisher's transformation and a two-sided p-value of $9 \times 10^{-8}$. A worse RSS goes with a better match to the labels.
None of this makes restarts or k-means++ a mistake. Without labels, RSS is the only guide, and both reliably find low-RSS clusterings. The experiment shows what that objective means on a particular collection: tight clusters, not necessarily the categories a person had in mind.
What k-means found
The lowest-RSS k-means++ clustering shows what a low-RSS clustering of Reuters looks like. As a contingency table of clusters against categories:
| Cluster | earn | acq | crude | trade | money-fx | interest |
|---|---|---|---|---|---|---|
| 1 | 413 | 2,069 | 94 | 0 | 2 | 3 |
| 2 | 515 | 0 | 0 | 0 | 0 | 0 |
| 3 | 835 | 0 | 0 | 0 | 0 | 0 |
| 4 | 866 | 1 | 0 | 0 | 0 | 0 |
| 5 | 512 | 0 | 0 | 0 | 0 | 0 |
| 6 | 777 | 222 | 279 | 326 | 305 | 268 |
K-means divided earn into four nearly pure clusters. It put all of trade, nearly all of money-fx and interest, and three quarters of crude together in one. The highest-weighted terms of each centroid show why. The four earn clusters are:
- dividend announcements (
qtly,div,payout); - results reporting a loss;
- results tables marked by
standqtr(from "1st qtr", once the digits are stripped); - results tables marked by
nineandmth(nine-month figures).
These are formulaic notices with distinctive vocabularies, which k-means separates easily. The mixed cluster's top terms are rate, billion, bank, trade, and market, the shared language of economic news.
From k-means's point of view, this is a good clustering. Here, splitting a large, internally varied category lowered RSS more than separating four small categories with overlapping vocabulary. The clusters are coherent. They are just not the categories the Reuters editors chose. This is the general difficulty of judging a clustering against labels, taken up in evaluating clusterings.
The objective also carries an assumption about shape. Each k-means cluster is the part of the collection inside a convex cell around its centroid, as the k-means algorithm proves, and RSS charges every document by its squared distance from one center. So the method favors compact, roughly ball-shaped groups, and a broad category is cheaper to describe as several balls than as one. Density-based methods drop the convexity; the library page on DBSCAN works one by hand.
Naming the clusters
A clustering is useful to a person only once its clusters have names. The list of top centroid terms above was one way to name them. Manning, Raghavan, and Schütze (2008, §17.7) distinguish two families of methods.
- Cluster-internal labeling uses only the cluster itself. Two standard labels are the terms with the highest weights in the centroid, and the title of the document nearest the centroid.
- Differential labeling compares the cluster with the others. It scores each term by how strongly its presence is associated with membership in the cluster, using the mutual information or the $\chi^2$ statistic of feature selection, with the cluster in the place of the class.
For differential labeling, each term and cluster give a two-by-two table of document counts. Take the stem qtly and cluster 2, the 515 dividend announcements. Of the 7,487 stories, 426 contain qtly and are in the cluster ($N_{11}$), 28 contain it and are not ($N_{10}$), 89 are in the cluster without it ($N_{01}$), and 6,944 are neither ($N_{00}$). The formula of feature selection gives the mutual information as a sum of one term per cell:
$$I = \tfrac{426}{7487} \log_2 \tfrac{7487 \times 426}{454 \times 515} + \tfrac{89}{7487} \log_2 \tfrac{7487 \times 89}{7033 \times 515} + \tfrac{28}{7487} \log_2 \tfrac{7487 \times 28}{454 \times 6972} + \tfrac{6944}{7487} \log_2 \tfrac{7487 \times 6944}{7033 \times 6972},$$
which is $0.2145 - 0.0290 - 0.0146 + 0.0783 = 0.2491$ bits. Its $\chi^2$ statistic is 5,705. Compare the stem ct (cents). It occurs in 509 of the cluster's 515 stories, more than qtly does, but also in 2,519 of the 6,972 stories outside. Its mutual information is 0.0883 bits. The centroid lists ct because it is frequent in the cluster. The differential score ranks it far below qtly because it is frequent elsewhere too.
The table gives the eight highest-scoring terms under each method for the six clusters of the contingency table. Terms are Porter stems. A minus sign marks a term that is less frequent inside the cluster than outside.
| Cluster | Centroid weight | Mutual information |
|---|---|---|
1 (2,581 stories, mostly acq) |
share, stock, acquir, it, compani, ha, common, inc | v (−), net (−), shr (−), qtr (−), ct (−), rev (−), acquir, note (−) |
2 (515, earn) |
qtly, div, pai, record, prior, april, ct, set | div, qtly, record, pai, prior, april, v, ct |
3 (835, earn) |
loss, v, profit, shr, rev, net, th, ct | loss, shr, v, net, th, rev, ct, qtr |
4 (867, earn) |
v, shr, net, st, ct, qtr, rev, avg | shr, v, net, qtr, st, ct, rev, it (−) |
5 (512, earn) |
rd, nine, mth, v, shr, net, qtr, ct | rd, nine, mth, qtr, shr, v, net, ct |
| 6 (2,177, mixed) | rate, billion, bank, pct, he, trade, from, market | lt (−), he, ct (−), v (−), shr (−), rate, last, rev (−) |
Three things can be read from it, all observations on this clustering.
- For the small, formulaic clusters the two methods nearly agree. Clusters 2 to 5 share seven or eight of their eight terms. The $\chi^2$ lists are close to the mutual information lists everywhere: they share six to eight terms in every cluster. The course text reports the same of its example and omits $\chi^2$ for that reason.
- Differential labels can name a cluster by what it lacks. Both scores count negative association as well as positive, as feature selection shows. For cluster 1, seven of the top eight mutual information terms are earnings-table vocabulary that is absent from acquisition stories. For cluster 6, five of eight are absences, among them
lt, the remnant of an HTML entity that precedes company ticker symbols in the corpus files. Such terms separate the cluster from the rest very well and tell a reader nothing about its content. Keeping only terms more frequent inside the cluster givesacquir, it, common, compani, stock, sharehold, acquisit, sharefor cluster 1 andhe, rate, last, market, trade, report, see, wouldfor cluster 6. - Centroid labels pick up frequent, uninformative terms. The centroid lists include
it,ha(from has),inc,heandfrom. That is the weakness of cluster-internal labeling that the course text points out: it cannot tell a term frequent in the cluster from one frequent everywhere.
The story nearest each centroid gives the third kind of label, its headline. For clusters 1 to 6 these are, with ticker symbols removed: "First Financial bids for Comdata"; "Shawmut Corp sets regulary dividend" (as spelled in the corpus); "Mischer Corp 4th qtr loss"; "Roto-Rooter Inc 1st qtr net"; "Stanadyne Inc 3rd qtr net"; and "IMF, World Bank to meet amid new inflation fears". A headline is easier to read than a term list. It can also mislead, since one story stands for thousands: the headline of cluster 6 is a trade story, and the cluster holds five other categories. In current systems the label is often written by a language model that reads a sample of the cluster and of its neighbors. The library page on Clio describes one such system.
Choosing K
Six clusters were asked for because Reuters has six categories. Without labels, $K$ has to come from somewhere else, and this section shows that neither RSS nor a standard criterion supplies it here. K-means needs $K$ in advance, and RSS cannot choose it directly, because the lowest attainable RSS always falls as $K$ grows (Problem 1 below proves it). With $K = N$, every document is its own cluster and RSS is zero. The lowest RSS found in five k-means++ runs for each $K$:
| K | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 12 | 15 | 20 |
|---|---|---|---|---|---|---|---|---|---|---|
| RSS | 6,848 | 6,684 | 6,639 | 6,591 | 6,529 | 6,474 | 6,399 | 6,354 | 6,284 | 6,199 |
Repeating this with 30 k-means++ runs for each of nine values of $K$ from 2 to 50 (2, 3, 4, 6, 8, 12, 20, 30 and 50) shows the shape of the curve and how much it varies from run to run. With two clusters all 30 runs reached the same RSS, 6,848.3. With three, 29 runs reached 6,683.6 and one stopped at 6,825.1. From four clusters on, the runs spread out, and the lowest of 30 runs is 20 to 40 below the median.
Two approaches are common (Manning, Raghavan, and Schütze, 2008, §16.4.1):
- Look for a knee. Plot RSS against $K$ and choose the point after which adding clusters helps much less. Here the largest drop is from two clusters to three. After that, RSS falls by roughly 15 to 60 per added cluster with no clear knee, and nothing in the curve points to six, the number of categories.
- Penalize complexity. Choose the $K$ that minimizes $\mathrm{RSS}(K) + \lambda K$, where the penalty $\lambda$ charges for each additional cluster (the text's equation 16.11). The Akaike information criterion gives one principled choice, $\lambda = 2M$ for $M$ dimensions.
Where $2M$ comes from. The Akaike information criterion (AIC) chooses the model that minimizes $-2L + 2q$, where $L$ is the model's largest log-likelihood and $q$ its number of free parameters. The course text states the criterion, as its equation 16.12, without deriving it, and so do we; the derivation is in Akaike's Information Criterion, Derived. To apply it, read a k-means clustering as a probability model: each document is drawn from a Gaussian centered on its cluster's centroid, with variance 1 in every coordinate. The log-density of a document $\vec{x}$ in cluster $k$ is then $-\frac{M}{2} \log 2\pi - \frac{1}{2} \lvert \vec{x} - \vec{\mu}_k \rvert^2$. Summing over the documents,
$$L = -\frac{NM}{2} \log 2\pi - \frac{1}{2}\, \mathrm{RSS}, \qquad \text{so} \qquad -2L = \mathrm{RSS} + NM \log 2\pi.$$
The last term is the same for every $K$ and drops out of the comparison. The free parameters are the coordinates of the $K$ centroids, $q = KM$. So AIC minimizes $\mathrm{RSS}(K) + 2MK$ (Manning, Raghavan, and Schütze, 2008, §16.4.1, equation 16.13). Model-based clustering and the EM algorithm makes the probability model precise.
The penalty $2M$ rests on the variance being fixed at 1. With variance $\sigma^2$ in every coordinate, $-2L = \mathrm{RSS}/\sigma^2 + NM \log(2\pi\sigma^2)$, and AIC minimizes $\mathrm{RSS}(K) + 2M\sigma^2 K$. Unit-length TF-IDF vectors in 3,000 dimensions vary far less than 1 per coordinate. Around the single mean of the collection the variance per coordinate is $7{,}135.7/(7{,}487 \times 3{,}000) \approx 3.2 \times 10^{-4}$. So a variance of 1 overstates the penalty about three thousandfold. The count $q = KM$ also leaves out the cluster assignments, which the model fits as well. The course text makes the same two simplifications.
Example (AIC on Reuters). With $M = 3{,}000$ features and the variance fixed at 1, AIC chooses a single cluster. That outcome is a consequence of the variance assumption, not a finding about the collection. The penalty is $\lambda = 6{,}000$ per cluster, and no step in the table of RSS by $K$ lowers RSS by anything close to that, so within the table the choice is $K = 2$. Below the table it is $K = 1$. One cluster has RSS 7,135.7, so going to two clusters, at the lowest RSS found for $K = 2$, lowers RSS by 287 and costs 6,000. Three or more clusters could never win: with unit vectors the RSS of one cluster is at most $N = 7{,}487$, less than the 12,000 that two extra clusters cost. The course text reports the same outcome on its own example. The general difficulty with a penalty is that the answer depends on $\lambda$, which moves the choice of $K$ to a choice of $\lambda$. Problem 2 below finds the values of $\lambda$ that would select each $K$.
With labels available, the external measures can be plotted against $K$ as well. On Reuters the adjusted Rand index peaks at $K = 6$, the number of categories (Clustering measures corrected for chance shows the curves). But labels are exactly what clustering usually lacks, and a measure that needs them cannot choose $K$ for an unlabeled collection. The silhouette, a label-free measure that can compare clusterings with different $K$, is defined and worked in evaluating clusterings; the Reuters runs here were not scored with it.
In practice $K$ is often set by the application. A search result clustering interface has room for perhaps five to ten clusters, and a browsing hierarchy for a manageable number of branches at each level.
Feature scaling
The last choice is the vectors themselves. K-means uses Euclidean distance, which adds up squared differences in each feature. A feature measured in large units therefore outweighs one measured in small units, regardless of which matters more. TF-IDF vectors mostly avoid the problem:
- every coordinate is a term weight in the same units;
- the differences in scale that IDF introduces are intended;
- length normalization removes differences in document length.
Clustering other kinds of objects, described by features in different units, usually requires standardizing each feature. That means subtracting its mean and dividing by its standard deviation, so that each has the same spread. A Gaussian mixture with full covariance matrices needs no such step: Gaussian Mixture Models proves that, from correspondingly transformed starting values, its fit follows any change of units exactly (Theorem 4), so standardizing changes nothing.
The Goodreads reviewer clustering shows what happens otherwise. Its features were average review length, as recorded in the dataset (most likely in characters), with values in the thousands, and three features on scales of a few units to about ten. Length accounted for more than 99.99 percent of the squared distance between the centroids of the two largest clusters, and the clusters became bands of review length.
Spherical k-means
TF-IDF vectors are already on one scale, but one more question remains about them. For text, what matters is usually the direction of a document vector, not its length. Standard k-means on unit vectors produces centroids that are shorter than unit length, since the mean of unit vectors pointing in different directions is shorter than any of them.
Spherical k-means (Dhillon and Modha, 2001, §3) normalizes each centroid back to unit length after the update step and assigns documents by cosine similarity to the centroids. It maximizes the total cosine similarity between documents and their centroids. Standard k-means on unit vectors assigns a document by its Euclidean distance to centroids of varying length. That is not the same as assigning by cosine, so the two can produce different clusterings.
Why it converges. The argument mirrors the one for k-means, with a quantity that rises instead of one that falls. Dhillon and Modha (2001, Lemma 3.1) prove by the same two steps that the objective never decreases. The objective is the total cosine $\sum_k \sum_{\vec{x} \in \omega_k} \vec{x} \cdot \vec{c}_k$, where the documents $\vec{x}$ and the centers $\vec{c}_k$ are unit vectors.
- The assignment step cannot lower it. With the centers fixed, each document contributes its dot product with its own center, and the step moves a document only to a center with a larger dot product.
- The update step cannot lower it. With the assignment fixed, cluster $k$ contributes $\sum_{\vec{x} \in \omega_k} \vec{x} \cdot \vec{c} = \vec{s}_k \cdot \vec{c}$, where $\vec{s}_k$ is the sum of its documents. By the Cauchy-Schwarz inequality, $\vec{s}_k \cdot \vec{c} \le \lvert \vec{s}_k \rvert\, \lvert \vec{c} \rvert = \lvert \vec{s}_k \rvert$ for every unit vector $\vec{c}$, with equality exactly when $\vec{c} = \vec{s}_k / \lvert \vec{s}_k \rvert$. So the normalized sum, which is the normalized mean, is the best unit center, and the cluster's contribution becomes $\lvert \vec{s}_k \rvert$.
- It stops. There are finitely many assignments, each with one value of the objective. If the assignment changes only when the objective strictly rises and ties are broken consistently, no assignment recurs, exactly as in the k-means algorithm.
The update needs $\vec{s}_k \ne \vec{0}$, which holds for TF-IDF vectors, whose coordinates are never negative.
A two-dimensional example shows how much shorter centroids get and why it matters. The mean of two orthogonal unit vectors, $(1, 0)$ and $(0, 1)$, is $(0.5, 0.5)$, of length $0.707$. A cluster whose members point in many directions has a centroid shorter still. For a unit document $\vec{x}$ and a centroid $\vec{\mu}$ at angle $\theta$,
$$\lvert \vec{x} - \vec{\mu} \rvert^2 = 1 + \lvert \vec{\mu} \rvert^2 - 2 \lvert \vec{\mu} \rvert \cos\theta,$$
which depends on the centroid's length as well as its direction.
Example (a short centroid loses a document). Standard k-means can assign a document to a centroid 35° away in preference to one pointing exactly along it. Take the document $\vec{x} = (1, 0)$, a short centroid $\vec{\mu}_1 = (0.3, 0)$ pointing exactly along it, and a unit-length centroid $\vec{\mu}_2$ at 35°. By cosine, $\vec{\mu}_1$ is the better match, 1 against 0.819. By squared distance, $\vec{\mu}_2$ is nearer, 0.362 against 0.490 (rounded to three decimals). Standard k-means sends the document to $\vec{\mu}_2$, and spherical k-means to $\vec{\mu}_1$. In general, standard k-means on text favors the tight clusters, whose centroids are long, over loose ones pointing the same way.
The two measured on Reuters. Every other choice in this article was measured, so this one was too. Spherical k-means was run from the same 30 random starts as the standard runs of the 30-seed table, with the same seed documents. Values are medians with interquartile ranges. The RSS of a spherical clustering is computed from the means of its clusters, so the two columns are comparable.
| Measure | Standard k-means | Spherical k-means |
|---|---|---|
| RSS | 6,559 (6,549 to 6,575) | 6,585 (6,578 to 6,600) |
| Purity | 0.784 (0.740 to 0.803) | 0.807 (0.783 to 0.825) |
| NMI | 0.459 (0.401 to 0.509) | 0.505 (0.471 to 0.543) |
| Rand index | 0.703 (0.662 to 0.737) | 0.737 (0.703 to 0.752) |
| Adjusted Rand index | 0.305 (0.215 to 0.395) | 0.381 (0.306 to 0.414) |
| Iterations | 28.5 (21 to 39) | 22.5 (17 to 29) |
Spherical k-means ended with a higher RSS in all 30 paired starts. That is expected but not guaranteed: RSS is not what spherical k-means optimizes, while each standard run stops at a local minimum of RSS that a different partition could in principle beat. It ended with a higher NMI in 27 of the 30 and a higher adjusted Rand index in 25. So on this collection, assigning by direction alone gave clusterings closer to the categories. That fits the pattern of the whole article: here, clusterings with a slightly worse RSS agreed better with the editors.
Worked problems
Problems 1 and 4 are Exercises 16.13 and 16.4 of the course text (Manning, Raghavan, and Schütze, 2008, §16.7 and §16.4.1), restated in our own words. Problems 2 and 3 are posed here on the article's own data.
Problem 1 (more clusters never cost more). Let $\mathrm{RSS}_{\min}(K)$ be the lowest RSS of any clustering of the collection into $K$ clusters. Prove that it decreases as $K$ grows.
We prove that $\mathrm{RSS}_{\min}(K + 1) < \mathrm{RSS}_{\min}(K)$ whenever $\mathrm{RSS}_{\min}(K) > 0$, for $K < N$. Once the minimum reaches zero it stays there.
Take a clustering into $K$ clusters with the lowest RSS, and suppose that RSS is positive. Then some cluster has a member $\vec{x}$ that differs from the cluster's mean $\vec{m}$, and that cluster has $n \ge 2$ members. Make $\vec{x}$ a cluster of its own. That is a clustering into $K + 1$ clusters. The new singleton costs nothing. By the formula proved in Problem 2 of the k-means algorithm, the cluster that lost $\vec{x}$ has its RSS lowered by $\frac{n}{n-1} \lvert \vec{x} - \vec{m} \rvert^2 > 0$. So this clustering into $K + 1$ clusters has a lower RSS than $\mathrm{RSS}_{\min}(K)$, and the best one has an RSS at least as low.
If $\mathrm{RSS}_{\min}(K) = 0$, every document coincides with its cluster's mean. Splitting any cluster with two or more members into two keeps the RSS at zero, so $\mathrm{RSS}_{\min}(K + 1) = 0$ as well. The complete statement is therefore: $\mathrm{RSS}_{\min}$ falls strictly until $K$ equals the number of distinct documents, and is zero from then on. The six points of the k-means algorithm show the strict fall: 36.71, 7.875, 2.458, 1.125, 0.5, 0 for $K = 1$ to 6. The result concerns the true minimum. The RSS that k-means actually finds can rise with $K$ in a single run, since each run ends at a local minimum.
Problem 2 (which penalty selects which K). For the table of RSS by $K$ above, find the values of $\lambda$ for which the criterion $\mathrm{RSS}(K) + \lambda K$ selects six clusters, and the $K$ selected for every other $\lambda$.
Six clusters are selected for $32.5 \le \lambda \le 51.67$. $K = 6$ beats a smaller $j$ when $\mathrm{RSS}(6) + 6\lambda \le \mathrm{RSS}(j) + j\lambda$, that is, when $\lambda \le (\mathrm{RSS}(j) - 6{,}529)/(6 - j)$. For $j = 5, 4, 3, 2$ the bounds are $62$, $110/2 = 55$, $155/3 = 51.67$ and $319/4 = 79.75$. The smallest is 51.67. $K = 6$ beats a larger $j$ when $\lambda \ge (6{,}529 - \mathrm{RSS}(j))/(j - 6)$. For $j = 8, 10, 12, 15, 20$ the bounds are $55/2 = 27.5$, $130/4 = 32.5$, $175/6 = 29.17$, $245/9 = 27.22$ and $330/14 = 23.57$. The largest is 32.5.
Repeating the comparison for every $K$ in the table gives the full picture:
| $\lambda$ | 0 to 17 | 17 to 23 | 23 to 32.5 | 32.5 to 51.67 | 51.67 to 164 | above 164 |
|---|---|---|---|---|---|---|
| $K$ selected | 20 | 15 | 10 | 6 | 3 | 2 |
Only six of the ten values of $K$ are ever selected. The others, 4, 5, 8 and 12, lie above the lower convex hull of the RSS curve and lose to a neighbor for every $\lambda$. The table uses RSS rounded to integers, the best of five runs each, and it stops at $K = 2$ and $K = 20$, so the end intervals describe the table and not the collection. The interval for six clusters is narrow, and nothing in the data singles it out in advance.
Problem 3 (the spherical update). A cluster holds the unit vectors $(1, 0)$, $(0, 1)$ and $(0.6, 0.8)$. Find the unit center that maximizes the total cosine and the value it reaches. Compare the member $(0.6, 0.8)$ as a center.
The best center is $(0.6644, 0.7474)$, with total cosine 2.4083. The sum of the three vectors is $\vec{s} = (1.6, 1.8)$, of length $\sqrt{1.6^2 + 1.8^2} = \sqrt{5.8} = 2.4083$. By the Cauchy-Schwarz argument above, the best unit center is $\vec{s} / \lvert \vec{s} \rvert = (0.6644, 0.7474)$ and the total cosine it reaches is $\lvert \vec{s} \rvert = 2.4083$. With the member $(0.6, 0.8)$ as center, the total is $0.6 + 0.8 + 1 = 2.4$, slightly less. The mean of the three vectors, $(0.5333, 0.6)$, points the same way as the best center but has length $2.4083/3 = 0.8028$. That shortfall from 1 is what standard k-means carries into its distances.
Problem 4 (synonyms in one cluster). Why are documents that use different terms for the same concept, such as car and automobile, likely to end up in the same k-means cluster?
Because a centroid pools the vocabulary of all its members, and documents about one subject share their other terms. A document is compared with centroids, never directly with another document. A small computed case shows the mechanism. Take five terms, car, automobile, engine, wheel and bank, and unit-length documents with equal weights on their terms. Two documents, {car, engine, wheel} and {automobile, engine, wheel}, have cosine $2/3$ through the two terms they share, so they cluster together. Their centroid is $(0.2887, 0.2887, 0.5774, 0.5774, 0)$: it has weight on both car and automobile. Now take two documents with no term in common, {car, engine} and {automobile, wheel}. Their cosine is 0. Each is at squared distance 0.6086 from that centroid, and at squared distance 2 from a centroid about bank. Both join the same cluster, although they share nothing with each other. In a real collection the shared context terms play the part of engine and wheel.
What we have learned
Starting points, $K$ and the vectors each change what k-means finds, not always in the expected direction:
- Run k-means several times and keep the lowest RSS, but expect clusterings with similar RSS to differ substantially.
- k-means++ seeding guards against seeds bunched in one region, at almost no cost, and is the default in widely used libraries such as scikit-learn (scikit-learn documentation). On Reuters it did not lower RSS compared with random seeds, but it found clusterings closer to the categories.
- Keeping the lowest RSS of several runs lowers RSS reliably; on Reuters it also lowered agreement with the categories.
- Name clusters by terms that are distinctive and present, not only distinctive: differential scores also rank terms a cluster lacks.
- The lowest attainable RSS always decreases with $K$, so $K$ must come from a knee, a penalty, or the application.
- Put features on comparable scales before clustering, or the largest one will decide the result.
- K-means minimizes RSS, and on real collections that can mean splitting large categories and merging small ones. On Reuters, spherical k-means, which ignores centroid length, agreed better with the categories.
Throughout this article the clusterings were graded by purity, NMI and the Rand index, and the three did not always agree. On Reuters, purity rose with $K$ while the adjusted Rand index peaked at six. Evaluating clusterings defines them step by step on a seventeen-document example and shows what each one rewards. Clustering measures corrected for chance derives the adjusted Rand index and tests every measure on clusterings that should score badly. Before that, Model-based clustering and the EM algorithm treats the clusters as probability distributions, which turns the hard assignments of k-means into degrees of membership.
The experiment scripts are tools/experiments/clustering/reuters_kmeans.py (the ten-run tables, the contingency table and RSS by $K$), reuters_restarts.py (the 30-seed measurements) and reuters_labels.py (the cluster labels, the single-cluster RSS and the spherical runs). The small examples and the worked problems are computed by lloyd_worked.py. All are in the site repository. The Reuters runs are seeded and the order of the feature terms is fixed, with ties in document frequency broken by first occurrence and then alphabetically, so a rerun reproduces every number here exactly. That order matters more than it might seem. With equally frequent terms in a different order the vectors are the same, but sums are rounded differently, and a story almost equally near two centroids can tip a run into a different local minimum.
References
- Arthur, D., and Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. In Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), 1027–1035. record
- Dhillon, I. S., and Modha, D. S. (2001). Concept decompositions for large sparse text data using clustering. Machine Learning, 42(1–2), 143–175. record
- Lewis, D. D. (1997). Reuters-21578 text categorization test collection, distribution 1.0. record · 11 pages
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 16.4, 16.7 and 17.7. Cambridge University Press. record · 102 pages
- scikit-learn documentation.
sklearn.cluster.KMeans. https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html record
Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 16 revisions