K-Means Clustering
A visual and mathematical explanation of clustering through iterative expectation-maximization, Voronoi partitioning, and centroid displacement.
Partitioning Continuous Feature Space
Given an unlabeled dataset of N observations X = {x_1, x_2, ..., x_N} where each observation x_i ∈ ℝ^d is a d-dimensional continuous vector, our goal is to partition the N observations into k non-empty, mutually disjoint subsets S = {S_1, S_2, ..., S_k} such that:
Finding the optimal partition that globally minimizes intra-cluster distance is an NP-hard combinatorial optimization problem even for k = 2 in general dimension. Lloyd's algorithm offers a deterministic heuristic that converges monotonically to a local optimum.
Centers of Gravity and Gravitational Pull
Imagine placing $k$ anchors onto a plane covered with particles. Each particle feels an allegiance to whichever anchor is closest to it, forming distinct territories known as Voronoi cells.
Once every particle has declared allegiance to its nearest anchor, each anchor relocates to the exact center of gravity (the mathematical mean vector $\mu_j$) of all its devoted particles.
Because the anchors moved, the territories shift. Particles on the borders might now find a different anchor closer. We repeat this dance until no particle changes allegiance and the anchors cease to move.
Objective Function & Coordinate Descent
The optimization objective minimizes the Within-Cluster Sum of Squares (WCSS), also referred to as inertia:
Where x_i is the observation vector, S_j is the j-th cluster subset, and \mu_j is the center coordinate vector of cluster j.
The Coordinate Descent Decomposition
Lloyd's algorithm solves this non-convex problem by alternating minimization across two sets of variables: the discrete cluster assignments $S$ and the continuous centroid coordinates $\mu$.
Holding centroids fixed, we assign each point x_i to the closest centroid \mu_j, which strictly minimizes J with respect to S.
Holding assignments fixed, taking the derivative with respect to \mu_j and setting to zero yields the arithmetic mean of the assigned points.
Because both Step 1 and Step 2 strictly decrease or preserve $J(S, \mu)$, and because the number of distinct partitions of $N$ points into $k$ subsets is finite (bounded by $k^N$), Lloyd's algorithm cannot cycle and must terminate at a local minimum in a finite number of iterations.
The 5-Step Execution Cycle
Select k initial centroids (Random or K-Means++ D²)
Compute pairwise L2 distances from all N points to k centroids
Assign each point to its closest centroid (argmin Euclidean distance)
Relocate each centroid to the mean of its assigned cluster
Check if centroid shift ||Δμ|| < ε. If not, repeat from 02
Observe Centroids Traversing the Manifold
Step through the alternating minimization phases. Watch the Voronoi partitioning update in real time as data points get captured by incoming centroids.
Vectorized NumPy Lloyd Algorithm
Production-grade Python code implementing vectorized pairwise distance broadcasting: $(N, 1, d) - (1, k, d) \to (N, k, d)$ without external machine learning dependencies.
Random Initialization vs. K-Means++
Standard Lloyd initialization randomly selects $k$ observations uniformly, which frequently places two centroids within the same true cluster. Arthur & Vassilvitskii (2007) introduced K-Means++, choosing subsequent centroids with probability proportional to their squared distance $D(x)^2$ from already chosen centroids, guaranteeing an $O(\log k)$ competitive ratio.
When K-Means Fails
Because distance is measured with isotropic Euclidean norms, K-Means assumes convex, spherical clusters. It completely fails on concentric circles, crescent moons, or manifold ribbons (DBSCAN or Spectral Clustering are required).
If one cluster contains 10,000 points and a neighboring cluster contains 100 points, K-Means will split the large cluster in half and merge the small cluster into the neighbor to minimize squared distance.
Features with large numerical variances dominate the squared distance computation. Features must strictly be standardized ($\mu = 0, \sigma = 1$) prior to clustering.
Because distances are squared in the objective function, a single rogue point far from the origin will drag a centroid away from legitimate data (K-Medoids / PAM provides an L1 robust alternative).
Concepts Orbiting K-Means
In ByteLogic, no concept lives in isolation. Explore the theoretical connections from K-Means to general latent variable models:
Soft probabilistic cluster assignments using Expectation-Maximization with full covariance matrices.
Ding & He (2004) proved that PCA subspaces are continuous relaxations of K-Means cluster indicator vectors.
Partitioning space into polygonal convex regions closest to a discrete set of seed sites.
