Clustering groups observations according to a chosen notion of similarity. The distance measure, representation, and cluster model determine which groupings the algorithm can discover.
k-Means
k-Means partitions n points into k clusters by alternating two steps until convergence: (1) assign each point to its nearest centroid, (2) recompute each centroid as the mean of its assigned points. Formally it minimizes the within-cluster sum of squares:
J = Σ_{k} Σ_{x ∈ C_k} ‖x - μ_k‖²
Theorem 13.1 (Monotone decrease). Lloyd’s assignment and centroid updates never increase J. With exact centroid updates, a fixed tie order for initial assignment, retention of the current assignment on ties thereafter, and unchanged centroids for empty clusters, the algorithm reaches a fixed point in finitely many iterations.
Proof. Reassignment with fixed centroids minimizes each point’s squared distance. Retaining current assignments on ties ensures that any reassignment after initialization strictly reduces J. Recomputing each nonempty centroid as its cluster mean also cannot increase J: the derivative of the sum of squared distances vanishes at the mean, its unique minimizer. Empty clusters contribute zero. For each fixed assignment the nonempty centroids achieve a unique minimum objective value; there are finitely many assignments. After each exact update a changing assignment must lead to a strictly smaller value, so eventually the assignment and centroids are unchanged. A practical implementation can use first-index tie breaking, a numerical tolerance and an iteration cap; the theorem describes the exact variant. ∎
k-means is not guaranteed to find the global optimum — it is highly sensitive to centroid initialization, which motivates k-means++.
k-Means++ Initialization
Naive random initialization can produce poor local optima (e.g., two initial centroids landing in the same true cluster). k-means++ instead chooses initial centroids sequentially: pick the first uniformly at random, then each subsequent centroid with probability proportional to its squared distance to the nearest already-chosen centroid. This biases initialization toward spreading centroids across distinct regions of the data, and comes with a formal guarantee (Arthur & Vassilvitskii, 2007): the expected value of J at k-means++ initialization is within O(log k) of the optimal J, a guarantee plain random initialization does not have.
Continue with the book
Explore the full treatment, worked examples, and exercises in The AI Algorithms Compendium.
Companion article for The AI Algorithms Compendium, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
