Curriculum03. Unsupervised LearningLesson 1 of 4

K-Means Clustering & Lloyd's Algorithm

Unsupervised partitioning, Voronoi tessellations, and alternating coordinate descent.

25 min readIntermediateModule 03
01 // CORE INTUITION

Core Intuition: Gravitational Voronoi Basins

Imagine placing KK magnetic beacons in a field scattered with steel ball bearings. Every bearing rolls toward its nearest beacon, forming KK 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.

Takeaway:K-Means partitions space into Voronoi cells by repeatedly reassigning points and recentering prototype beacons.
02 // THE PROBLEM IT SOLVES

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 KK representative centroid prototypes.

Takeaway:Use K-Means to discover discrete, cohesive subgroups in unlabeled multidimensional data.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Lloyd's Two-Phase Cycle

Lloyd's algorithm alternates between two complementary phases until convergence:

1. Assignment Phase: Centroids μ1,…,μK\boldsymbol{\mu}_1, \dots, \boldsymbol{\mu}_K stay fixed. Assign each point x(i)\mathbf{x}^{(i)} to its closest centroid using squared Euclidean distance: c(i)=arg⁡min⁡k∥x(i)−μk∥22c^{(i)} = \arg\min_k \|\mathbf{x}^{(i)} - \boldsymbol{\mu}_k\|_2^2. 2. Update Phase: Assignments stay fixed. Recompute each centroid μk\boldsymbol{\mu}_k as the arithmetic mean of all points assigned to cluster kk: μk=1∣Sk∣∑i∈Skx(i)\boldsymbol{\mu}_k = \frac{1}{|S_k|} \sum_{i \in S_k} \mathbf{x}^{(i)}.

Because both phases strictly reduce or preserve total squared error, the algorithm is guaranteed to converge in a finite number of steps.

Takeaway:K-Means coordinates two alternating steps: Voronoi assignment and center-of-mass recentering.
04 // INTERACTIVE SANDBOX

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.

Lloyd Coordinate Descent Engine
PHASE: INITITERATION: 0INERTIA: 0

Alternating optimization: (1) Assign each point to its nearest centroid (c(i)=arg⁡min⁡k∥x(i)−μk∥22c^{(i)} = \arg\min_k \|\mathbf{x}^{(i)} - \boldsymbol{\mu}_k\|_2^2), and (2) Update each centroid to the cluster mean.

μ1μ2Feature x₁Feature x₂
Cluster 1 (μ₁)
Cluster 2 (μ₂)
Centroid assignment
Takeaway:Inertia decreases monotonically at every step until centroids stabilize and convergence is reached.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: The Inertia Objective

The objective JJ measures total internal cluster scatter. Minimizing JJ globally is an NP-hard combinatorial problem. Lloyd algorithm implements coordinate descent: the assignment step minimizes JJ with respect to cluster indicators SS, and the update step minimizes JJ with respect to centroids μ\boldsymbol{\mu}.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
JJTotal Within-Cluster Sum of Squares (WCSS), also called inertia or distortion
KKNumber of predefined cluster partitions
SkS_kSet of sample indices currently assigned to cluster kk
x(i)\mathbf{x}^{(i)}Feature vector of observation ii in dd-dimensional space
μk\boldsymbol{\mu}_kCentroid prototype vector of cluster kk
∥⋅∥22\|\cdot\|_2^2Squared Euclidean L2L_2 norm, penalizing distant points quadratically
Takeaway:K-Means minimizes inertia through coordinate descent on cluster indicators and centroid prototypes.
06 // KEY ASSUMPTIONS

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.

Takeaway:Verify that clusters are roughly spherical with comparable variance before relying on K-Means.
07 // COMMON PITFALLS

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 (D(x)2D(x)^2), spreading them out across the dataset.

Additionally, K-Means cannot cluster non-convex geometries such as concentric rings because straight Voronoi boundaries cannot curve.

Algorithmic Checkpoint

Suppose you run standard K-Means with K=2 on two concentric circles (an inner ring and an outer ring). What happens?

Takeaway:Use K-Means++ initialization to prevent bad local minima, and use DBSCAN or spectral clustering for curved manifold shapes.
08 // COMPLEXITY

Computational Complexity: Linear in Samples

Each iteration computes Euclidean distances between all nn samples and all KK centroids across dd dimensions, taking O(n⋅K⋅d)O(n \cdot K \cdot d) operations. For II iterations until convergence, total runtime is O(n⋅K⋅d⋅I)O(n \cdot K \cdot d \cdot I).

Space complexity is O(n⋅d+K⋅d)O(n \cdot d + K \cdot d), requiring storage only for dataset features and centroid coordinates. At inference time, assigning a new unseen sample to the nearest cluster takes only O(K⋅d)O(K \cdot d) operations.

Takeaway:K-Means scales linearly with dataset size n, making it practical for large datasets via mini-batch variants.
09 // REAL-WORLD USE

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.

Takeaway:Vector quantization using K-Means accelerates nearest-neighbor search across millions of embeddings.
10 // PRODUCTION CODE

Production Code: NumPy & scikit-learn

Compare a vectorized NumPy implementation of Lloyd algorithm with scikit-learn optimized KMeans(init="k-means++", n_init=10).

Production Implementation
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}")
Implementation Walkthrough:

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.

Takeaway:Always use k-means++ initialization with multiple restarts in production to escape bad local minima.