45.08.08 · mathematical-statistics / 08-learning-methods

k-Means and Model-Based Clustering

shipped3 tiersLean: none

Anchor (Master): Hastie, Tibshirani & Friedman 2009 The Elements of Statistical Learning 2e (Springer) §14.3.6-14.3.12 (model-based clustering with Gaussian mixtures and BIC, hierarchical/agglomerative clustering and the dendrogram, spectral clustering via the graph Laplacian); Arthur & Vassilvitskii 2007 Proc. SODA pp. 1027-1035 (k-means++: the seeding and its -competitive expected approximation guarantee); Aloise, Deshpande, Hansen & Popat 2009 Machine Learning 75:245-248 (NP-hardness of Euclidean sum-of-squares clustering for general dimension)

Intuition Beginner

Imagine you have a scatter of dots on a page and you suspect they fall into a few natural clumps, but nobody has labelled which clump each dot belongs to. Clustering is the task of discovering those clumps from the dots alone. The most common recipe, called k-means, fixes the number of clumps in advance — say three — and then hunts for three good "centre" points and an assignment of every dot to its nearest centre.

The recipe runs as a back-and-forth loop. Drop three centres down somewhere to start. First move: hand each dot to whichever centre is closest to it, splitting the page into three territories. Second move: now that each centre owns a set of dots, slide that centre to the exact middle (the average position) of the dots it owns. Sliding the centres changes who is nearest to what, so repeat the first move, then the second, and keep going. Each pass tidies the clumps a little more.

The loop stops when nothing moves: every dot is already closest to its own centre, and every centre already sits at the middle of its dots. At that point you have a clustering. The quantity the loop quietly shrinks at every step is the total spread — the sum, over all dots, of the squared distance from each dot to its centre. Tight clumps mean a small total spread, so driving that number down is the same as finding compact groups.

One catch: where you drop the starting centres changes where you end up. A bad start can settle into a poor clumping, so people run the loop several times from different starts and keep the best.

Visual Beginner

Picture the page after a few passes. There are three small crosses for the three centres, and every dot is coloured to match the cross it was handed to. The colour boundaries look like straight fences halfway between neighbouring crosses, so the page is carved into three straight-edged territories, and each cross sits right in the middle of its own colour.

step what you do what comes out
assign with the centres fixed, colour each dot by its nearest centre a grouping of the dots into territories
update with the colours fixed, move each centre to the average of its dots new centre positions

The takeaway: k-means is two alternating moves — colour the dots by nearest centre, then move each centre to the middle of its dots — and repeating the pair shrinks the total spread until the picture stops changing.

Worked example Beginner

Six numbers on a line: . We look for two clusters (). Start with centres and .

Step 1, assign each number to its nearer centre. Numbers are closer to (distances ) than to . Numbers are closer to . So cluster one is and cluster two is .

Step 2, recompute each centre as the average of its cluster. Cluster one averages . Cluster two averages . The centres move to and .

Step 3, reassign with the new centres. Numbers are still nearest ; numbers are still nearest . Nobody switches teams, so the next update leaves the centres unchanged. The loop has settled.

Now total the spread to see what was minimised. With , cluster one contributes . With , cluster two contributes . The total spread is — small, because the two clumps are tight and far apart.

What this tells us: from a rough start, one assign-then-update pass already found the two obvious groups, and a second pass confirmed nothing should change. The number the loop drove down, the total squared distance to centres, ended at , the smallest it can be for this split.

Check your understanding Beginner

Formal definition Intermediate+

Let be observations and fix the number of clusters . A clustering is an assignment map partitioning the indices into clusters of sizes .

Definition (within-cluster scatter; k-means objective). With squared Euclidean dissimilarity, the pooled within-cluster sum of squares is

where is the cluster centroid. Introducing free representatives , this is the minimised value of the joint objective

so . The k-means problem is , equivalently .

Definition (Lloyd's algorithm). Starting from initial representatives , iterate for :

  • Assignment step. Holding fixed, assign each point to its nearest representative,
  • Update step. Holding fixed, set each representative to its cluster mean,

Iterate until the assignment is unchanged. (Ties in the assignment step are broken by a fixed rule; an emptied cluster is reseeded, e.g. at the point farthest from its centre.)

The identity shows is equivalently half the average within-cluster pairwise squared distance, weighted by cluster size; this is the form used when only a dissimilarity matrix is available.

Definition (k-medoids / PAM). Replacing the squared Euclidean distance by a general dissimilarity and constraining each representative to be one of the data points (a medoid ) gives k-medoids; the update step becomes a search over candidate medoids minimising within-cluster total dissimilarity, which is robust to outliers and applies to non-Euclidean data.

Definition (Gaussian mixture model; model-based clustering). A -component Gaussian mixture has density with mixing weights , , means , covariances , and the multivariate normal density 45.08.07. Model-based clustering fits this mixture by maximum likelihood (via EM) and assigns each point to the component of highest posterior responsibility . Constraining the covariances yields a family of models — spherical , diagonal, full, and tied () — of increasing flexibility and parameter count.

The new symbols are recorded in _meta/NOTATION.md: (within-cluster scatter), (joint k-means objective), (assignment map), (cluster centroid), (cluster size), (mixture parameters), (responsibility).

Counterexamples to common slips Intermediate+

  • "Lloyd's algorithm finds the clustering with the smallest ." It finds a local optimum: a partition no single assignment-or-update move can improve. The global k-means problem is NP-hard, and the local optimum reached depends on initialisation. Different starts give different, generally suboptimal, clusterings; multiple restarts (or k-means++ seeding) mitigate but do not remove this.

  • "k-means works with any distance." The centroid-update step is the minimiser of within-cluster scatter only for squared Euclidean distance; for an arbitrary dissimilarity the mean need not minimise total dissimilarity, and the monotone-descent guarantee fails. Use k-medoids, where the representative is an actual data point chosen to minimise total dissimilarity, for general .

  • "k-means recovers the true clusters if they exist." The objective rewards spherical, comparably sized, comparably scaled clusters. Elongated, unequal-variance, or unequal-population clusters are systematically mis-split because the nearest-centroid rule draws straight (Voronoi) boundaries; a Gaussian mixture with full covariances, which fits orientation and scale, is the corresponding fix.

  • "More clusters is always a better fit." is non-increasing in and reaches zero at (every point its own cluster), so alone cannot choose . A complexity-aware criterion is required — the gap statistic for k-means, BIC for the mixture-model likelihood 45.06.09.

Key theorem with proof Intermediate+

The signature result is that Lloyd's algorithm is a coordinate-descent on that decreases the objective at every step and terminates after finitely many iterations at a partition-local optimum. The two steps are the two block-minimisations of , and finiteness follows because takes finitely many values along the run [Lloyd, S. P. — Least Squares Quantization in PCM].

Theorem (monotone descent and finite termination of Lloyd's algorithm). Let . The Lloyd iteration satisfies

and the algorithm terminates after finitely many iterations at a pair that is simultaneously optimal in each block: and . Such a fixed point is a local minimum of in the sense that no reassignment of a single point and no recentring lowers .

Proof. Both steps minimise over one block with the other held fixed. The assignment step minimises : the summands are independent across , and each is minimised by sending to the nearest representative, which is exactly . Hence

The update step minimises , which separates over . For each the function is a sum of squared distances; its gradient vanishes at , and the Hessian is positive definite, so the centroid is the unique minimiser. Hence

establishing the monotone decrease. For termination: the value depends only on the assignment , and there are at most assignments, so takes finitely many values along the run. A strictly decreasing finite sequence cannot repeat, so after finitely many steps no assignment change occurs; at that point already assigns every point to its nearest current centroid and , the two fixed-point conditions. Because each summand is independently assigned-optimal and each centroid is recentring-optimal, no single reassignment and no recentring lowers .

Bridge. This monotone-descent guarantee is the foundational reason Lloyd's algorithm is usable despite the global k-means problem being NP-hard, and it builds toward the model-based generalisation: k-means is exactly the hard-assignment, zero-variance limit of the EM algorithm for a spherical Gaussian mixture 45.08.07, where the assignment step is the degenerate E-step (responsibilities collapsing to nearest-centroid indicators) and the centroid update is the M-step. This is dual to the soft picture of the mixture model — finite component variance gives fractional responsibilities and a smooth descent on the log-likelihood rather than the combinatorial . The central insight is that alternating block-minimisation of a single objective forces monotone descent whether the blocks are (assignment, centroids) here or (latent posterior, parameters) in EM, and this is exactly the coordinate-ascent structure proved for EM in 45.08.07. The two-condition fixed point — nearest-neighbour partition and centroid representative — generalises Lloyd's original quantizer-optimality conditions, and putting these together, the descent terminates only at a partition-local optimum, which is why initialisation (the k-means++ seeding of the Advanced results) and the choice of (the gap statistic and BIC) appear again as the two questions the descent itself cannot answer.

Exercises Intermediate+

Advanced results Master

The results below organise clustering around the descent theorem of the Key theorem: the seeding that controls which local optimum the descent reaches, the model-based mixture view and its complexity-penalised selection of the number of components, and the two structurally different families — hierarchical and spectral — that abandon a fixed- centroid objective entirely. The hard/soft EM connection of 45.08.07 and the model-selection machinery of 45.06.09 run throughout.

Theorem 1 (NP-hardness of the global k-means problem). Minimising over all partitions into clusters is NP-hard: for in dimension growing with (Aloise-Deshpande-Hansen-Popat), and for general in the plane (Mahajan-Nimbhorkar-Varadarajan). Consequently no polynomial-time algorithm solves k-means exactly unless P NP, and Lloyd's polynomial-per-iteration descent is necessarily a heuristic for the global problem. Lloyd's iteration count can itself be superpolynomial in the worst case (a lower bound) although it is fast in practice and has polynomial smoothed complexity [Arthur, D. & Vassilvitskii, S. — k-means++: The Advantages of Careful Seeding].

Theorem 2 (k-means++ seeding and its guarantee). Seed the centres by -weighting: pick uniformly at random from the data; for pick with probability proportional to , the squared distance to the nearest already-chosen centre. Let be the k-means cost of the resulting seeds (before any Lloyd step) and the optimal cost. Then

so k-means++ is -competitive in expectation, a guarantee uniform seeding lacks. Running Lloyd's monotone descent from these seeds only decreases the cost further, so the bound is preserved; this seeding-then-descent is the standard modern k-means [Arthur, D. & Vassilvitskii, S. — k-means++: The Advantages of Careful Seeding].

Theorem 3 (model-based clustering and BIC component selection). Fitting a -component Gaussian mixture by EM yields, for each covariance parameterisation (spherical, diagonal, full, tied) and each , a maximised log-likelihood and a parameter count . The Bayesian information criterion

is minimised over (and over the covariance family) to select the number and shape of components 45.06.09. Unlike , which decreases monotonically in , the likelihood-plus-penalty trades fit against parameters and admits an interior optimum; under regularity BIC is a consistent order selector. Because the free-covariance mixture likelihood is unbounded (a component mean on a single point with vanishing variance sends ), the EM fit targets a sensible interior local maximum, the same degeneracy flagged for mixtures in 45.08.07 [Hastie, T., Tibshirani, R. & Friedman, J. — The Elements of Statistical Learning (2nd ed.)].

Theorem 4 (agglomerative clustering and the dendrogram). Agglomerative hierarchical clustering starts with singleton clusters and repeatedly merges the two closest clusters under an inter-cluster dissimilarity — single linkage , complete linkage , group-average linkage , or Ward's minimum-variance criterion (merge the pair giving the least increase in ). The merge sequence is recorded as a dendrogram, a rooted binary tree whose merge heights equal the dissimilarities at which merges occur; for the linkages above (single, complete, average, Ward) the heights are monotone non-decreasing up the tree, so the dendrogram has no inversions and a clustering at any is read off by cutting at the corresponding height. The Lance-Williams recurrence updates from in per merged pair, giving an algorithm without committing to a fixed in advance [Hastie, T., Tibshirani, R. & Friedman, J. — The Elements of Statistical Learning (2nd ed.)].

Theorem 5 (spectral clustering via the graph Laplacian). Build a similarity graph with weight matrix , degree matrix , and unnormalised graph Laplacian . For any partition indicator , , so is positive semidefinite with constant null vector on a connected graph; the multiplicity of the eigenvalue equals the number of connected components. The balanced graph-cut objectives RatioCut and the normalised cut Ncut are NP-hard, and their continuous relaxations are solved by the bottom nonzero-eigenvalue eigenvectors of (respectively the normalised Laplacian ); spectral clustering embeds the points in the span of those eigenvectors and runs k-means in that embedding. The eigenvector embedding linearises clusters that are not linearly separable in the original space, which is why spectral methods recover non-convex (e.g. nested-ring) structure that centroid k-means cannot. This connects to the eigen-decomposition machinery of principal components 45.06.08 [Hastie, T., Tibshirani, R. & Friedman, J. — The Elements of Statistical Learning (2nd ed.)].

Synthesis. Clustering is one descent idea worked in several geometries, and the foundational reason the centroid method coheres is the Key theorem: alternating block-minimisation of forces monotone descent to a partition-local optimum, exactly the coordinate-ascent structure that drives EM in 45.08.07, of which hard k-means is the zero-variance limit. The central insight is that the descent answers neither of the two questions a clustering poses — which local optimum (controlled by k-means++ seeding, whose -weighting is -competitive against the NP-hard global problem) and how many clusters (controlled by the gap statistic for k-means and by BIC for the mixture likelihood 45.06.09, which unlike penalises complexity and so admits an interior optimum). This is dual to the model-based view: where k-means imposes spherical, equal-scale Voronoi cells, the Gaussian mixture with full covariances fits orientation and scale and reports soft responsibilities, so the same data can be clustered by a combinatorial objective or by a likelihood, and the two coincide in the spherical zero-variance limit.

Putting these together, hierarchical clustering abandons fixed for a whole dendrogram of nested partitions read at any cut height, and spectral clustering abandons centroid geometry for the graph Laplacian, whose bottom eigenvectors relax the NP-hard balanced-cut objectives and whose embedding — built from the same spectral theorem behind principal components 45.06.08 — linearises clusters that centroid methods cannot separate. The bridge across all four is that each replaces an intractable global combinatorial optimum with a tractable surrogate — a descent, a seeding, a greedy merge, or an eigenvector relaxation — and that none of them can be validated against a ground truth that, by the unsupervised premise, does not exist; cluster validation (stability under resampling, gap, silhouette, the dimensionless co-membership indices) is therefore an open, criterion-relative judgement rather than a test against a known answer.

Full proof set Master

Proposition 1 (centroid minimises within-cluster scatter; the bias-variance-style decomposition). For points and any , ; hence is the unique minimiser, with minimum the within-cluster scatter.

Proof. Insert : . Summing over , the cross term is because by the definition of the centroid. The remaining terms give . The first summand is independent of and the second is non-negative, vanishing iff ; hence the centroid is the unique minimiser and the minimum is the within-cluster scatter.

Proposition 2 (monotone descent and finite termination of Lloyd's algorithm). The Lloyd iteration satisfies for all and terminates in finitely many steps at a pair satisfying the nearest-neighbour and centroid fixed-point conditions.

Proof. The assignment step minimises over assignments: is a sum of independent per-point terms, each minimised by assigning to its nearest representative, so . The update step minimises over representatives: by Proposition 1 the per-cluster minimiser is the centroid , so . Chaining gives the monotone decrease. The realised values are determined by the assignment, of which there are at most ; a non-increasing sequence taking finitely many values and strictly decreasing whenever the assignment changes must, after finitely many steps, leave the assignment fixed. At that fixed assignment , every point is assigned to its nearest current centroid (else the assignment step would change it) and every (the update fixed point), the two stated conditions.

Proposition 3 (hard k-means as the limit of spherical-mixture EM). For the equal-weight spherical Gaussian mixture , as the EM responsibilities converge to the nearest-centroid indicators (for a unique nearest centre), and the EM M-step coincides with the Lloyd update.

Proof. With and equal weights, . Let , unique by assumption, and write . For , every exponent with the term equal to and all others as ; hence . For , the denominator term is since , so . The responsibilities become hard indicators, and the M-step mean becomes the average of the points whose nearest centre is — the Lloyd update. The EM monotonicity of 45.08.07 specialises in this limit to the Lloyd descent of Proposition 2.

Proposition 4 (positive semidefiniteness of the graph Laplacian and the quadratic-form identity). For a symmetric non-negative weight matrix with degree matrix , , the Laplacian satisfies for all ; consequently , , and on a connected graph .

Proof. Expand . The and terms each give , summing to ; the cross term gives . Hence . Since , the right side is non-negative, so . Taking makes every , so . If then for all , so is constant across every edge; on a connected graph this forces constant, so is one-dimensional. (On a graph with components the same argument gives , the indicator vectors of the components spanning the kernel.)

Proposition 5 (within/between decomposition: k-means maximises between-cluster scatter). Let be the total scatter about the grand mean . For any clustering, with the between-cluster scatter; since is fixed, minimising is equivalent to maximising .

Proof. Insert into each total-scatter term: for , . Summing over , the cross term vanishes because , leaving . Summing over gives . The total scatter depends only on the data, not on the clustering, so over partitions ; the minimiser of within-cluster scatter is the maximiser of between-cluster scatter.

Connections Master

  • k-means is the hard-assignment, zero-variance limit of the EM algorithm for a spherical Gaussian mixture developed in 45.08.07: the assignment step is the degenerate E-step whose responsibilities collapse to nearest-centroid indicators (Proposition 3), and the centroid update is the M-step. The monotone-descent guarantee of the Key theorem is the specialisation of EM's monotone ascent, and the foundational reason both algorithms converge is the same — alternating block-minimisation of a single objective — so the soft mixture model and hard k-means are two ends of one temperature scale.

  • Choosing the number of clusters reuses the model-assessment and selection machinery of 45.06.09: BIC selects the number of Gaussian-mixture components by trading likelihood against parameter count, exactly the complexity-penalised selection studied there, and the gap statistic plays the analogous role for the centroid objective , which on its own decreases monotonically in and so cannot select it.

  • Spectral clustering embeds points using the bottom eigenvectors of the graph Laplacian , built from the same symmetric-matrix spectral theorem that underlies principal components in 45.06.08: where PCA takes the top eigenvectors of a covariance (directions of maximal variance), spectral clustering takes the bottom nonzero-eigenvalue eigenvectors of the Laplacian (the smoothest functions on the graph), and both are eigen-embeddings that linearise structure before a downstream method (regression there, k-means here) is applied.

  • The soft-assignment / hard-assignment duality that relates k-means to its mixture model recurs as the relationship between the discriminant boundaries of 45.08.03 and the generative Gaussian model behind them: model-based clustering is the unsupervised counterpart of Gaussian discriminant analysis, fitting the same per-class Gaussians but inferring the class labels rather than observing them, so the central insight that a generative Gaussian model induces a geometric (quadratic or linear) decision rule appears again with the labels treated as latent.

Historical & philosophical context Master

The centroid algorithm has several independent origins. Stuart Lloyd described the alternating nearest-neighbour / centroid procedure for least-squares scalar quantization in a 1957 Bell Laboratories technical note, published only in 1982 in the IEEE Transactions on Information Theory [Lloyd, S. P. — Least Squares Quantization in PCM]; the name k-means is due to James MacQueen (1967), and Hugo Steinhaus (1956) and Edward Forgy (1965) gave closely related formulations, so the method is genuinely a case of multiple discovery across quantization, statistics, and pattern recognition. The vector-quantization generalisation of Linde, Buzo, and Gray (1980) is identical in form and is the version used in signal coding.

The computational status of the global problem was settled much later: Aloise, Deshpande, Hansen, and Popat (2009) proved that Euclidean sum-of-squares clustering is NP-hard already for two clusters in general dimension, and Mahajan, Nimbhorkar, and Varadarajan (2009) proved NP-hardness for general in the plane, so Lloyd's polynomial-per-iteration descent is necessarily a heuristic for an intractable optimum. The practical response was the -seeding of David Arthur and Sergei Vassilvitskii (2007), whose k-means++ gives the -competitive expected guarantee that uniform seeding lacks [Arthur, D. & Vassilvitskii, S. — k-means++: The Advantages of Careful Seeding]. The model-based programme — clustering as maximum-likelihood fitting of a finite mixture, with covariance constraints and BIC selection — was developed by Banfield and Raftery (1993) and Fraley and Raftery (2002) in the mclust framework, and the spectral approach via the graph Laplacian was synthesised by Shi and Malik (2000) (normalised cuts), Ng, Jordan, and Weiss (2002), and the survey of von Luxburg (2007). The recurring methodological difficulty, emphasised throughout Hastie, Tibshirani, and Friedman's treatment [Hastie, T., Tibshirani, R. & Friedman, J. — The Elements of Statistical Learning (2nd ed.)], is that unsupervised clustering has no ground-truth label against which to validate, so the choice of objective, dissimilarity, and number of clusters is criterion-relative and the resulting partition is a hypothesis rather than a verified answer.

Bibliography Master

@article{lloyd1982quantization,
  author  = {Lloyd, Stuart P.},
  title   = {Least squares quantization in {PCM}},
  journal = {IEEE Transactions on Information Theory},
  volume  = {28},
  number  = {2},
  pages   = {129--137},
  year    = {1982},
  note    = {Bell Laboratories technical note, 1957}
}

@inproceedings{arthur2007kmeanspp,
  author    = {Arthur, David and Vassilvitskii, Sergei},
  title     = {k-means++: The Advantages of Careful Seeding},
  booktitle = {Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA)},
  pages     = {1027--1035},
  year      = {2007}
}

@article{aloise2009nphard,
  author  = {Aloise, Daniel and Deshpande, Amit and Hansen, Pierre and Popat, Preyas},
  title   = {NP-hardness of {Euclidean} sum-of-squares clustering},
  journal = {Machine Learning},
  volume  = {75},
  number  = {2},
  pages   = {245--248},
  year    = {2009}
}

@article{macqueen1967kmeans,
  author  = {MacQueen, James},
  title   = {Some methods for classification and analysis of multivariate observations},
  journal = {Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability},
  volume  = {1},
  pages   = {281--297},
  year    = {1967}
}

@article{lindebuzogray1980,
  author  = {Linde, Yoseph and Buzo, Andr{\'e}s and Gray, Robert M.},
  title   = {An algorithm for vector quantizer design},
  journal = {IEEE Transactions on Communications},
  volume  = {28},
  number  = {1},
  pages   = {84--95},
  year    = {1980}
}

@article{fraleyraftery2002mclust,
  author  = {Fraley, Chris and Raftery, Adrian E.},
  title   = {Model-based clustering, discriminant analysis, and density estimation},
  journal = {Journal of the American Statistical Association},
  volume  = {97},
  number  = {458},
  pages   = {611--631},
  year    = {2002}
}

@article{vonluxburg2007spectral,
  author  = {von Luxburg, Ulrike},
  title   = {A tutorial on spectral clustering},
  journal = {Statistics and Computing},
  volume  = {17},
  number  = {4},
  pages   = {395--416},
  year    = {2007}
}

@article{shimalik2000ncut,
  author  = {Shi, Jianbo and Malik, Jitendra},
  title   = {Normalized cuts and image segmentation},
  journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
  volume  = {22},
  number  = {8},
  pages   = {888--905},
  year    = {2000}
}

@book{hastie2009esl,
  author    = {Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
  title     = {The Elements of Statistical Learning: Data Mining, Inference, and Prediction},
  edition   = {2},
  publisher = {Springer},
  year      = {2009}
}