A shop has thousands of customers and a record of what each bought. It wants a few groups of similar customers, so that each group can get a suitable offer. Nobody has labelled the customers with a “right” group. The data itself has to suggest the groups.
That is clustering: split the examples into groups of similar ones, using no labels. It is the first lesson on unsupervised learning (P0.3). Supervised methods such as k-NN (P3.B1) are trained against labels. Here there is no , so the loss has to be computed from the data alone.
k-means is the best-known clustering method. Its idea fits in one sentence: assign each point to the nearest centre, then move each centre to the mean of its group, and repeat. This lesson explains why that works, where it fails, and how to choose the number of groups. All data here is made up, and the lesson says so wherever it matters.
What is a cluster, and why is it ill-posed?
A cluster is a group of points that are more similar to each other than to the rest. That is an idea, not a definition, and different definitions give different answers. Look at the customers: you could split them into 2 groups (big spenders and small), into 5 (by product type), or into 50 (one per shop district). None of these is wrong. A classifier can be scored against known labels; a clustering has no answer sheet.
So a clustering result is always a combination of choices you made:
- the distance between points (here, ordinary straight-line distance, P1.B4);
- the scale of every feature, since distance adds up all features;
- the number of groups , which k-means needs before it starts.
Keep this in mind for the whole lesson: k-means finds the best grouping for one precise definition of best, and whether that definition suits your data is up to you.
The objective: sum of squared distances to the centre
k-means describes each cluster by a single point, its centre (also called centroid), for cluster . Each point belongs to exactly one cluster; write for the number of the cluster of point . How good is a choice of centres and groups? Add up the squared distance from every point to the centre of its own cluster:
This is the within-cluster sum of squares (WCSS). Scikit-learn calls it inertia. Small means every point is close to its centre, so the clusters are tight. Dividing by gives the average loss of P0.3: each point’s loss is its squared distance to the nearest centre, and the parameters are the centres. This lesson uses the sum, which is what the libraries report.
The goal is to choose the groups and the centres to make as small as possible. Trying every possible grouping is hopeless: there are up to of them. The next section gives a fast shortcut.
Lloyd’s algorithm: two easy steps, repeated
- Start: choose starting centres (how to choose them well comes later).
- Assign: give every point to its nearest centre.
- Update: move every centre to the mean of the points assigned to it.
- Repeat steps 2 and 3 until an Assign step changes no point’s group.
This is called Lloyd’s algorithm, and people usually mean it when they say “k-means”.
A hand-worked example
Six made-up points on a line: . Take and start with the centres and .
-
Assign 1. Points and are nearer to centre (distances and ; to centre they are and ). Points are nearer to centre . The WCSS is the sum of the squared distances to the assigned centre:
-
Update 1. Centre 1 moves to the mean of , which is . Centre 2 moves to the mean of , which is . The first group adds . The four squared distances of the second group are , , and , which add to . The WCSS is .
-
Assign 2. Point is now nearer to (distance ) than to (distance ). It switches group. Groups: and . WCSS with the old centres: .
-
Update 2. The centres become and . WCSS: .
-
Assign 3. No point changes group, so the algorithm stops.
The WCSS went from to , then , then : it fell at every step. The next section shows that this is no accident.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
See it: step through the algorithm
The widget runs the same two steps on 2-D made-up points. Before the first Assign the points are grey and the large marks are the starting centres. Assign colours every point by its nearest centre. Update moves each centre to the mean of its colour, and a dashed trail shows where each centre has been. Marks differ in shape as well as colour. The readout shows the WCSS after every step.
Things to try (the data and the starts are fixed, so these numbers repeat):
- Well-separated blobs, , random start 1. Press Assign, Update and so on: the loop stops after 4 Assign steps, with all three blobs found (25 points each) and a WCSS of 82.24.
- Same data, still , random start 6. The loop also stops after 4 Assign steps, but at a WCSS of 362.10, with clusters of 10, 50 and 15 points. Two centres started in the top blob and none in the lower left one, so one centre has to cover two blobs. The algorithm cannot see that this is worse, because no single Assign or Update helps. Switch to k-means++ with the same start number: it takes 2 Assign steps and ends at 82.24.
- Unequal sizes, . The lowest WCSS the starts reach is 164.89 (for example random start 2), and some starts end at 229.38 (random start 5). The clusters of the best result have 18, 40 and 16 points although the data were drawn as groups of 50, 10 and 14: k-means follows distances, not the way the data was made.
- Two moons, . Whatever the start, the result has a WCSS of 198.84: a straight cut that slices both moons. The method cannot bend around a moon. A short section below returns to this.
- Raise to 6 on the blobs. The best WCSS you can reach keeps falling, but the extra clusters just cut up groups that were fine.
Why each step cannot make things worse
The two steps each solve a small problem exactly. Think of as a function of two things: the assignment (which cluster each point is in) and the centres.
The assign step is the best assignment for fixed centres. With the centres held fixed, is a sum of one term per point, , and each point chooses its cluster separately. The smallest term for point comes from choosing the nearest centre. So the Assign step minimizes over all assignments, and the new is less than or equal to the old one.
The update step is the best centre for a fixed group. With the assignment held fixed, splits into one sum per cluster, and each centre only affects its own sum. Take a group of points with mean (their sum divided by ), and let be the group’s total squared distance to a centre placed at the point . Then
(Here is the sum of over the points of . Write as the sum of and and expand the square. The cross term contains , which is zero by the definition of the mean.) The last term is never negative and is zero only for . So the mean is the one best centre for the group, and moving a centre there lowers or leaves it unchanged. That is why the algorithm uses the mean (and not, say, the median).
So the loop stops. never increases, and it does not change at all once an Assign step changes no group. There are only finitely many ways to split points into groups, and every pass that changes the grouping lowers strictly, so no grouping can be visited twice. The loop therefore reaches a grouping that the Assign step no longer changes, in a finite number of steps. (Exact ties are rare with real-valued data. The argument assumes that a point keeps its group unless another centre is strictly nearer.) In practice the loop usually needs a few to a few dozen iterations.
What the argument does not say: it does not say the final grouping has the smallest possible over all groupings. It only says that no single step can improve it.
Local minima: the start matters
The stopping point is a local minimum: no Assign or Update can improve it, yet a better grouping may exist. Which minimum you reach depends on the starting centres. You saw that in the widget (WCSS 82.24 versus 362.10 on the same blobs). The cell below runs the algorithm on made-up data with four round blobs, and uses the same code for two random starts, then for 200 starts of each kind of seeding.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Two random starts, seeded so that the result repeats, reach WCSS 351.6 and 159.7. The worse one merges two real blobs into one cluster (sizes 40, 60, 18, 22: the 60 is the blob of 40 and the blob of 20 at the top right joined together, and the blob of 40 at the lower left has been cut into 18 and 22). Finding the grouping with the lowest possible is a hard problem in general, so no method is guaranteed to find it on every data set. The standard defences are two cheap habits.
Seed with k-means++. The simplest start, k random data points as centres, can put two centres into one blob. k-means++ (Arthur and Vassilvitskii, 2007) spreads the centres out:
- Choose the first centre uniformly at random from the data points.
- For each point, find , the squared distance to the nearest centre chosen so far.
- Choose the next centre from the data points with probability proportional to : far-away points are the most likely, and points already chosen can never be chosen again, since their is zero.
- Repeat steps 2 and 3 until there are centres, then run Lloyd’s algorithm as usual.
The authors proved that this seeding alone gives an expected WCSS within a factor of order of the best possible. In the cell, the random starts end within 1% of the best result in 66% of the 200 runs and k-means++ in 88%. The worst runs of both are bad (670.0 and 666.6), so a lucky start is not guaranteed.
Restart and keep the best. Run the whole algorithm several times from different starts, and keep the run with the lowest WCSS. In scikit-learn this is the parameter n_init. Restarts cost several times the running time, but the quality of a single run is hard to judge by eye.
Choosing k
is a hyperparameter (P3.A4), and there is no labelled validation set to choose it. A tempting idea, the lowest WCSS, fails: the best never rises as grows (and in practice it falls), and it is zero at (every point is its own cluster). Three tools help.
The elbow plot. Plot the best WCSS against , and look for the bend where adding a cluster stops paying off. The cell below does this for two made-up data sets: four tight blobs and the same four blobs spread out much more. For the tight blobs, the drop from to is large (366.5 to 159.7) and the drop to is small (138.3), so is the elbow. For the loose blobs the WCSS falls in a smooth curve, 1400 to 909 to 632 to 520, and no bend is clear. The elbow is a visual rule, and many data sets look like the second one.
The silhouette score. This asks, for each point, whether it is nearer to its own cluster than to the next one. For point let
- be its mean distance to the other points of its own cluster;
- be the smallest, over the other clusters, of its mean distance to the points of that cluster.
Then which lies between and (and is by convention for a cluster of one point). Close to means the point is well inside its cluster; near means it sits on the border; negative means it is probably in the wrong cluster. The silhouette score is the mean of over all points; choose the with the highest one.
By hand, on the final grouping of the six points above, and : for the point , and , so . The six values are 0.769, 0.804, 0.559, 0.559, 0.804 and 0.769, and the mean is (scikit-learn gives the same).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
For the tight blobs the silhouette peaks at (0.685), in line with the elbow. For the loose blobs it is almost flat at 0.428, 0.416, 0.419 for : the data does not say clearly how many groups it has. Computing the score needs all pairwise distances, so its cost grows with .
What the groups are for. The most useful rule is often outside the data. A marketing team that can run four campaigns wants ; a colour palette of 16 colours means . Also check that the clusters are stable: if re-running with different starts or on half the data gives very different groups, the structure is weak. In the end, the number is a decision backed by evidence, not a measurement.
Assumptions and failure modes
Minimizing the sum of squared distances to centres implicitly assumes clusters that are round, of similar size and similar spread. Three ways it breaks, all in the cell below.
- Scale. Distances add up all features, so a feature in large units decides everything (the same issue as in k-NN, P3.A11). In the cell, two groups differ clearly in one feature, and a second, useless feature is measured in thousands. On the raw numbers, k-means recovers the true groups for only 51% of the points (about chance); after standardizing both features (P3.A11, using the mean and standard deviation of the data), it recovers 100%.
- Shape. The boundary between two clusters is a straight line, the set of points equally close to both centres. Two interleaved half-circles (“moons”) cannot be separated by a straight line, and k-means gets only 76% of the points right on made-up moons. Gaussian mixtures (P3.C2) give each cluster its own elliptical shape, and density-based clustering (P3.C6) follows curved clusters.
- Size. A blob of 150 points and a smaller one of 15 points four units apart: k-means cuts the big blob (clusters of 142 and 23 points), because that lowers the sum of squares more than keeping the small blob apart.
Also, because every centre is a mean, a few far-away outliers drag centres towards them. Remove obvious outliers first, or use a variant based on medians or real data points (named below).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What a run costs
Each iteration measures the distance from every one of points to every one of centres in dimensions, so it costs about operations (P1.G4); in NumPy this is the pairwise-distance table of P2.3, with numbers of memory. For , and that is about steps per iteration, and large data sets use mini-batch k-means, which updates the centres from small random batches.
Go deeper Compressing colours: vector quantization
Take an image with 24 bits per pixel (8 bits each for red, green and blue). Treat every pixel as a point in 3-D colour space and run k-means with . Now store, for every pixel, only the number of its nearest centre (4 bits, since ), plus a table of the 16 centre colours. The picture needs about of the memory, six times smaller, plus 16 colours of 24 bits each for the table, and the colours are the means of the groups, so the squared colour error is kept small. This is vector quantization: replace each vector by the nearest vector of a small code book. The same idea compresses collections of feature vectors.
Go deeper Variants and neighbours of k-means
k-medoids uses real data points as centres and can use any distance, which makes it more robust to outliers but slower. k-means is also a “hard” form of expectation-maximization for Gaussian mixtures, where every point is shared among the clusters with probabilities (P3.C2).
k-means in scikit-learn
Scikit-learn is not available in the browser, so this block is shown, not run. It was run locally (scikit-learn 1.8.0) on the same four-blob data as the cells above (make_data() with seed 5).
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
km = KMeans(n_clusters=4, random_state=0).fit(X) # k-means++ seeding, n_init="auto"
print("inertia :", round(km.inertia_, 1))
print("iterations :", km.n_iter_)
print("sizes :", np.bincount(km.labels_))
print("centres :", km.cluster_centers_.round(2).tolist())
print("silhouette :", round(silhouette_score(X, km.labels_), 3))
for k in range(2, 7):
m = KMeans(n_clusters=k, random_state=0).fit(X)
print(k, round(m.inertia_, 1), round(silhouette_score(X, m.labels_), 3))
inertia : 159.7
iterations : 3
sizes : [40 39 40 21]
centres : [[6.99, 2.93], [4.46, 7.63], [1.98, 1.75], [8.31, 8.2]]
silhouette : 0.685
2 896.0 0.516
3 366.5 0.634
4 159.7 0.685
5 137.7 0.607
6 122.0 0.488
The inertia (159.7) and silhouette (0.685) match the NumPy cells. Things to know about the defaults:
n_init. Since scikit-learn 1.4 the default is"auto": one run with the default"k-means++"seeding and ten runs with"random". Older tutorials may assume 10.- Scikit-learn’s k-means++ is a greedy version: for each new centre it tries a few candidates and keeps the best. That is why its inertia for and (137.7 and 122.0) is slightly lower than the cell’s table (138.3 and 123.4).
- Empty clusters. If a centre ends up with no points, the mean of nothing does not exist, so an implementation needs a rule. The widget leaves the centre where it is. Scikit-learn moves it onto a point far from its own centre. A frequent empty cluster can mean that is too large.
Depth: three ways to see it
Intuition
Imagine opening post offices in a town. Every house goes to its nearest office (Assign). Then each office moves to the middle of the houses it serves, to cut the total walking (Update). Houses may now be nearer to a different office, so repeat. Each move cannot increase the total walking distance squared, and eventually nothing moves. The analogy breaks when the real areas are not round or the walking is not straight-line: k-means draws straight borders and treats every direction the same.
Math
Objective:
Assign:
Update, with :
Neither step increases , so the sequence of values converges, and with finitely many assignments the loop ends. Cost: per iteration. Silhouette: .
Code
import numpy as np
def kmeans_step(X, C):
d2 = ((X[:, None, :] - C[None, :, :]) ** 2).sum(axis=2) # (N, k), as in P2.3
labels = d2.argmin(axis=1) # assign
C_new = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else C[j]
for j in range(len(C))]) # update
return labels, C_newRepeat kmeans_step until labels stops changing. In scikit-learn, use KMeans(n_clusters=k).fit(X).
Common mistakes
Quiz
Check your understanding
Why can an Update step never increase the WCSS?
The total squared distance to a centre equals the total squared distance to the mean plus the group size times the squared distance between the centre and the mean, so no centre beats the mean. The new centre is a mean, which is usually not a data point at all. Reassigning is the other step. Dividing by the number of points does not change which centre is best.
Two runs of k-means on the same data with different random starting centres end with different WCSS values. What is the best explanation?
Neither step can improve a point where the grouping is stable, but that point need not be the best one. The algorithm is deterministic given its start, so different starts can give different answers without any bug. The value of k is fixed in the question, and WCSS is a plain number with no free constant.
Two features describe each customer: age in years (about 20 to 70) and yearly spending in dollars (about 100 to 50,000). You run k-means on the raw numbers. What happens?
Squared differences in dollars are far larger than squared differences in years, so the dollar feature swamps the sum. Standard k-means does no rescaling by itself, and it runs without complaint, which is why the problem goes unnoticed. Age is not the dominant feature, since small numbers contribute little to the distance.
You plot the best WCSS against k for k = 1 to 10 and the curve falls smoothly with no bend. What should you conclude?
The best WCSS never rises as k grows for any data, so a smooth curve gives no preferred k, and other evidence has to decide. The lowest WCSS is at the largest k, and at k = N it reaches zero, so it favours the useless answer. A smooth curve is normal for loose data and not a sign of a bug. k = 1 gives the highest WCSS, so it only wins if there is truly one group.
k-means with k = 2 is run on two interleaved half-circles (moons). What is the main reason it does not separate them?
Every point goes to its nearest centre, so the points equally near two centres form a straight line and each cluster is a convex region. Two moons need a curved boundary. k-means uses no labels in the first place. Even moons of equal size fail, and k = 2 is the right number here, so neither a size difference nor the number of clusters is the cause.
Exercises
- Points on a line, , starting centres and . Run the algorithm and give the WCSS after each step.
Show answer
Assign 1: go to centre , and to centre (the point is from and from ). The squared distances are , so the WCSS is . Update: centres and . The two groups add and , so the WCSS is . Assign 2 changes nothing, so the algorithm stops with WCSS . - For the grouping and of exercise 1, compute the silhouette value of the point .
Show answer
, the distance to the point . , the mean distance to . So . - Points on a line. k-means++ has chosen the point as its first centre. What is the probability of each point being the second centre?
Show answer
The squared distances are , which add up to . The probabilities are , and . The point cannot be chosen again. - Roughly how many multiply-and-add steps does one Assign step cost for points, centres and features?
Show answer
About , which is . - What is the WCSS at , and why is it useless for choosing ?
Show answer
Zero: every point is its own cluster and its own centre, so every distance is zero. The WCSS never rises as grows, so it always favours the largest , and it says nothing about whether the groups are meaningful.
Next: P3.C2 softens k-means: Gaussian mixtures give every point a probability of belonging to each cluster, and fit with expectation-maximization. P3.C3 turns to principal component analysis, which reduces the number of features; P3.C6 covers density-based clustering for shapes k-means cannot follow. P3.A11 returns to scaling, which every distance-based method needs.