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)}:
- 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 }.
- 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:
- Choose the first center ฮผ1 uniformly at random from X.
- 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 / Variant | Cluster Geometry | Outlier & Noise Robustness | Per-Iteration Time Complexity | Hyperparameters Required |
|---|---|---|---|---|
| Standard Lloyd's k-Means | Convex isotropic Voronoi cells | Low (squared loss sensitive to outliers) | O(nkd) | Number of clusters k |
| k-Means++ (ArthurโVassilvitskii) | Convex isotropic Voronoi cells | Low (O(log k)-competitive seeding) | O(nkd) | Number of clusters k |
| Elkan / Hamerly Triangle-Inequality k-Means | Exact match to Lloyd's k-Means | Low | O(nd) to O(nkd) | Number of clusters k |
| Mini-Batch k-Means (Sculley) | Convex isotropic Voronoi cells | Low | O(bkd) for batch size b โช n | k, 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 |
| DBSCAN | Arbitrary non-convex connected shapes | High (explicit noise label) | O(n log n) with spatial index | Radius ฮต, 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
- 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
- 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
- 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
- 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