Core Intuition: Gravitational Voronoi Basins
Imagine placing magnetic beacons in a field scattered with steel ball bearings. Every bearing rolls toward its nearest beacon, forming distinct clusters.
Now lift each beacon and place it at the exact geometric center of mass of the bearings that chose it. Bearings on the boundary reconsider their choice and roll toward their new nearest neighbor. Repeating this process until beacons stabilize partitions the field into clean geometric territories.
The Problem It Solves: Finding Hidden Structure
Supervised learning requires expensive ground-truth labels. In many real scenarios, labels do not exist: customer segmentation from transaction logs, document clustering in raw text archives, or palette quantization for image compression.
K-Means is an unsupervised algorithm that discovers natural subgroups without human supervision. It compresses millions of continuous feature vectors into representative centroid prototypes.
Step-by-Step Mechanism: Lloyd's Two-Phase Cycle
Lloyd's algorithm alternates between two complementary phases until convergence:
1. Assignment Phase: Centroids stay fixed. Assign each point to its closest centroid using squared Euclidean distance: . 2. Update Phase: Assignments stay fixed. Recompute each centroid as the arithmetic mean of all points assigned to cluster : .
Because both phases strictly reduce or preserve total squared error, the algorithm is guaranteed to converge in a finite number of steps.
Interactive Sandbox: Stepping Through Lloyd's Iterations
Explore the 2D coordinate plane with sample points and initial centroids. Click "Step Forward" to alternate between the Assignment phase (points take the color of their closest centroid) and the Update phase (centroids glide to the cluster center of mass).
Watch the Within-Cluster Sum of Squares (Inertia) drop with each step. Click "Step Back" to reverse the historical state and observe why local reassignments alter centroid trajectories.
Alternating optimization: (1) Assign each point to its nearest centroid (), and (2) Update each centroid to the cluster mean.
Mathematical Formulation: The Inertia Objective
The objective measures total internal cluster scatter. Minimizing globally is an NP-hard combinatorial problem. Lloyd algorithm implements coordinate descent: the assignment step minimizes with respect to cluster indicators , and the update step minimizes with respect to centroids .
Key Assumptions: Spherical Geometry & Equal Variance
K-Means makes strong geometric assumptions about data shape:
1. Spherical Clusters: Using Euclidean distance assumes clusters form isotropic spherical clouds. It fails on elongated, crescent, or spiral shapes. 2. Equal Variance and Scale: K-Means assumes clusters share similar diameters. A small dense cluster next to a large diffuse cluster causes points from the diffuse cluster to be absorbed incorrectly. 3. Planar Voronoi Boundaries: Decision boundaries between clusters are always straight hyperplanes perpendicular to centroid connections.
Common Pitfalls: Local Minima & Non-Convex Shapes
Random centroid initialization often gets trapped in bad local minima, splitting true clusters or leaving some centroids empty. K-Means++ fixes this by picking initial centroids with probability proportional to squared distance from existing centroids (), spreading them out across the dataset.
Additionally, K-Means cannot cluster non-convex geometries such as concentric rings because straight Voronoi boundaries cannot curve.
Suppose you run standard K-Means with K=2 on two concentric circles (an inner ring and an outer ring). What happens?
Computational Complexity: Linear in Samples
Each iteration computes Euclidean distances between all samples and all centroids across dimensions, taking operations. For iterations until convergence, total runtime is .
Space complexity is , requiring storage only for dataset features and centroid coordinates. At inference time, assigning a new unseen sample to the nearest cluster takes only operations.
Real-World Use: Vector Quantization & Retrieval
Beyond customer segmentation, K-Means is a workhorse in vector similarity search systems like FAISS and Milvus. Deep learning embeddings for millions of images or text chunks are quantized into thousands of Voronoi cells. At query time, the system inspects only the closest centroid cells, reducing search latency by orders of magnitude.
It is also used for color quantization in image compression, reducing millions of distinct RGB colors to an indexed palette of 16 or 32 representative cluster centers.
Production Code: NumPy & scikit-learn
Compare a vectorized NumPy implementation of Lloyd algorithm with scikit-learn optimized KMeans(init="k-means++", n_init=10).
import numpy as np
def kmeans_lloyd(X: np.ndarray, k: int = 3, max_iter: int = 100, tol: float = 1e-4):
n_samples, n_features = X.shape
# Randomly pick k distinct points as initial centroids
rng = np.random.default_rng(42)
indices = rng.choice(n_samples, size=k, replace=False)
centroids = X[indices].copy()
for iteration in range(max_iter):
# Compute squared distance from each point to each centroid: shape (n_samples, k)
distances = np.sum((X[:, np.newaxis, :] - centroids[np.newaxis, :, :]) ** 2, axis=2)
# Assign each point to the closest centroid
labels = np.argmin(distances, axis=1)
# Compute new centroids as cluster means
new_centroids = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)
])
shift = np.linalg.norm(new_centroids - centroids)
centroids = new_centroids
if shift < tol:
print(f"Converged at iteration {iteration} with shift {shift:.6f}")
break
# Calculate final inertia (WCSS)
inertia = np.sum([np.sum((X[labels == j] - centroids[j]) ** 2) for j in range(k)])
return centroids, labels, inertia
X = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0]])
centroids, labels, inertia = kmeans_lloyd(X, k=2)
print("Centroids:\n", centroids)
print(f"Final Inertia: {inertia:.3f}")In the NumPy function, broadcasting X[:, np.newaxis, :] - centroids[np.newaxis, :, :] computes all pairwise vector differences simultaneously without slow Python loops. In scikit-learn, KMeans uses k-means++ initialization by default and runs 10 random seeds (n_init=10), returning the model with the lowest inertia to prevent getting trapped in local minima.