Exercise: feature spaces and k-means
Before this unit: Day 12: Thresholding.
See also: Day 33: Random forests; Day 46: Colour; Day 39: Variational autoencoders.
Goal
By the end of this exercise you should be able to:
- describe pixels and objects as points in a feature space,
- run k-means (Lloyd’s algorithm) by hand on a few points, and compute J at every step,
- explain why k-means always stops, why it can stop in a local minimum, and how k-means++ and restarts help,
- predict where k-means fails: elongated groups, groups of different sizes, features in different units.
Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
| Word | Meaning |
|---|---|
| Feature space | one axis per measured number (intensity, colour channels, position, area, …); every pixel or object is a point |
| Centre \mathbf m_k | the representative point of group k |
| Assign step | every point goes to its nearest centre (Voronoi cells) |
| Update step | every centre moves to the mean of its points |
| J | \sum_i \lVert\mathbf x_i - \mathbf m_{c(i)}\rVert^2, the within-cluster sum of squares |
| k-means++ | next centre drawn with probability \propto D(\mathbf x)^2, the squared distance to the nearest centre so far |
By hand
B1. Points 1, 2, 4, 7, 9, 10 on a line, K = 2, start \mathbf m = (1, 2). (a) Run k-means to convergence. After every assign step give the groups and J; after every update step the centres. (b) Where is the boundary between the two groups at the end? (c) Start instead from \mathbf m = (4, 7). Where does it end?
B2. Points 0, 1, 5, 6, 10, 11, K = 3, start \mathbf m = (0, 1, 8). (a) Do one assign and one update step. Show that nothing changes any more. What is J? (b) Compute J for the groups \{0, 1\}, \{5, 6\}, \{10, 11\}. (c) Explain in one sentence why no single step of k-means can get from (a) to (b).
B3. k-means++ on the points of B2, with the first centre at 0. (a) Give the probability of each point being chosen as the second centre. What is the probability that it is 10 or 11? (b) Suppose the second centre is 10. Give the probabilities for the third centre. How likely is a start with one centre in each group?
B4. Six points in 2D: (0, 0), (0, 2), (1, 1), (6, 0), (6, 2), (7, 1), K = 2, start \mathbf m_1 = (0, 0), \mathbf m_2 = (1, 1). Run k-means to convergence and give J after each assign step.
B5. Predict, with a sketch, what k-means with K = 2 does with (a) two long parallel cigar-shaped groups, close together; (b) a large, widely spread group of 120 points next to a tight group of 30 points; (c) two groups that differ only in y, when y is measured in units 10 times smaller (so the numbers in y are 10 times larger).
B6. For the points of B2 the smallest possible J for K = 1, \dots, 6 is 101.5, 26.5, 1.5, 1.0, 0.5, 0. (a) Why can the best J never increase with K? (b) Draw J against K. Which K would you choose, and why?
B1. (a)
| step | groups | J | centres after update |
|---|---|---|---|
| 1 | \{1\}, \{2, 4, 7, 9, 10\} | 0 + 0 + 4 + 25 + 49 + 64 = 142 | (1, 6.4) |
| 2 | \{1, 2\}, \{4, 7, 9, 10\} | 26.84 | (1.5, 7.5) |
| 3 | \{1, 2, 4\}, \{7, 9, 10\} | 15.5 | (2.33, 8.67) |
| 4 | unchanged | 9.33 | stop |
- Halfway between the centres: (2.33 + 8.67)/2 = 5.5.
- Assign \{1, 2, 4\}, \{7, 9, 10\} at once; update to (2.33, 8.67): the same answer, after one iteration.
B2. (a) Distances from 5: to 1 is 4, to 8 is 3, so 5 goes to 8, and so do 6, 10, 11. Groups \{0\}, \{1\}, \{5, 6, 10, 11\}; the update gives 0, 1 and (5 + 6 + 10 + 11)/4 = 8: unchanged. J = 0 + 0 + 9 + 4 + 4 + 9 = 26. (b) 6 \times 0.5^2 = 1.5. (c) To reach (b), the centre at 1 would have to move to 5.5 and the centre at 0 to 0.5; but the centre at 1 owns only the point 1, so its mean is 1; and 5 is closer to 8 than to 1. Every single step keeps the configuration.
B3. (a) D^2 = 0, 1, 25, 36, 100, 121, sum 283. Probabilities 0, 0.004, 0.088, 0.127, 0.353, 0.428; for 10 or 11: 221/283 = 0.78. (b) Now D^2 = \min(distance to 0, distance to 10)^2 = 0, 1, 25, 16, 0, 1, sum 43. P(5 \text{ or } 6) = 41/43 = 0.95. Working through the other second centres in the same way (11: 50/52; 5: 61/63; 6: 41/43; 1: always a bad start, since the pair \{0, 1\} already holds two centres) and weighting by their probabilities from (a) gives 0.95 for a start with one centre in each pair. Random points as centres are much worse: of the \binom{6}{3} = 20 triples only 2^3 = 8 have one point in each pair, probability 0.4 (some bad starts still recover when k-means runs).
B4. Assign 1: (0, 0) to \mathbf m_1, the other five to \mathbf m_2: J = 0 + 2 + 0 + 26 + 26 + 36 = 90. Update: \mathbf m_1 = (0, 0), \mathbf m_2 = (4, 1.2). Assign 2: \{(0,0), (0,2), (1,1)\} and \{(6,0), (6,2), (7,1)\}, J = 25.12. Update: \mathbf m_1 = (0.33, 1), \mathbf m_2 = (6.33, 1). Assign 3: unchanged, J = 5.33. Converged.
B5. (a) It cuts across both cigars: a straight boundary through their middle, one centre near each end. Halving the length of a long group lowers J more than separating two close parallel groups. (b) The boundary is the bisector between the two centres, halfway between them. The spread-out group has points beyond that line: they are given to the small group, which ends up too big (the demo: 108 and 42 instead of 120 and 30). (c) With y numbers 10 times larger, differences in y dominate the squared distances (by a factor 100): the groups that differ in y are found easily. In the opposite case (y numbers 10 times smaller), y is ignored and k-means splits along x, even if that means nothing. Units are a choice; k-means takes them literally.
B6. (a) With one more centre you can always keep the old solution and put the new centre on one of the points: J cannot go up, and usually goes down. (b) J drops from 101.5 to 26.5 to 1.5, then hardly changes (1.0, 0.5, 0). The elbow is at K = 3: the three pairs. Beyond that, every extra centre only splits a pair.
Math questions
B7. (math) Show that for a fixed set of points \mathbf x_1, \dots, \mathbf x_n the sum \sum_i \lVert\mathbf x_i - \mathbf m\rVert^2 is smallest for \mathbf m = \bar{\mathbf x}, the mean. Show also that \sum_i \lVert\mathbf x_i - \mathbf m\rVert^2 = \sum_i\lVert\mathbf x_i - \bar{\mathbf x}\rVert^2 + n\lVert\mathbf m - \bar{\mathbf x}\rVert^2.
B8. (math) Show that the set of points equally far from \mathbf m_1 and \mathbf m_2 is the hyperplane through (\mathbf m_1 + \mathbf m_2)/2 with normal \mathbf m_2 - \mathbf m_1.
B9. (math) Prove that the assign step and the update step each cannot increase J, and conclude that k-means terminates after finitely many iterations.
B10. (math) Multiply feature 2 of every point by s > 0. Is the k-means result (the groups) the same for every s? Give a two-point-per-group example in 2D where the answer changes between s = 1 and s = 10.
B7. f(\mathbf m) = \sum_i\lVert\mathbf x_i - \mathbf m\rVert^2 has gradient -2\sum_i(\mathbf x_i - \mathbf m), zero at \mathbf m = \frac1n\sum_i\mathbf x_i; f is a convex quadratic (Hessian 2nI), so this is the minimum. For the identity, write \mathbf x_i - \mathbf m = (\mathbf x_i - \bar{\mathbf x}) + (\bar{\mathbf x} - \mathbf m) and expand: the cross term 2(\bar{\mathbf x} - \mathbf m)^\top\sum_i(\mathbf x_i - \bar{\mathbf x}) is zero because the deviations from the mean sum to zero.
B8. \lVert\mathbf x - \mathbf m_1\rVert^2 = \lVert\mathbf x - \mathbf m_2\rVert^2 \iff 2\mathbf x^\top(\mathbf m_2 - \mathbf m_1) = \lVert\mathbf m_2\rVert^2 - \lVert\mathbf m_1\rVert^2. This is a hyperplane with normal \mathbf m_2 - \mathbf m_1. Inserting \mathbf x = (\mathbf m_1 + \mathbf m_2)/2: (\mathbf m_1 + \mathbf m_2)^\top(\mathbf m_2 - \mathbf m_1) = \lVert\mathbf m_2\rVert^2 - \lVert\mathbf m_1\rVert^2, true.
B9. Assign: J = \sum_i \lVert\mathbf x_i - \mathbf m_{c(i)}\rVert^2, and each term is replaced by \min_k\lVert\mathbf x_i - \mathbf m_k\rVert^2 \le the old term. Update: J = \sum_k \sum_{i \in G_k}\lVert\mathbf x_i - \mathbf m_k\rVert^2, and by B7 each inner sum is smallest at the group mean. So J is non-increasing. If an assign step changes some c(i) (with ties broken consistently, only when the new centre is strictly nearer), J decreases strictly. J after the update depends only on the partition, and there are at most K^n partitions; a strictly decreasing sequence cannot revisit one, so the assignments stop changing after finitely many iterations.
B10. No. Distances become \sqrt{(\Delta x_1)^2 + s^2(\Delta x_2)^2}, so the groups depend on s. Example: points (0, 0), (0, 1), (3, 0), (3, 1), K = 2. At s = 1: split by x_1, \{(0,0), (0,1)\} and \{(3,0),(3,1)\} with J = 4 \times 0.25 = 1, while the split by x_2 gives J = 4 \times 2.25 = 9. At s = 10 the second coordinates are 0 and 10: the split by x_2 has J = 9 and the split by x_1 has J = 4 \times 25 = 100, so the best groups are now \{(0,0),(3,0)\} and \{(0,1),(3,1)\}.
Explore
The demo shows points (grey until assigned, then coloured by their group) and the centres as large crossed circles, with the Voronoi cell of each centre shaded. assign colours every point by its nearest centre; update moves every centre to the mean of its points (the dashed trail shows where it came from); step does both; run repeats until nothing changes. The plot shows J after every assign step; 100 restarts runs k-means from 100 different starts and draws a histogram of the final J. Click to add points, drag points or centres, choose the start (random points, k-means++, or by hand), K, and a stretch of the y axis.
E1. Preset by hand (1D). Press assign and update alternately. Compare the centres and J with your table in B1. Then drag the two centres to 4 and 7 (B1c) and run again.
E2. Preset three blobs (k-means++). Press run. How many updates are needed, and what is the final J? Now choose random points and press 100 restarts. How many of the 100 runs reach the best J, and what do the others look like? Repeat with k-means++.
E3. Preset stuck: two centres in one group. Check B2: what is J, and does anything change when you press step? Press 100 restarts (random points). What fraction reaches J = 1.5? Then preset k-means++ avoids it: where are the three seeds?
E4. Preset elongated: cut across. Run. Describe the groups. Is k-means wrong, or is it doing what it was asked? (The true split into the two cigars has J = 5.51.)
E5. Preset big and small group. Run. Where is the boundary, compared with the gap between the groups? Count roughly how many points of the big group end up in the small one.
E6. Preset rescale the y axis (two horizontal bands). Run at y \times 1. Then drag the y-axis slider to 1.5 and run again. Explain the change with B5(c).
E1. Centres (1, 6.4), (1.5, 7.5), (2.33, 8.67); J = 142, 26.84, 15.50, 9.33, as in B1. From 4 and 7 the first assignment is already final and the run ends at the same centres.
E2. Two updates: J goes 3.478 → 1.814 → 1.811 (in the units of the unit square). With random points as starts, 94 of 100 runs reach J = 1.811; the other 6 stop between 7.6 and 8.4, with two centres in one blob and one centre between the other two blobs. With k-means++: 99 of 100.
E3. J = 26 and step changes nothing (B2). With random starts, 80 of 100 runs reach 1.5 and 20 stop at 26. The k-means++ seeds land at 10, 0 and 5, one per pair, and one update gives J = 1.5.
E4. Each group gets one end of both cigars: the boundary is a straight line across them, and only 125 of the 160 points are grouped as in the two cigars. The final J is 3.08, lower than 5.51 for the true split. k-means did what it was asked: the true groups simply do not minimise J. A model with elongated groups is needed (units 2–3).
E5. The boundary is halfway between the two centres, which is inside the spread of the big group, not in the gap. The groups come out as 108 and 42 points instead of 120 and 30: about 12 points of the big group are given to the small one.
E6. At y \times 1 k-means splits the bands into a left and a right half (73 of 140 points agree with the bands, i.e. chance level): the bands are long in x, and cutting them across lowers J most. At y \times 1.5 the vertical gap between the bands counts 2.25 times more in the squared distances, and k-means separates the two bands (all 140 points). Nothing in the data changed, only the units.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in gmm/src/kmeans/exercise.rs. A point is a list of numbers (one for grey values, two for the 2D examples).
C1. assign(points, centres): every point to its nearest centre, and J = \sum_i \lVert\mathbf x_i - \mathbf m_{c(i)}\rVert^2. The check is the first step of B1.
C2. update(points, groups, centres): every centre to the mean of its points; a centre with no points stays where it is.
C3. kmeans(points, start, max_iterations): alternate C1 and C2 until no point changes its group, and record J after every assign step:
centres = start; groups = none
repeat:
new groups, J = assign(points, centres); record J
if new groups = groups: stop
groups = new groups
centres = update(points, groups, centres)
The checks are your tables of B1 and B4 (J = 142, 26.84, 15.5, 9.33 and 90, 25.12, 5.33) and the stuck start of B2 (J = 26).
C4. kmeanspp_probabilities(points, chosen) and kmeanspp(points, k, rng): k-means++ seeding.
centres = [ a point chosen at random ]
while fewer than k centres:
D²(x) = squared distance of x to its nearest centre, for every point
choose the next centre at random, point x with probability D²(x) / Σ D²
The checks are your probabilities of B3, and 100 seeded runs on the points of B2, nearly all of which must reach J = 1.5.
Then cargo run -p gmm -- kmeans and open the pictures in out/kmeans/.
C5. The program runs k-means with K = 2 on the grey values of the course micrograph (on the scale 0 to 255), starting from 0 and 255. Compare the centres and the boundary with the isodata threshold of the lecture. Then look at cell-k3.png and cell-k4.png (each group a grey level, dark to bright).
C6. On the points of B2, how many of 100 starts from random points reach J = 1.5, and how many of 100 k-means++ starts? Compare with B3(b).
C7. Two long parallel groups (long-groups.png, the background coloured by the nearest centre, crosses at the centres). How many of the 160 points does k-means group as in the truth? Compare its J with the J of the true groups. What changes when the program multiplies x_2 by 3 (long-groups-x2-times-3.png)? Compare with B5(a) and (c).
C8. For four groups the program prints the best J for K = 1, \dots, 7. Where is the elbow?
The model solution is gmm/src/kmeans/solution.rs in the download.
C5. Centres 111.5 and 214.4, boundary 163.0, after 7 assign steps: the isodata result of the lecture (means 112 and 214, threshold 163). With K = 3 the centres are 88, 152 and 223, with K = 4 79, 133, 189 and 234: each extra group splits the grey range further, as multi-level thresholds; the label pictures are speckled, because k-means on grey values ignores the neighbours.
C6. 87 of 100 random starts and 99 of 100 k-means++ starts reach 1.5. As in B3(b), k-means++ almost always seeds one centre in each pair; random points often put two centres in the same pair, and then k-means may get stuck as in B2 (some such starts still recover).
C7. It agrees for only 80 of 160 points, chance level: it cuts both groups across, into a left and a right half (the boundary is vertical in the picture). Its J is 103.5, while the true groups have J = 200.6: by its own measure k-means is right, the objective does not suit elongated groups (B5(a)). With x_2 multiplied by 3 the gap between the groups counts 9 times more in the squared distances, and k-means finds the two groups (160 of 160, B5(c)).
C8. The best J is 1075, 571, 323, 77, 67, 60, 53: it falls steeply up to K = 4 and only slowly after it. The elbow is at K = 4, the number of groups.
Where this leads
k-means draws straight boundaries between round groups of equal size, and every point belongs to exactly one group. The next unit replaces each group by a Gaussian with its own shape (covariance), size and weight, and gives every point a probability of belonging to each group. Unit 3 fits that model with EM, which turns out to be a “soft” k-means. SLIC superpixels (graph-based segmentation day) are k-means with the pixel position as two extra features.