Level 3 In-Depth AI · Classical Machine Learning
k-Means Clustering
The classic way to split unlabelled data into k groups. Place k centres, assign every point to its nearest centre, move each centre to the middle of its points, and repeat until nothing changes.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- Vectors
- How Machines Learn
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Unsupervised Learning
- k-Means Clustering
Read them roughly in this order. See it on the concept map →
Why it matters
You have 50,000 customers, each described by how often they buy, how much they spend and what they buy. Marketing wants "about five types of customer" to design campaigns around. Nobody has labelled the customers with types. You need an algorithm that proposes groups on its own.
k-means is the first tool most people reach for. It is simple enough to code in ten lines, fast enough to run on millions of points, and easy to explain: every cluster is summarised by one representative point, its centre. It is used for:
- Segmentation: customers, products, documents, genes.
- Compression (vector quantisation): replace each colour in an image with the nearest of 16 "palette" colours, or each embedding with the nearest of a few thousand centres. Fast vector search indexes in Vector Databases use exactly this trick to skip most of the data.
- Features for other models: "which cluster is this in?" or "how far is it from each centre?" can be useful inputs to a supervised model.
- A first look at the structure of an unfamiliar dataset.
It is also the clearest example of an algorithm that alternates between two easy steps until it settles, an idea that reappears in the EM algorithm and many others.
The intuition
Imagine placing three ice-cream vans on a beach so that sunbathers walk as little as possible. Each sunbather goes to whichever van is closest. Start by parking the vans anywhere. Then:
- Assign. Every sunbather picks the nearest van.
- Update. Each driver looks at their own customers and moves the van to the middle of them, shortening their walks.
After the move some sunbathers find a different van is now closer, and switch. So the drivers move again. Repeat. Soon the vans stop moving: each one sits in the middle of its own crowd, and every sunbather is already at their nearest van. Each van's crowd is a cluster.
Key idea k-means alternates two steps: assign each point to its nearest centre, then move each centre to the mean of its assigned points. Each step lowers the total squared distance from points to their centres, so the process always settles, though not necessarily at the best possible clustering.
How it works
The objective
You choose , the number of clusters. Each cluster has a centre , also called its centroid. k-means tries to make the inertia, the total squared distance from each point to its own centre, as small as possible:
Here is point , is the cluster it is assigned to, and is the squared Euclidean distance. Small inertia means tight clusters.
Finding the assignment that makes smallest over all possible groupings is computationally hard (NP-hard). k-means doesn't try. It uses a fast local search called Lloyd's algorithm:
- Initialise: choose starting centres.
- Assign: put each point in the cluster of its nearest centre.
- Update: move each centre to the mean of its points: .
- Repeat steps 2 and 3 until the assignments stop changing.
Why does it settle? The assign step can only lower (each point moves to a closer centre or stays). The update step can only lower too, because the mean is the single point that minimises the total squared distance to a set of points. never goes up, and there are only finitely many ways to assign the points, so the algorithm must stop.
A worked example by hand
Seven points, , and (deliberately unlucky) starting centres at the first and fourth points:
| Point | A | B | C | D | E | F | G |
|---|---|---|---|---|---|---|---|
| (1, 1) | (1.5, 2) | (3, 3.9) | (5, 7) | (3.5, 5) | (4.5, 5) | (3.5, 4.5) |
Start: , .
Assign (round 1). Distances from each point to the two centres:
| A | B | C | D | E | F | G | |
|---|---|---|---|---|---|---|---|
| to | 0 | 1.12 | 3.52 | 7.21 | 4.72 | 5.32 | 4.30 |
| to | 7.21 | 6.10 | 3.69 | 0 | 2.50 | 2.06 | 2.92 |
Cluster 1 = {A, B, C}; cluster 2 = {D, E, F, G}. For example, C is from , just closer than 3.69 from .
Update. New centres are the means:
Inertia falls from 32.7 (with the starting centres) to 11.9.
Assign (round 2). Point C is now 1.98 from but 1.86 from , so it switches to cluster 2. Every other point stays put.
Update. (the mean of A and B) and (the mean of the other five). Inertia: 8.75.
Assign (round 3). Nobody switches. Done. The two clusters are {A, B} at the bottom left and {C, D, E, F, G} at the top right.
Starting well: k-means++
The result depends on where you start. A bad start can leave two centres sharing one real cluster while another centre straddles two clusters. The algorithm then converges to a local minimum, a clustering that no single assign or update step can improve but that is clearly worse than the best. In the code below, one random start reaches inertia 1,885 and another gets stuck at 2,821.
Two standard defences:
- k-means++ initialisation. Pick the first centre at random from the data. Pick each next centre at random too, but with probability proportional to its squared distance from the nearest centre chosen so far. Far-away points are much more likely to be picked, so the starting centres spread out. Arthur and Vassilvitskii showed in 2007 that this gives a result that is, in expectation, within a factor of of the best possible inertia. It is the default in scikit-learn.
- Several restarts. Run k-means several times from different starts (
n_init) and keep the run with the lowest inertia.
Choosing k
k-means needs you to say how many clusters you want. Two common aids:
- The elbow method. Plot inertia against . Inertia always falls as grows (with it is zero, every point its own cluster), but it usually falls steeply at first and then flattens. The bend, or "elbow", suggests a natural .
- The silhouette score. For each point, let be its average distance to the other points in its own cluster and its average distance to the points of the nearest other cluster. Its silhouette is : close to 1 if it sits snugly in its cluster, near 0 if it's on a border, negative if it's probably in the wrong cluster. Average over all points and pick the with the highest score.
The figure shows a common situation: the methods disagree, because the data has structure at more than one scale. In practice, is often decided by what is useful. Five customer segments may suit the marketing team better than the "statistically best" three.
What k-means assumes
Because each point goes to its nearest centre, every cluster is the set of points closer to its centre than to any other. Those regions are convex polygons (a Voronoi diagram). So k-means works best when clusters are:
- roughly round (spherical), not long, curved or ring-shaped;
- of similar size and spread, since a big diffuse cluster loses its edge points to a small tight neighbour;
- on comparable feature scales, which is why you standardise first.
Other clustering methods, briefly
- Hierarchical (agglomerative) clustering starts with every point as its own cluster and repeatedly merges the two closest clusters. The full history of merges is drawn as a tree called a dendrogram; cut it at any height to get any number of clusters. You don't have to choose in advance, but it is slow beyond tens of thousands of points.
- DBSCAN (density-based spatial clustering of applications with noise) grows clusters from points that have at least
min_samplesneighbours within a radiuseps. It finds clusters of any shape, works out how many there are by itself, and labels isolated points as noise rather than forcing them into a cluster. It struggles when clusters have very different densities. HDBSCAN is a popular extension that handles that. - Gaussian mixture models are a "soft" k-means: each cluster is a bell-shaped blob with its own size and orientation, and each point gets a probability of belonging to each. They are fitted with the EM algorithm, which alternates steps just as k-means does.
In code
k-means from scratch in NumPy. The three lines inside the loop are the whole algorithm. We run it from two different random starts:
import numpy as np
from sklearn.datasets import make_blobs
def kmeans(X, k, n_iter=100, seed=0):
rng = np.random.default_rng(seed)
centres = X[rng.choice(len(X), k, replace=False)] # start: k random points
for it in range(n_iter):
dists = np.linalg.norm(X[:, None, :] - centres[None, :, :], axis=2)
labels = dists.argmin(axis=1) # assign: nearest centre
new = np.array([X[labels == j].mean(axis=0) for j in range(k)]) # update: mean of members
if np.allclose(new, centres):
break
centres = new
inertia = ((X - centres[labels]) ** 2).sum()
return labels, centres, inertia, it
X, _ = make_blobs(n_samples=500, centers=4, cluster_std=1.5, random_state=1)
for seed in (0, 3):
labels, centres, inertia, iters = kmeans(X, k=4, seed=seed)
print(f"seed {seed}: converged after {iters} iterations, inertia {inertia:.1f}, "
f"sizes {np.bincount(labels)}")
# seed 0: converged after 5 iterations, inertia 1884.5, sizes [122 125 128 125]
# seed 3: converged after 13 iterations, inertia 2821.2, sizes [ 46 79 139 236]
Seed 0 finds the four real blobs of 125 points. Seed 3 gets stuck in a local minimum with lopsided clusters and 50% more inertia. That is why scikit-learn uses k-means++ and several restarts. Here it is scanning with both selection aids:
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=500, centers=4, cluster_std=1.5, random_state=1)
for k in range(2, 8):
km = KMeans(n_clusters=k, init="k-means++", n_init=10, random_state=0).fit(X)
print(f"k={k} inertia {km.inertia_:7.1f} silhouette {silhouette_score(X, km.labels_):.3f}")
# k=2 inertia 4915.5 silhouette 0.653
# k=3 inertia 3006.7 silhouette 0.490
# k=4 inertia 1884.5 silhouette 0.526
# k=5 inertia 1661.5 silhouette 0.479
# k=6 inertia 1472.8 silhouette 0.381
# k=7 inertia 1287.5 silhouette 0.367
km.cluster_centers_ holds the centres and km.predict(new_points) assigns new data. For millions of points, MiniBatchKMeans updates the centres from small random batches and is much faster. AgglomerativeClustering and DBSCAN live in the same sklearn.cluster module.
Common pitfalls
- Not scaling features. k-means uses Euclidean distance, so a feature measured in thousands dominates one measured in units. Standardise first, unless the raw units really do reflect what "similar" should mean.
- Trusting a single run. One unlucky start gives a poor local minimum. Use k-means++ and
n_initof 10 or so. - Forcing k-means onto the wrong shapes. Elongated, curved, nested or very unequal clusters break its assumptions. Plot the data (after PCA and Dimensionality Reduction if needed), and try DBSCAN or a Gaussian mixture.
- Outliers. A few extreme points drag centres towards them, because the mean is sensitive to outliers. Remove them first, or use k-medoids, which uses actual data points as centres.
- Reading meaning into arbitrary clusters. k-means always returns clusters, even for data with no clusters at all. Check that the clusters are stable across runs and subsamples, and that they mean something.
- Categorical data. Means of category codes are meaningless. Use one-hot encoding with care, or k-modes, or a method built for categories.
Watch out k-means will happily split a single blob of random noise into tidy-looking pieces. A clean result is not evidence of real groups. Look at the silhouette score, re-run on subsamples, and ask whether the clusters make sense to someone who knows the data.
Where it leads
- Gaussian mixture models and EM: soft, probabilistic clustering with elliptical clusters.
- Vector quantisation in approximate nearest-neighbour search (inverted-file indexes, product quantisation) powers Vector Databases and Embeddings and Semantic Search.
- Image tokenisers: some image and audio generators compress patches into discrete codes by picking the nearest of a learned set of centres, a k-means-like codebook (see Variational Autoencoders).
- Dimensionality reduction before clustering makes distances more meaningful in high dimensions. See PCA and Dimensionality Reduction and t-SNE and UMAP.
- Anomaly detection: a point far from every centre is unusual. See Anomaly Detection.
A bit of history
Stuart Lloyd devised the algorithm at Bell Labs in 1957 for a problem in signal processing: choosing the levels with which to quantise a signal. His report circulated internally and was only formally published in 1982, which is why the method is often called Lloyd's algorithm. Edward Forgy published essentially the same method in 1965, and James MacQueen coined the name "k-means" in 1967. David Arthur and Sergei Vassilvitskii introduced k-means++ seeding in 2007. DBSCAN was published by Ester, Kriegel, Sander and Xu in 1996. Despite being over sixty years old, k-means remains one of the most used algorithms in data analysis.
Try it
- Redo the hand example starting from centres B and F . Do you reach the same final clusters? How many rounds does it take?
- In the from-scratch code, replace the random start with k-means++ seeding (pick each new centre with probability proportional to its squared distance to the nearest existing centre). Does seed 3 still get stuck?
- Harder: run
KMeans(n_clusters=3)on 300 uniformly random points (np.random.rand(300, 2)). Plot the result. What is the silhouette score? Does the data have clusters?Hint for 2:
p = d2 / d2.sum()andrng.choice(len(X), p=p), whered2is each point's squared distance to its nearest chosen centre.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Clustering
k-means, DBSCAN, hierarchical clustering, Gaussian mixtures and more, with a famous side-by-side comparison chart.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
Mining of Massive Datasets
The Stanford book behind CS246. Its chapters on recommender systems, clustering and dimensionality reduction are excellent and free.
The Elements of Statistical Learning
The graduate-level reference for classical statistical learning. Free PDF.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/k-means.md