Lesson 17 · Structure without labels
Clustering: k-means and Gaussian mixtures
The problem
The shop has a map of its customers' houses: 180 of them, each a point in km east and km north of the shop. It wants 3 delivery zones, each with a driver base. Where should the bases go, and which houses should each one serve?
Nobody has labelled the houses with zones. There is no right answer to copy, so this is unsupervised learning again. Splitting examples into groups whose members are close to each other is called clustering. Each group is a cluster.
This lesson has two methods. The first places a centre for each cluster and gives every house to its nearest centre. The second gives each cluster a bell-shaped hill of any oval shape, and lets a house belong partly to two of them.
k-means: move each base to its houses
Here's a rule a manager might try by hand:
- Assign. Give each house to its nearest base.
- Move. Move each base to the average position of its houses.
- Repeat until no house changes base.
Moving a base to the middle of its houses makes their trips shorter. But then some houses near a border may be closer to a different base, so assign again.
Worked example
One round of k-means on 6 houses
Six houses: , , , , and . Two bases start, badly placed, at A and B .
This rule is k-means, for clusters, each with a centre at the mean of its points. Step through it on the 6 houses, then on the whole map, with 3 bases starting next to the shop.
Base 1 (0)Base 2 (0)
Start: 2 bases placed by hand. No house is assigned yet.
Total squared distance: not defined yet
Lines join each house to the base it belongs to.
Things to notice:
- On the map, the bases start in a clump at the shop. Over 7 rounds they spread out to the three groups of houses.
- Each assign step says how many houses switched base. The number drops to 0, and k-means stops.
- Watch the score in the chart.
The score k-means makes smaller
The score is the total squared distance from each point to its centre. scikit-learn calls it the inertia:
Here is house , is the cluster it's assigned to, and is cluster 's centre. Read it back: for every house, take its squared distance to its own base, and add them all up. Small means houses sit close to their bases.
Predict first
During k-means, can the inertia ever go up from one step to the next?
k-means measures closeness with straight-line distance. That's fair here, because both coordinates are in km. With features in different units, scale them first, or the biggest units decide the clusters.
DigressionWhere k-means comes fromA Bell Labs memo from 1957 that stayed unpublished for 25 years. · 1 min
Stuart Lloyd of Bell Labs described the assign-and-move rule in 1957, in a memo about sending signals with fewer bits. It wasn't published until 1982, in the IEEE Transactions on Information Theory, so the plain algorithm is often called Lloyd's algorithm. James MacQueen gave the method the name "k-means" in a 1967 paper. Similar ideas appeared independently in the 1950s and 1960s, including work by Hugo Steinhaus and by Edward Forgy.
The k-means++ starts in the next section are from David Arthur and Sergei Vassilvitskii, in 2007.
Where you start matters
k-means always stops. But it doesn't always stop at the best answer.
Here's a small town: four estates of 5 houses at the corners of a rectangle 6 km wide and 2 km tall. With 2 bases, the best split is clear: left against right. Its inertia is 21.5.
Base 1 (11)Base 2 (9)
Base 1 (10)Base 2 (10)
Final inertia: 21.5 after 2 rounds · best possible: 21.5
The best split: left against right.
Drag a base, or focus it and use the arrow keys.
Things to notice:
- Start one base above the other and k-means splits top against bottom, with inertia 181.5. That's more than 8 times worse.
- It stays there. Each base sits at the mean of its houses, and each house is closer to its own base than to the other. Neither step can change anything.
- Start the bases side by side and it finds left against right.
The top-against-bottom split is a local optimum: no single step can improve it, but a better answer exists elsewhere. It's like the local minimum of a function. k-means is a downhill method, so where it ends depends on where it starts.
The usual fix is to run k-means several times from different starts and keep the run with the lowest inertia.
3 of 6 runs got stuck. Keeping the run with the lowest inertia gives 21.5.
Dashed rings: where the two bases started. Crosses: where they ended. Each box is the inertia it reached; the best possible is 21.5.
Things to notice:
- Random starts pick 2 houses at random as the first bases. Two houses on the same side, one above the other, can lead to the trap. About 1 run in 7 gets stuck.
- k-means++ starts get stuck far less often.
- Either way, keeping the best of 6 runs almost always finds the best split.
k-means++: spread out the starts
Random starts often put two bases in the same group of houses. The k-means++ method picks the starting bases one at a time. It prefers houses far from the bases already chosen:
- Pick the first base: a house chosen at random.
- For every house, find its squared distance to the nearest base chosen so far.
- Pick the next base at random, with each house's chance in proportion to that squared distance.
- Repeat steps 2 and 3 until there are bases.
Base 1: a house picked at random. Every house had the same chance, 1 in 180.
Things to notice:
- Houses right next to a base have almost no chance. Squared distance makes far houses count a lot.
- So the second base almost always lands in a different group from the first, and the third in the group that's left.
- It's still random. Press "New random draw" a few times: now and then two bases land in the same group, and k-means has to sort it out.
DigressionHow many clusters? The elbow plot and the silhouette scoreTwo common ways to choose k, and why neither one settles it. · 3 min
The shop chose 3 zones because it has 3 drivers. Often nobody knows in advance. Two quick checks help.
The elbow plot. Run k-means for and plot the inertia. It always falls as grows: with one base per house it would be 0. So look for the bend, where adding a cluster stops helping much.
The silhouette score. For each point, let be its average distance to the other points in its own cluster. Let be its average distance to the points of the nearest other cluster. Its silhouette is
Near 1, the point sits well inside its cluster. Near 0, it's on a border. Negative, it's probably in the wrong cluster. Average over all points, and pick the with the highest average.
Base 1 (60)Base 2 (60)Base 3 (60)
k = 3: inertia 278.4 · silhouette 0.657
Each k is the best of 10 k-means++ runs. Colours and shapes repeat after 4 bases; the labels name each base.
Things to notice:
- The inertia falls from 1,523 to 791 to 278, then only to 168. The bend is at .
- The silhouette is highest at (0.657), but is close behind (0.635). The fourth base splits the long road zone in two.
- So both checks point to 3 here, but neither proves it. On messier data the bend is soft, and the silhouette favours round, well-separated clusters. In the end, is a hyperparameter, and the best choice often depends on the use: here, the number of drivers.
Bell curves in two dimensions
k-means gives every zone the same round shape: a house joins whichever centre is nearest. But look at the map's third group, which runs along a road. It's long and thin, and tilted. To describe groups like that, give each cluster a shape as well as a centre.
The normal distribution describes one number with a bell-shaped density. The same idea works for a point with two numbers. The density becomes a hill over the plane. Its height is greatest at the mean, and its contour lines are ellipses. The covariance matrix sets the ellipses' size, stretch and tilt, as in the PCA lesson's covariance ellipse.
This is the multivariate normal distribution, written for mean and covariance matrix .
Covariance matrix Σ = [[2.25, 0.45], [0.45, 0.36]]
Inside the solid ellipse: 41% of the samples (theory 39%). Inside the dashed one: 85% (theory 86%).
The covariance in the corner is correlation × spread₁ × spread₂. The same 300 random draws are reshaped each time.
Things to notice:
- With correlation 0, the ellipses line up with the axes. Positive correlation tilts them up and to the right.
- A big spread along one direction and a small one across it makes a long, thin cloud, like houses along a road.
- About 39% of the samples fall inside the solid ellipse and 86% inside the dashed one, whatever the shape. In two dimensions that's the rule for 1 and 2 standard deviations.
In dimensions, the density is
Read it back. The part inside the exponential is a squared distance from the mean, measured in the ellipse's own units. Along a long axis of the ellipse, a step of 1 km counts for little; across a short axis, it counts for a lot. The inverse does that rescaling.
The number in front makes the total volume under the hill 1. It uses the determinant, which measures how much stretches area.
When is the identity matrix, the distance is the ordinary squared distance , and the hill is round. That's the shape k-means assumes for every cluster.
Gaussian mixtures: zones as hills
Now picture the map as made by a random process. Each house first picks a zone, with zone having share (the shares add to 1). Then the house lands at a point drawn from that zone's 2-D normal, .
The density of houses on the map is the sum of the zones' hills, each scaled by its share:
This is a Gaussian mixture model. ("Gaussian" is another name for normal.) Each zone has a centre , like k-means. It also has a shape and a share .
Which zone did this house come from?
We only see the houses, not the zones they picked. But for a given house, we can ask how likely each zone is. That's Bayes' rule: the zone's share is the prior, and its density at the house is the evidence.
Worked example
A house between two zones
Two round zones with equal shares and the same spread, 1 km in every direction. A house is 1 km from zone A's centre and 2 km from zone B's.
In general, the chance that house came from zone is
The numbers are called responsibilities: how much of house each zone is responsible for. For each house they add to 1. Giving a point a probability for each cluster, instead of exactly one cluster, is a soft assignment. k-means makes hard assignments.
Fitting a mixture: EM
To fit the mixture, we want centres, shapes and shares that make the houses as likely as possible: maximum likelihood. If we knew which zone each house came from, that would be easy. Each zone's centre would be the mean of its houses, its shape their covariance matrix, and its share their fraction.
We don't know the zones. But with a guess at the model, we can compute the responsibilities. So alternate, as k-means does:
- E step (expectation). With the current model, compute every house's responsibilities .
- M step (maximisation). Refit each zone as if the responsibilities were exact, counting house as of a house in zone :
- share: , zone 's fraction of the houses
- centre: , a weighted average
- shape: , the covariance matrix of the houses, each weighted by
- Repeat until the model stops changing.
This is the expectation–maximisation (EM) algorithm. It works for any model with a hidden part. Here the hidden part is which zone each house came from.
Zone 1 (51)Zone 2 (53)Zone 3 (76)blended colour = unsure
Shares: Zone 1 33% · Zone 2 33% · Zone 3 33%
Houses with no zone above 90%: 120
Mean log-likelihood: −5.588 → −3.072 at the end
Each step colours the houses by their chances (E step), then refits each ellipse to its share of the houses (M step). Blended colours mean unsure. Dashed ellipses: 2 standard deviations.
Things to notice:
- At first, three round zones sit at the shop, and many houses have blended colours. The model can't yet tell the zones apart.
- The ellipses spread out to the three groups. The road zone stretches into a long, tilted ellipse, which a k-means zone can't do.
- The mean log-likelihood rises at every step, from −5.59 to −3.07, then stops changing. Like k-means' inertia, it never goes the wrong way.
- In the final model, almost every house is more than 90% sure of its zone, because the groups are well apart. A house in the gap between the town centre and the suburb would get a split, such as 72% and 28%.
The log-likelihood is the log of the mixture's density at each house, averaged over the houses. Higher means the model makes the houses more probable. EM can never lower it. The deeper aside below explains why.
When round zones fail
Predict first
Two long, thin groups of houses lie side by side along two parallel roads, 2 km apart and 8 km long. Does k-means with k = 2 split them along the roads?
Group 1 (53)Group 2 (47)
Group 1 (50)Group 2 (50)blended colour = unsure
k-means can only draw a straight border halfway between two centres. The mixture’s ellipses can be long and thin. Dashed ellipses: 2 standard deviations.
Things to notice:
- k-means cuts both roads in half. Each group mixes houses from both roads.
- The mixture puts one long, thin ellipse on each road, and every house is sure of its road.
- But the mixture found the roads only from a good start. Go back to the EM figure and choose "Roads, from k-means". Starting from k-means' answer, EM stays stuck cutting across. Its log-likelihood is lower: −3.59, against −2.56 for the roads. EM is also a local method, so restarts help here too.
DeeperEM in general, and k-means as EM with hard choicesWhy the likelihood can't go down, and what k-means has to do with it. · 4 min
EM has the same shape for any model with a hidden part:
- E step: with the current parameters, work out the probabilities of the hidden parts (here, which zone each house came from).
- M step: choose new parameters that maximise the likelihood, averaged over those probabilities.
Why the likelihood can't fall. Think of the E step as building a simpler stand-in for the log-likelihood. The stand-in touches the true curve at the current parameters and sits below it everywhere else.
The M step climbs to the top of the stand-in. Since the stand-in sits below the true curve, the true curve at the new point is at least as high as the stand-in's peak. And that peak is at least as high as where we started. So each step goes up or stays level. Like k-means, EM can stop at a local optimum.
k-means is a special case. Take a mixture where every zone is round with the same small spread and the same share. A house's responsibilities depend only on its distances to the centres, through . As shrinks, the nearest centre's term swamps all the others. Each house's responsibility becomes 1 for its nearest centre and 0 for the rest.
The E step becomes k-means' assign step. The M step's weighted average becomes the plain average of the assigned points: the move step.
So k-means is EM with hard assignments and round, equal clusters. That's why it's faster and simpler, and why it can't follow a long road.
Arthur Dempster, Nan Laird and Donald Rubin set out the general method in 1977. Their paper was "Maximum likelihood from incomplete data via the EM algorithm". They noted that special cases had been used many times before. Their convergence argument had a gap, which C. F. Jeff Wu closed in 1983.
k-means or a mixture?
| k-means | Gaussian mixture | |
|---|---|---|
| Each cluster is | a centre | a centre, an ellipse and a share |
| Each point gets | one cluster | a probability for each cluster |
| Cluster shapes | round, similar sizes | any ellipse |
| Speed | fast | slower (more numbers to fit) |
| Can get stuck | yes: restart | yes: restart |
Use k-means for a quick, simple split, especially with many points. Use a mixture when groups have different shapes or sizes, or when you need to know how sure each assignment is. Both need you to choose , and both need features on comparable scales.
In scikit-learn and PyTorch
scikit-learn's KMeans is an estimator. Its fit runs k-means; predict gives new points their nearest centre.
kmeans = KMeans(n_clusters=3, n_init=10, random_state=0) # 10 starts, keep the best
labels = kmeans.fit_predict(X) # (180,): a zone number per house
print(kmeans.cluster_centers_.round(2)) # the 3 bases
print(round(kmeans.inertia_, 1)) # 278.4: total squared distance to the nearest base
print(kmeans.predict([[0.0, 0.0]])) # a new house next to the shop: which base serves it?[[ 1.72 -2.17]
[-1.96 1. ]
[ 2.5 1.98]]
278.4
[1]What to notice:
n_init=10runs k-means from 10 k-means++ starts and keeps the lowest inertia. Set it explicitly. Since scikit-learn 1.4, the defaultn_init="auto"means a single run when the start is k-means++.inertia_is the total squared distance, 278.4, the same as the figures.- A new house next to the shop, at , goes to centre 1: the town centre, at .
- The cluster numbers are arbitrary. Another run could number the same zones differently.
Fixed starting centres give one run with no randomness. These are the three bases at the shop from the step-through figure:
start = np.array([[-1.0, -1.0], [0.0, 0.0], [1.0, 1.0]]) # three bases next to the shop
one_run = KMeans(n_clusters=3, init=start, n_init=1).fit(X) # from fixed starts: one run, no randomness
print(one_run.n_iter_, round(one_run.inertia_, 1))8 278.4It takes 8 rounds (the 8th round confirms nothing changes) and reaches the same inertia, 278.4, as the step-through figure.
On the four estates, the effect of the start:
E = four_estates() # (20, 2)
for init in ["random", "k-means++"]:
stuck = sum(KMeans(2, init=init, n_init=1, random_state=s).fit(E).inertia_ > 50 for s in range(200))
print(f"{init:9} stuck in {stuck} of 200 single runs")
best = KMeans(2, n_init=10, random_state=0).fit(E) # 10 runs, keep the lowest inertia
print("best of 10:", round(best.inertia_, 1))random stuck in 25 of 200 single runs
k-means++ stuck in 0 of 200 single runs
best of 10: 21.5scikit-learn's k-means++ is a little more careful than the version in the figure. At each pick it draws a few candidate houses and keeps the one that lowers the inertia most. Here that's enough to avoid the trap every time.
The mixture:
gmm = GaussianMixture(n_components=3, random_state=0).fit(X) # full covariances; starts from k-means
print(gmm.weights_.round(2)) # each zone's share of the houses
print(gmm.means_.round(2))
road = np.argmax(gmm.covariances_[:, 0, 0]) # the zone stretched east-west along the road
print(gmm.covariances_[road].round(2)) # a long, thin, tilted ellipse
between = np.array([[-0.2, 1.4]]) # a house in the gap between the town centre and the suburb
print(gmm.predict_proba(between).round(2)) # soft: a probability per zone
print(round(gmm.score(X), 3)) # mean log-likelihood per house[0.33 0.33 0.33]
[[ 1.72 -2.17]
[-1.96 1. ]
[ 2.5 1.98]]
[[2.63 0.65]
[0.65 0.23]]
[[0. 0.72 0.28]]
-3.072GaussianMixturefits full covariance matrices by default (covariance_type="full"). It starts EM from a k-means answer.- The road zone's covariance matrix has variance 2.63 east and 0.23 north, and covariance 0.65. That's a long ellipse, tilted up to the right.
predict_probagives the soft assignment. The house in the gap is 72% town centre, 28% suburb.scoreis the mean log-likelihood per house, −3.072, matching the end of the EM figure.
On the two roads:
R, which_road = two_roads()
km2 = KMeans(n_clusters=2, n_init=10, random_state=0).fit(R)
default = GaussianMixture(n_components=2, random_state=0).fit(R) # starts from k-means' answer
spread = GaussianMixture(n_components=2, n_init=10, init_params="random_from_data", random_state=0).fit(R)
def agreement(pred: np.ndarray) -> float:
"""Share of houses grouped as the roads are (cluster numbers may be swapped)."""
same = (pred == which_road).mean()
return max(same, 1 - same)
for name, pred, ll in [
("k-means", km2.labels_, None),
("mixture from k-means", default.predict(R), default.score(R)),
("mixture, 10 starts", spread.predict(R), spread.score(R)),
]:
print(f"{name:21} matches the roads for {agreement(pred):.0%}" + (f", log-likelihood {ll:.2f}" if ll else ""))k-means matches the roads for 59%
mixture from k-means matches the roads for 58%, log-likelihood -3.59
mixture, 10 starts matches the roads for 100%, log-likelihood -2.56The default mixture starts from k-means and stays stuck. With n_init=10 and init_params="random_from_data", it starts from 10 sets of random houses and keeps the run with the highest likelihood. That one finds the roads.
Clustering isn't only for maps. The taste profiles from the PCA lesson have 6 numbers per customer. With 3 clusters, k-means never sees the customer types. It still finds them almost exactly:
taste = load("taste-profiles")
T, kind = np.array(taste["x"]), np.array(taste["type"]) # (150, 6) shares; the type is hidden from k-means
found = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(T)
print(pd.crosstab(np.array(taste["types"])[kind], found, rownames=["type"], colnames=["cluster"]))cluster 0 1 2
type
adventurous 50 0 0
meat lover 1 0 49
veggie 0 50 0One meat lover lands with the adventurous eaters. Every other customer is grouped with their own type.
Finally, one EM step by hand in PyTorch. torch.distributions.MultivariateNormal gives each zone's log-density, and torch.logsumexp adds the zones' densities safely in log space (log-sum-exp).
def em_step(
X: torch.Tensor, weights: torch.Tensor, means: torch.Tensor, covs: torch.Tensor, reg: float = 1e-6
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""One EM step for a Gaussian mixture. X: (n, d); weights: (k,); means: (k, d); covs: (k, d, d)."""
# E step: how likely each point is to have come from each cluster
log_p = MultivariateNormal(means, covariance_matrix=covs).log_prob(X[:, None, :]) # (n, k)
log_joint = log_p + weights.log() # log(share × density)
log_lik = torch.logsumexp(log_joint, dim=1) # (n,): log of the mixture's density at each point
resp = (log_joint - log_lik[:, None]).exp() # (n, k): soft assignments, each row adds to 1
# M step: refit each cluster to its points, counting each point by its share
nk = resp.sum(dim=0) # (k,): "how many points" each cluster has
new_means = resp.T @ X / nk[:, None] # (k, d): weighted averages
diff = X[None, :, :] - new_means[:, None, :] # (k, n, d)
new_covs = torch.einsum("nk,kni,knj->kij", resp, diff, diff) / nk[:, None, None]
new_covs += reg * torch.eye(X.shape[1]) # keeps each Σ invertible, as scikit-learn's reg_covar
return resp, log_lik.mean(), nk / len(X), new_means, new_covs
Xt = torch.tensor(X, dtype=torch.float64)
w0 = torch.full((3,), 1 / 3, dtype=torch.float64)
m0 = torch.tensor(start, dtype=torch.float64) # the same three starts by the shop
c0 = torch.eye(2, dtype=torch.float64).repeat(3, 1, 1) # round clusters to begin with
resp, ll, w1, m1, c1 = em_step(Xt, w0, m0, c0)
print(round(ll.item(), 3), w1.numpy().round(3))-5.588 [0.282 0.281 0.437]log_prob(X[:, None, :])broadcasts 180 houses against 3 zones, giving a table of log-densities.- Subtracting each row's log-sum-exp and taking
expgives the responsibilities, which add to 1 across each row. - The M step is three weighted averages.
torch.einsumbuilds each zone's weighted covariance matrix in one line. - The log-likelihood and the new shares match the figure's first step, and scikit-learn's
GaussianMixtureafter one iteration from the same start. The third zone, at , takes the biggest share at first.
Putting it together
The shop's three zones, start to finish:
- Features: each house's km east and km north. Same units, so no scaling is needed.
- k-means with 3 bases, best of 10 k-means++ starts: bases at the town centre , the suburb and along the road . Inertia 278.4.
- Check : the elbow bends at 3 and the silhouette peaks at 3. Three drivers agree.
- A Gaussian mixture finds the same three centres, and adds shapes: the road zone is a long ellipse tilted along the road.
- Soft assignments flag the few houses between zones. Those are the ones to check by hand before drawing the delivery map.
Common misconceptions
"k-means finds the best clustering." It finds a local optimum, which depends on the start. Run it several times (n_init) and keep the lowest inertia.
"The inertia tells you the right k." It always falls as grows. Look for a bend, check the silhouette, and think about what the clusters are for.
"k-means finds any group you can see." It prefers round groups of similar size, because each house goes to its nearest centre. Long, thin or uneven groups get cut up.
"A Gaussian mixture always finds the right ellipses." EM can also stop at a local optimum. On the two roads, the default start from k-means stays stuck.
"Cluster 0 means the same thing every run." Cluster numbers are arbitrary labels. Compare clusterings by which points they group together, not by their numbers.
"Clusters are real groups." k-means will split any data into clusters, even pure noise. Clusters are a summary; check that they mean something.
Recap
- Clustering groups examples so each group's members are close, with no labels.
- k-means repeats two steps: assign each point to its nearest centre, then move each centre to its points' mean. The inertia (total squared distance) never goes up.
- k-means stops at a local optimum that depends on the start. k-means++ spreads the starts out. Keeping the best of several runs fixes most bad starts.
- A multivariate normal is a bell-shaped hill whose contours are ellipses, set by its covariance matrix.
- A Gaussian mixture models the data as a weighted sum of such hills. Each point gets a soft assignment: a probability for each cluster, from Bayes' rule.
- EM fits a mixture by alternating the E step (responsibilities) and the M step (weighted refits). The likelihood never goes down. k-means is EM with hard assignments and round clusters.
- Names in this lesson: scikit-learn's
KMeans(n_clusters,n_init,init,.inertia_,.cluster_centers_,.predict),GaussianMixture(n_components,n_init,init_params,.means_,.covariances_,.weights_,.predict_proba,.score) andsilhouette_score; PyTorch'storch.distributions.MultivariateNormal,torch.logsumexpandtorch.einsum.