Subscribe
AI
5 min read

What Is K-Means Clustering? The 1957 Loop That Still Organizes AI Data

The assignment-and-update loop Stuart Lloyd designed in 1957 still clusters your embeddings, deduplicates training corpora, and builds the codebooks that shrink model weights.

What Is K-Means Clustering? The 1957 Loop That Still Organizes AI Data

K-means is the oldest workhorse in machine learning. Give it a pile of points and a number k, and it repeatedly assigns each point to its nearest center and moves each center to the average of its points, until nothing changes. Out of that two-line loop comes the grouping algorithm that still clusters your embeddings, deduplicates training corpora, and builds the codebooks that shrink model weights.

The idea is not from machine learning at all. Hugo Steinhaus posed the problem of dividing material bodies into parts in 1957, and Stuart Lloyd of Bell Labs designed the standard algorithm the same year, for pulse-code modulation, not publishing it until 1982 (Wikipedia history, Lloyd 1982). Edward Forgy published the same method in 1965, and James MacQueen coined the term "k-means" in 1967. The algorithm you run today is still Lloyd's loop, which is why statisticians call it Lloyd-Forgy.

The loop and what it optimizes

The objective is concrete: partition n points into k groups so the total within-cluster sum of squared distances is as small as possible. Each group is represented by its centroid, the mean of its members. Computing the perfect partition is provably hard. Aloise, Deshpande, Hansen and Popat showed in 2009 that Euclidean sum-of-squares clustering is NP-hard even in the plane (Machine Learning 75), settling a question about whether the simplicity of the algorithm hid an efficient solution. It does not.

So instead of solving the problem, k-means walks downhill on it:

  1. Pick k starting centers.
  2. Assign every point to its nearest center.
  3. Recompute each center as the mean of its assigned points.
  4. Repeat steps 2 and 3 until assignments stop changing.
The k-means iteration: scattered dots, dots linked to their nearest star-shaped center with region boundaries, and recomputed centers in a later pass

Every pass can only lower the total squared distance, so the process always terminates, but at a local minimum. Where you start decides where you finish. Bad initial centers can strand a center in empty territory or split one natural group while two others merge, and Arthur and Vassilvitskii showed that plain Lloyd can require super-polynomial time in the worst case. Their 2007 fix, k-means++, picks the first center at random, then each subsequent center with probability proportional to its squared distance to the nearest existing center. Spread-out seeds give an O(log k)-competitive guarantee, and in practice the seeding step alone accounts for most of the accuracy difference between a naive and a careful k-means run. This is why scikit-learn's KMeans uses k-means++ initialization by default and ships a MiniBatchKMeans variant that updates centers from random subsets, the standard way to run the loop on data too large to sweep in one pass (scikit-learn clustering docs). R ships a different refinement, the Hartigan-Wong algorithm from 1979, which moves one point at a time and generally does better than plain Lloyd, with several random starts recommended (R kmeans documentation).

Where k-means lives inside modern AI

You may never call k-means directly, but it is likely in your stack in four places.

Vector search. The FAISS library, which powers embedding search at billion-vector scale, builds its indexes with k-means twice. The inverted-file index runs k-means over the database to place coarse quantizer centroids, so a query only scans the clusters near it. The product quantization step, which compresses vectors to a few bytes each, was defined by Jégou, Douze and Schmid in 2011 as exactly this: split the space into low-dimensional subspaces and run k-means in each to learn the codebook (IEEE TPAMI 33(1)). Johnson, Douze and Jégou's 2017 GPU implementation of both steps is what made billion-scale k-NN graphs a commodity job, building a graph on 1 billion vectors in under 12 hours on four GPUs (arXiv 1702.08734). Every "find similar chunks" step in a RAG pipeline runs on centroids that k-means chose.

Training data deduplication. Exact-match dedup (hash every document, drop repeats) misses near-duplicates: the same blog post scraped twice with different boilerplate. Meta researchers addressed this with SemDeDup in 2023: embed every item, run k-means over the embedding space, and within each cluster remove points that sit within an epsilon-ball of another point, which is where semantic duplicates live. On a LAION subset the method removed 50% of the training data with minimal performance loss, effectively halving training time. On C4, an already partially curated text corpus, it kept about 80% of the data at comparable perplexity, a 15-20% compute saving over prior near-duplicate methods that removed far less. The same clustering-dedup logic appears in follow-up work like D4.

A conveyor-pipeline diagram: a dense dot cloud passes through rings that gather duplicate clusters, drops one batch into a bin, and exits as a thinned even stream

Self-supervised pretraining. Before contrastive learning took over, DeepCluster (Caron, Bojanowski, Joulin and Douze, ECCV 2018) trained image networks by running k-means on current features, treating the cluster index as a temporary label, and updating the network to predict those labels, iterating (arXiv 1807.05520). Clustering as a teacher turned out to have legs: Caron's later SwAV work trained by contrasting cluster assignments instead of image pairs, a direct descendant of using k-means partitions as supervision.

Weight quantization. This closes the historical circle. Lloyd's unpublished 1957 note was about designing quantization codebooks for pulse-code modulation: represent a continuous signal with a finite list of reconstruction values. That is still the definition of vector quantization. When AQLM compresses an open LLM to 2-3 bits per parameter, it does so via multi-codebook quantization: weight vectors are approximated by sums of codewords drawn from learned codebooks, and learning those codebooks is the same centers-and-assignments game Lloyd played for telephone signals, now run on transformer weight matrices in an input-adaptive fashion.

What to know before trusting it

The model behind the loop is "clusters are roughly spherical blobs of similar density." When real groups are elongated, nested, or wildly uneven in size, squared-distance assignment produces partitions that satisfy the objective and nothing else. Centroids in high dimensions need care: distance concentration weakens the notion of "nearest," and the literature on Lloyd's shortcomings consistently notes deterioration as dimensionality grows (Power k-Means, ICML 2019). You must also supply k, and the method gives you no honest answer for it; practitioners fall back on within-cluster inertia curves or stability across restarts, which are heuristics, not guarantees. Scale your features first, because squared Euclidean distance lets one wide-ranged dimension bully all the others.

What keeps k-means in production despite all of this is the same thing that kept it since 1957: one pass is a few matrix multiplications and an argmin, embarrassingly parallel, easy to understand, and good enough more often than fancier methods justify. In an era of trillion-token corpora, the cheap approximation that runs is worth more than the correct one that does not.

If you use embeddings for search, you are storing k-means centroids whether you chose to or not. The interesting question was never whether the 1957 algorithm still matters. It is which parts of your AI stack are running on local minima someone picked by starting the loop at random.

Sources

AILLMeducational