Week 3 · K-means: grouping without labels
Read the words of the video
- Imagine a city needing three new pizza shops. We don't know the neighborhoods, only where houses are. We drop three shops, then each house goes to its nearest shop. Next, each shop moves to the center of its customer crowd. We repeat this, moving shops and re-assigning customers, until nothing changes.
- This game is called k-means clustering. Its goal is to group data points without labels. We want to make sure every point is as close as possible to its group's center. Lloyd's algorithm does this: first, we assign each point to its nearest center, then we update each center to be the mean of its assigned points, and repeat until stable.
- Let's try a simple example with points on a line: one, two, three, ten, eleven, twelve. We start with two centers. Points one, two, three initially group with the first center, and the rest with the second. We update the first center to be the average of one, two, and three, making it two. The second center becomes the average of its points, eleven. Then, points are reassigned.
- Remember, k-means always stops in finite steps, reaching a local minimum, not necessarily the best overall. It doesn't find the global optimum. K-means++ helps by picking spread-out starting centers using squared distance. You cannot choose 'k' just by minimizing the objective; use the elbow method. Keep practicing the steps!
The one-minute story
A city wants to open 3 pizza shops so that everybody has a shop nearby. Nobody has told you the neighbourhoods; you just have a map of where houses are.
Try this game:
- Drop 3 shops anywhere on the map.
- Every house walks to its nearest shop. Now each shop has a crowd of customers.
- Move each shop to the centre of its own crowd (the average of the houses that chose it).
- Houses may now be closer to a different shop. Repeat steps 2 and 3.
After a few rounds nothing changes any more: every shop sits in the middle of its crowd and every house is at its nearest shop. You have just clustered the houses into 3 groups without anyone labelling them. That is k-means.
By the end of this week you can:
- state the k-means objective and run Lloyd's algorithm by hand;
- prove (in words) that it always converges, and say what it converges to;
- seed it well with k-means++;
- explain how kernel k-means handles non-round clusters.
Words you need
- Cluster - a group of points that are similar to each other.
- Centroid (or centre, mean) - the average of the points in cluster .
- - the number of clusters, chosen by you before you start.
- Objective - the total squared distance from every point to its own centroid. Smaller is a tighter clustering.
- Lloyd's algorithm - the "assign, then update" loop.
- Local optimum - a result that cannot be improved by small changes, but might not be the best overall.
Idea 1: What is k-means trying to do?
You have points and want to split them into groups. Let record which group point belongs to, and be the group centres. The k-means objective is
the sum of squared distances from each point to its own centre. Finding the global minimum over all possible splits is NP-hard (practically impossible for big data), so we use a clever heuristic.
Idea 2: Lloyd's algorithm
Lloyd's algorithm (what people usually mean by "k-means")
- Initialise centres (random points, or smarter: see k-means++).
- Assignment step. Send every point to its nearest centre: .
- Update step. Move every centre to the mean of the points assigned to it: .
- Repeat 2 and 3 until the assignments stop changing.
Why it always stops (and where it stops)
Each step solves a small problem exactly:
- Assignment step: if the centres are fixed, the best choice of for each point is clearly the nearest centre. So cannot go up.
- Update step: if the groups are fixed, the best centre for a group minimises . Setting the derivative to zero (MLF week 2) gives the mean. So cannot go up again.
So never increases. And there are only finitely many ways to split points into groups, so the algorithm cannot keep improving forever: it must stop after a finite number of steps.
Be precise about what is guaranteed. Lloyd's algorithm always converges, in finitely many steps, to a local minimum of . It is not guaranteed to reach the global minimum, and different starting centres can give different final answers.
Question. Cluster the 1-D points into groups, starting with centres and . Track the objective.
Solution.
Round 1, assign. (distance 0). . : distance to is 2, to is 1, so . . Groups: and . Objective with the current centres: .
Round 1, update. . . Objective now: .
Round 2, assign. : distance 1 to , 5.6 to . : 2 vs 4.6 . : 9 vs 2.4 . Groups: and . Objective (centres and ): .
Round 2, update. , . Objective: .
Round 3. Assignments do not change, so we stop. Final centres , .
The sequence only goes down, exactly as the argument promised. A start like is poor, yet the algorithm recovers here. With three clusters or a nastier layout it might not.
Idea 3: Starting well, k-means++
A bad start can trap Lloyd's algorithm (two centres inside the same blob, an empty blob left). k-means++ chooses starting centres that are spread out:
- Pick the first centre uniformly at random from the data.
- For every point , compute , its distance to the nearest centre already chosen.
- Pick the next centre from the data with probability proportional to .
- Repeat until you have centres. Then run Lloyd's.
Far-away points get a much bigger chance (squared distance), so new centres tend to land in uncovered regions. Guarantee: the expected objective is at most times the best possible, specifically .
Question. The first centre is at . The remaining data points are at (on a line). With what probability is each chosen as the second centre?
Solution. , so , summing to . Probabilities: . The farthest point is times as likely as the nearest.
Idea 4: Choosing , and what k-means assumes
- always decreases when you add clusters, reaching at (every point its own centre). So you cannot just pick the smallest .
- The elbow method: plot against and choose the "bend" where extra clusters stop helping much.
- k-means works best when clusters are round, similar in size and well separated. Long thin or nested shapes (like rings) break it.
- It is sensitive to scale (standardise features) and to outliers (a mean is dragged by extremes).
- The centre is the mean because of the squared distance. Using absolute distance would give the median (k-medians).
Link to the next week: k-means is the hard-assignment limit of a Gaussian mixture model fitted with EM. Every point belongs to one cluster, instead of having fractional memberships.
Idea 5: Kernel k-means
For ring-shaped clusters, run k-means in the lifted space of MLT week 2. We cannot compute the centre explicitly, but we do not need to: the squared distance from to it only needs kernel values:
Then Lloyd's algorithm proceeds as before with this distance: assign each point to the cluster giving the smallest value; there is no explicit centre to update.
Question. With the linear kernel , cluster and point , compute the kernel distance.
Solution. . . . Total . Indeed the mean of is , the point itself. ✓
Your turn
Points on a line: . Centres start at and . Do one assignment and one update. Then give the objective.
Need a hint?
Each point goes to the nearer centre.
Show the full solution
, , (distance 3 vs 5), . New centres: and . Objective: .
Points , , , with centres and . Assign, update, and give the objective.
Need a hint?
Distances from each point to both centres.
Show the full solution
; . New centres: and . Objective: : ; : ; : ; : 0. Total .
First centre at ; other points at . What is the probability that is the second centre?
Need a hint?
for each.
Show the full solution
, total . Probability for : .
A data set of 100 points has for . What is for ? Can increase when you go from to (at the optimum)?
Need a hint?
What happens when every point is its own cluster?
Show the full solution
at . The optimal cannot increase when grows (you could simply leave a cluster unused), so it is non-increasing. (Lloyd's algorithm itself may land in a worse local minimum for than a good one for , but the best possible value never goes up.)
(a) Lloyd's algorithm always converges in a finite number of steps. (b) It always finds the globally best clustering. (c) The centroid minimising the sum of squared distances is the mean. (d) With the same data and , different initialisations can give different results.
Need a hint?
Re-read the "why it stops" box.
Show the full solution
(a) True. (b) False, only a local minimum. (c) True. (d) True.
Exam radar
MLT Quiz 1 summaries mention convergence in 22 papers, K-means in 10, k-means++ in 10, initialisation in 9, k-means objective in 8, Lloyd's algorithm in 7, sum of squared distances in 7, and Euclidean distance in 10. End Term papers also revisit K-Means in 12.
Typical items: "does Lloyd's algorithm always converge? to what?" (finite steps, local minimum); a small run of one assignment and update; "k-means++ picks the next centre with probability proportional to ..." (squared distance); and kernel k-means distance computations.
- Converges globally optimal.
- k-means++ probability is proportional to (squared), not .
- The update uses the mean (squared distance). With absolute distance it would be the median.
- computed after assignment and after update are different numbers; read which one is asked.
- More clusters always lowers ; don't choose by minimising .
Quick quiz
In Lloyd's algorithm, the update step moves each centre to...
- the nearest data point
- the mean of the points assigned to it
- the median of all points
- a random location
Lloyd's algorithm is guaranteed to...
- find the global optimum
- converge in a finite number of steps to a local optimum
- never change the centres
- find the best k
In k-means++, the next centre is chosen with probability proportional to...
- the distance D
- D squared
- 1 / D
- the same for every point
Select all TRUE statements. (select all that apply)
- Increasing k never increases the optimal objective.
- k-means is sensitive to the scale of the features.
- k-means works well for ring-shaped clusters.
- The assignment step uses the median.
Recap
- Objective . Lloyd: assign to nearest centre, then move centres to means, repeat.
- never increases, finitely many partitions, so it converges in finite steps to a local minimum (not necessarily global).
- k-means++: next centre ; .
- as : use the elbow, not minimum . Assumes round, similar-sized clusters.
- Kernel k-means: distance via kernel values; handles non-linear shapes.
- ; assign ; update
- k-means++: ;
- Kernel distance:
- MLF week 2 - Slopes, change and the steepest way up: K-means rests on one calculus fact: the average is the number that makes squared distances smallest.
- MLP week 12 - Unsupervised learning in sklearn: K-means in scikit-learn.
Practise with real exam questions
These come straight from past papers (with the real figures and the official answer key). Open 34 real questions on this week All Quiz 1 papers