โ† Wiki Index / Computation & Algorithms / k-Means Clustering
๐Ÿ’ป Computation & Algorithms

k-Means Clustering

k-Means clustering is an unsupervised vector quantization and partitioning algorithm that divides n multidimensional observations into k disjoint clusters by iteratively minimizing the within-cluster sum of squared Euclidean distances to cluster centroids.

k-Means clustering is a foundational unsupervised learning, data partitioning, and vector quantization algorithm in computation and algorithms, multivariate statistics, and signal processing. Given a dataset of n observations X = {x1, x2, โ€ฆ, xn} in d-dimensional Euclidean space โ„d and a user-specified integer k โ‰ค n, k-means partitions the data into k disjoint clusters S = {S1, S2, โ€ฆ, Sk} with cluster centers (centroids) ฮผ1, โ€ฆ, ฮผk โˆˆ โ„d so as to minimize the within-cluster sum of squares (WCSS), also known as the distortion or inertia objective.

The mathematical problem and its standard alternating minimization heuristic were discovered independently across four disciplines: by Hugo Steinhaus in 1956 (spatial mechanics), Stuart P. Lloyd at Bell Labs in 1957 (pulse-code modulation quantization, published in 1982), Edward W. Forgy in 1965, and James MacQueen in 1967, who coined the term "k-means." Geometrically, k-means tessellates โ„d into a centroidal Voronoi diagram whose cells are convex polyhedra, contrasting with density-based clustering methods such as DBSCAN, which discover arbitrarily shaped clusters and reject background noise without fixing k in advance.

Objective Function, NP-Hardness, and Lloyd's Alternating Algorithm

Given X โŠ‚ โ„d, the k-means optimization problem seeks a partition S = {S1, โ€ฆ, Sk} and centroid vectors ฮผ1, โ€ฆ, ฮผk โˆˆ โ„d minimizing the distortion function:

J(S, ฮผ) = โˆ‘j=1k โˆ‘xiโˆˆSj โ€–xi โˆ’ ฮผjโ€–22.

By the variance decomposition identity, minimizing the within-cluster sum of squares J(S, ฮผ) is algebraically equivalent to maximizing the between-cluster weighted sum of squared distances โˆ‘j=1k |Sj| โ€–ฮผj โˆ’ xฬ„โ€–22, and to a relaxed spectral trace maximization linked to principal component analysis (Ding & He, 2004). Despite its simple quadratic form, finding the global minimum of J(S, ฮผ) is NP-hard even for k = 2 clusters in general dimension d (Aloise et al., 2009) and for arbitrary k in the Euclidean plane d = 2 (Mahajan, Nimbhorkar, & Varadarajan, 2012).

Lloyd's Two-Step Coordinate Descent Iteration

Lloyd's algorithm finds a local minimum of J(S, ฮผ) by alternating between two coordinate-descent steps from an initial set of centroids {ฮผ1(0), โ€ฆ, ฮผk(0)}:

  1. Assignment (Voronoi) step: Holding the centroids ฮผ1(t), โ€ฆ, ฮผk(t) fixed, assign each data point xi to the cluster whose centroid is nearest in Euclidean distance (breaking ties deterministically by lowest index):

Sj(t) = { xi โˆˆ X : โ€–xi โˆ’ ฮผj(t)โ€–22 โ‰ค โ€–xi โˆ’ ฮผl(t)โ€–22 for all 1 โ‰ค l โ‰ค k }.

  1. Update (Centroid) step: Holding the cluster assignments S1(t), โ€ฆ, Sk(t) fixed, differentiate โˆ‘xiโˆˆSj โ€–xi โˆ’ ฮผjโ€–22 with respect to ฮผj to obtain the unique minimizerโ€”the arithmetic mean (center of mass) of the points in Sj(t):

ฮผj(t+1) = (1 / |Sj(t)|) โˆ‘xiโˆˆSj(t) xi.

Because both steps monotonically decrease the non-negative objective J(S, ฮผ) and there are at most kn finite partitions of n points, Lloyd's iteration always terminates in a finite number of steps at a stationary centroidal Voronoi configuration. Each iteration requires O(nkd) floating-point operations.

Initialization via k-Means++ and Accelerated Variants

When initial centroids are chosen uniformly at random from X (Forgy initialization), two centroids frequently land inside the same true cluster while another cluster receives none, trapping Lloyd's algorithm in arbitrarily poor local minima. In 2007, David Arthur and Sergei Vassilvitskii introduced k-means++ initialization, which spreads out initial centers via randomized D2-weighting:

  1. Choose the first center ฮผ1 uniformly at random from X.
  2. For each subsequent center m = 2, โ€ฆ, k, compute for every point xi โˆˆ X its squared distance D(xi)2 = min1โ‰คj<m โ€–xi โˆ’ ฮผjโ€–22 to the closest center already chosen, and sample the next center ฮผm = xi with probability proportional to D(xi)2 / โˆ‘r=1n D(xr)2.

Arthur and Vassilvitskii proved that k-means++ initialization alone guarantees an expected distortion ๐”ผ[J] โ‰ค 8(ln k + 2) Jopt before running a single Lloyd step, while accelerating subsequent Lloyd convergence by two- to tenfold.

Clustering Algorithm / VariantCluster GeometryOutlier & Noise RobustnessPer-Iteration Time ComplexityHyperparameters Required
Standard Lloyd's k-MeansConvex isotropic Voronoi cellsLow (squared loss sensitive to outliers)O(nkd)Number of clusters k
k-Means++ (Arthurโ€“Vassilvitskii)Convex isotropic Voronoi cellsLow (O(log k)-competitive seeding)O(nkd)Number of clusters k
Elkan / Hamerly Triangle-Inequality k-MeansExact match to Lloyd's k-MeansLowO(nd) to O(nkd)Number of clusters k
Mini-Batch k-Means (Sculley)Convex isotropic Voronoi cellsLowO(bkd) for batch size b โ‰ช nk, batch size b
k-Medoids (PAM / CLARA)Arbitrary metric space d(x, y)High (exemplars from data)O(k(n โˆ’ k)2)Number of medoids k
DBSCANArbitrary non-convex connected shapesHigh (explicit noise label)O(n log n) with spatial indexRadius ฮต, minimum points MinPts

Elkan's Triangle-Inequality Acceleration and Mini-Batch k-Means

In later iterations of Lloyd's algorithm, centroids move very little, so most point-to-centroid distance calculations โ€–xi โˆ’ ฮผjโ€–2 are redundant. Elkan's algorithm (2003) applies the metric triangle inequality โ€–xi โˆ’ ฮผjโ€–2 โ‰ฅ โ€–xi โˆ’ c(xi)โ€–2 whenever โ€–c(xi) โˆ’ ฮผjโ€–2 โ‰ฅ 2 โ€–xi โˆ’ c(xi)โ€–2 to skip up to 90% of distance evaluations while returning the same partition as standard Lloyd's algorithm. For web-scale datasets where n > 108, Mini-Batch k-Means (Sculley, 2010) samples random mini-batches of size b (e.g., b = 1,024) via a Monte Carlo method and applies stochastic gradient descent updates to the centroids.

Model Selection (Choosing k) and Relation to Gaussian Mixture Models

Because the raw distortion J(S, ฮผ) decreases monotonically as k increases (reaching J = 0 when k = n), selecting an appropriate cluster count k requires external criteria such as the Silhouette coefficient (Rousseeuw, 1987), which compares each point's mean intra-cluster distance a(i) against its nearest neighbor-cluster distance b(i) via s(i) = [b(i) โˆ’ a(i)] / max(a(i), b(i)) โˆˆ [โˆ’1, +1]; the Calinskiโ€“Harabasz variance-ratio criterion; or Tibshirani's Gap statistic, which compares log Jk against a Monte Carlo null reference distribution.

Probabilistically, k-means is the small-variance zero-temperature limit (ฯƒ2 โ†’ 0+) of the Expectationโ€“Maximization (EM) algorithm for an isotropic Gaussian Mixture Model (GMM) โˆ‘j=1k ฯ€j N(x | ฮผj, ฯƒ2I) with equal spherical covariances and equal mixing weights, where soft posterior responsibilities collapse to hard 0โ€“1 cluster assignments.

Frequently Asked Questions

When does k-means clustering fail?

Because k-means uses isotropic Euclidean distance from cluster means, it fails in three common scenarios: (1) non-convex or intertwined manifolds (such as concentric rings or crescent moons, where DBSCAN or spectral clustering succeeds); (2) elongated anisotropic elliptical clusters (where full-covariance Gaussian Mixture Models succeed); and (3) datasets with strong outliers, where squared Euclidean loss pulls centroids away from the cluster core (where k-medians or k-medoids succeeds).

Why should features be standardized before running k-means?

Because โ€–xi โˆ’ ฮผjโ€–22 = โˆ‘m=1d (xi,m โˆ’ ฮผj,m)2 sums squared coordinate differences across all dimensions, a single variable measured in large numerical units (such as income in dollars versus age in years) dominates the Euclidean distance unless features are standardized to zero mean and unit variance (z-scores).

References

  1. Lloyd, S. P. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2), 129โ€“137. https://doi.org/10.1109/TIT.1982.1056489
  2. MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, 1, 281โ€“297. https://doi.org/10.1525/9780520313880-018
  3. Arthur, D., & Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms, 1027โ€“1035. https://doi.org/10.1145/1283383.1283494
  4. Elkan, C. (2003). Using the triangle inequality to accelerate k-means. Proceedings of the Twentieth International Conference on Machine Learning (ICML), 147โ€“153. https://doi.org/10.5555/3041838.3041857
๐Ÿงฌ Support Open Science
Explore interactive science games on LowKey Games or browse scientific apparel & accessories in the CRV Science Shop.
๐Ÿ’ก Spot an inaccuracy or have primary literature to expand this article?
Submit a citation or revision note using your shared CRV Science / LowKey Games profile ID.
Suggest Revision