◆ AI All-in-One

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
↗ Plan a path here

Read first

Unsupervised LearningDot Product, Norms and Similarity

This leads to

—
The full path from zero — 6 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Dot Product, Norms and Similarity
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Unsupervised Learning
  7. 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:

  1. Assign. Every sunbather picks the nearest van.
  2. 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.

1. start 4 random points as centres 2. assign, then update centres jump to the means 3. repeat points switch, centres move 4. converged (5 updates) nothing changes any more × = cluster centre · dashed = path of each centre so far colour = the centre each point is currently assigned to
Fig. 1 k-means on 500 points with k = 4. It starts with four random points as centres (×). Each point is assigned to its nearest centre (colour), each centre moves to the mean of its points, and the two steps repeat. After five updates nothing changes and the algorithm stops.

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 kk, the number of clusters. Each cluster jj has a centre μj\boldsymbol{\mu}_j, 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:

J=∑i=1N∥xi−μc(i)∥2J = \sum_{i=1}^{N} \lVert \mathbf{x}_i - \boldsymbol{\mu}_{c(i)} \rVert^2

Here xi\mathbf{x}_i is point ii, c(i)c(i) is the cluster it is assigned to, and ∥⋅∥2\lVert \cdot \rVert^2 is the squared Euclidean distance. Small inertia means tight clusters.

Finding the assignment that makes JJ 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:

  1. Initialise: choose kk starting centres.
  2. Assign: put each point in the cluster of its nearest centre.
  3. Update: move each centre to the mean of its points: μj=1nj∑i∈cluster jxi\boldsymbol{\mu}_j = \frac{1}{n_j}\sum_{i \in \text{cluster } j} \mathbf{x}_i.
  4. Repeat steps 2 and 3 until the assignments stop changing.

Why does it settle? The assign step can only lower JJ (each point moves to a closer centre or stays). The update step can only lower JJ too, because the mean is the single point that minimises the total squared distance to a set of points. JJ 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, k=2k = 2, and (deliberately unlucky) starting centres at the first and fourth points:

Point A B C D E F G
(x1,x2)(x_1, x_2) (1, 1) (1.5, 2) (3, 3.9) (5, 7) (3.5, 5) (4.5, 5) (3.5, 4.5)

Start: μ1=(1,1)\boldsymbol{\mu}_1 = (1, 1), μ2=(5,7)\boldsymbol{\mu}_2 = (5, 7).

Assign (round 1). Distances from each point to the two centres:

A B C D E F G
to μ1\boldsymbol{\mu}_1 0 1.12 3.52 7.21 4.72 5.32 4.30
to μ2\boldsymbol{\mu}_2 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 (3−1)2+(3.9−1)2=4+8.41=3.52\sqrt{(3-1)^2 + (3.9-1)^2} = \sqrt{4 + 8.41} = 3.52 from μ1\boldsymbol{\mu}_1, just closer than 3.69 from μ2\boldsymbol{\mu}_2.

Update. New centres are the means:

  • μ1=(1+1.5+33,1+2+3.93)=(1.83,2.30)\boldsymbol{\mu}_1 = \left(\frac{1 + 1.5 + 3}{3}, \frac{1 + 2 + 3.9}{3}\right) = (1.83, 2.30)
  • μ2=(5+3.5+4.5+3.54,7+5+5+4.54)=(4.13,5.38)\boldsymbol{\mu}_2 = \left(\frac{5 + 3.5 + 4.5 + 3.5}{4}, \frac{7 + 5 + 5 + 4.5}{4}\right) = (4.13, 5.38)

Inertia falls from 32.7 (with the starting centres) to 11.9.

Assign (round 2). Point C is now 1.98 from μ1\boldsymbol{\mu}_1 but 1.86 from μ2\boldsymbol{\mu}_2, so it switches to cluster 2. Every other point stays put.

Update. μ1=(1.25,1.50)\boldsymbol{\mu}_1 = (1.25, 1.50) (the mean of A and B) and μ2=(3.90,5.08)\boldsymbol{\mu}_2 = (3.90, 5.08) (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 O(log⁡k)O(\log k) 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 kk. Inertia always falls as kk grows (with k=Nk = N 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 kk.
  • The silhouette score. For each point, let aa be its average distance to the other points in its own cluster and bb its average distance to the points of the nearest other cluster. Its silhouette is (b−a)/max⁡(a,b)(b - a)/\max(a, b): 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 kk with the highest score.
1 2 3 4 5 6 7 8 k (number of clusters) Inertia (elbow method) total squared distance to centres elbow at k = 4 1 2 3 4 5 6 7 8 0 0.4 0.8 k (number of clusters) Silhouette score higher = tighter, better-separated clusters k = 2 best k = 4 close the methods disagree: three of the four blobs touch, so k = 2 (the far blob versus the rest) also scores well
Fig. 2 Two ways to choose k for the 500 points in the first figure. Inertia (left) bends clearly at k = 4. The silhouette score (right) is highest at k = 2 and second-highest at k = 4, because three of the four blobs touch and one sits far away. Both answers are defensible.

The figure shows a common situation: the methods disagree, because the data has structure at more than one scale. In practice, kk 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.
k-means, k = 2 cuts straight across both moons DBSCAN follows each moon's shape k-means assumes round, similar-sized clusters around a centre; density-based methods do not
Fig. 3 k-means and DBSCAN on two interlocking half-moons. k-means, which can only draw straight boundaries between centres, cuts across both moons. DBSCAN, which grows clusters through dense regions, recovers each moon.

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 kk 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_samples neighbours within a radius eps. 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 kk 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_init of 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 kk 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 kk 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

  1. Redo the hand example starting from centres B (1.5,2)(1.5, 2) and F (4.5,5)(4.5, 5). Do you reach the same final clusters? How many rounds does it take?
  2. 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?
  3. 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() and rng.choice(len(X), p=p), where d2 is each point's squared distance to its nearest chosen centre.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In each round of Lloyd's algorithm, what are the two steps?

  2. Two runs of k-means from different random starts give inertia 1,885 and 2,821. What happened?

  3. Your data forms two interlocking half-moons. Which method is likely to recover each moon?

  4. Inertia falls steadily as k grows from 2 to 7. Why can't you just pick the k with the lowest inertia?

  5. A point's silhouette value is negative. What does that suggest?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

scikit-learn: Clustering

scikit-learn · Intermediate · Free

k-means, DBSCAN, hierarchical clustering, Gaussian mixtures and more, with a famous side-by-side comparison chart.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Book

Mining of Massive Datasets

Leskovec, Rajaraman & Ullman · Intermediate · Free

The Stanford book behind CS246. Its chapters on recommender systems, clustering and dimensionality reduction are excellent and free.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/k-means.md