Ch.26: Algorithms: How K-Means Clustering Finds Groups

Outline

Transcript

0:00 K-means clustering divides unlabeled points into groups by assigning them to centers, then averaging each group. It can choose a few brightness values to represent an image. We'll run that loop and see why a different start can stop at a worse answer. My instinct is to split these eight dots left from right. How could that picture go wrong? That split looks obvious. Each dot has 2 coordinates: horizontal position, then height. Suppose we ask for two groups. The program starts with two centers and compares distances.

0:30 The k means that requested group count. Open rings represent centers; the eight solid dots are our input data. First put A on point one, at 0, 0, and B on point three, at two, 0. Both centers begin on the left. Huh. Both centers sit on one side of that big empty gap. Our first assignment has to use those starting positions. Keep those two rings fixed for this step. Each dot goes to the nearer of its current rings. Let's check point four before we assign the rest. With those starting rings fixed, take a point at 2, 6: point four.

1:05 Compare its horizontal and vertical differences from each center, square them, then add. For A, that's two squared plus 6 squared: 40. For B, the horizontal difference is 0, so its score is 36. B wins. Those are squared distances; taking square roots would give ordinary straight-line distances, but wouldn't change which center is nearer. And four belongs to B even though B doesn't look like the middle of a sensible group yet. We're comparing against the rings we actually have. Apply that comparison to every dot.

1:37 Points one and two join A. Points three through eight join B. Each point receives one group label. Google's clustering guide documents the cycle; we've linked the sources in the description. Six points against two. That isn't the split I had in mind. Are we stuck with those labels now? No. Assignment lasts until the next pass. Those six points will first pull B to a new position, and that movement can change who belongs there. Good. I was already arguing with that first guess. Let's give it a chance to move the rings.

2:08 We can locate a representative from each group's members while keeping the dots fixed. Now use those memberships to update A. For example, its points share horizontal coordinate 0, with heights 0 and 6. Their middle is 0, 3. Yes. Average each coordinate separately. A's calculation stays on the display. B has six members. Their horizontal coordinates sum to 48. Divide by the number of members and B moves to eight. The heights add to 18. Divide by 6 to get three, so B's updated position is 8, 3. Look from point four toward those updated rings.

2:45 B's in the gap now. A center represents its group; it doesn't have to be one of the observations. That coordinate-wise average is the mean. You'll also hear this representative point called a centroid. I'm tempted to say we've finished: we've assigned the points and found their centers. What tells us to run another pass? Assignment used the old positions. We moved B from 2, 0 to 8, 3. A point can now be closer to a different center. So the new means can invalidate the labels that produced them. That leaves point four with a fresh decision to make.

3:19 With the rings moved, point four is two across and three up from A. Squaring those gaps gives 4 plus 9: 13. B is at 8, 3. Point four lies 6 left and three up from that ring. Squaring the gaps gives a total of 45. 13 beats 45, so point four moves to A. Point three changes sides too: it has the same horizontal position and sits three below the rings. Hold on. The points haven't moved at all. Their membership changed because we moved the representatives. That's the repeat doing useful work. Yeah. Now A owns points one through four, and B owns five through eight.

3:58 Update the averages again. A's horizontal average is 1; B's is 11. Both groups still average height three. The rings finish at 1, 3 and 11, 3, in the middle of the left and right rectangles. Run assignment once more. Every point keeps its group. Averaging those unchanged memberships produces those same centers. Now the two operations agree with each other. Neither asks the other to change anything, so this example can stop. Yes. The loop has settled. That tells us something precise about these assignments and centers, but it hasn't compared them with every possible grouping.

4:32 Before we test that limit, I'd like a better definition of better. We keep moving centers, but what number says the movement helped? Add the squared distance from each dot to its assigned center. So now we can compare the states with 1 total instead of judging their appearance. Now calculate that total from the finished groups. Consider a point near the bottom left: point one. Its horizontal gap is one, its vertical gap three. Their squares contribute 10. All eight points contribute 10 here, giving 80.

5:03 Lower means the points lie closer to their assigned representatives under this particular squared-distance score. Our actual trace started at 472. The first averages lowered it to 184. Reassignment made it 120; the second averages reached 80. Assignment picks the cheapest center already there. Why should the average be the cheapest place to put a center? Let's check the left group. Hold height at three. Its horizontal coordinates are 0, 0, 2, 2. At their mean of one, all four horizontal gaps square to 1: total four. Move the ring left to 0.

5:38 Two gaps disappear, but the other two become two each. Squaring those gives eight. I helped two points and still made the total worse. Yeah. Moving right to two gives eight as well. Now let the ring slide by any amount. The display calls that movement t. Expand the two squared gaps. One adds twice the shift; the other subtracts it. Those parts cancel. Ah, leaving one shift-squared term per point. Four points give four copies, so either direction adds that extra error. Does the same arithmetic average work if we choose a different distance rule?

6:13 Not automatically. That guarantee belongs to the squared coordinate differences we're adding. Changing the rule can change which representative minimizes it. Okay, that explains why the two moves fit together. Pick the cheapest labels for stationary centers, then find each group's average. That shared score can fall or stay put. Which makes every move explainable. But we haven't tried another start. Let's change the starting centers and see where these same rules leave us. Now try A at point one and B at point two, with the rings above and below each other.

6:47 Okay, the bottom row goes to A and the top row to B. Each dot matches one ring's height exactly; the other is six away. Next average those groups. Both horizontal coordinates become six; the heights remain 0 and 6. The resulting centers are 6, 0 and 6, 6. Then another assignment keeps the bottom and top rows separate. Moving horizontally didn't erase the distance advantage each row has to its own ring. And averaging leaves those rings unchanged too. The loop stops with a cost of 208, compared with 80 for the left-right result.

7:21 Wait. I can follow every legal step and still finish with the worse grouping. Stopping only proves that these two operations have stopped changing their answer. Exactly. It improved from that starting state, but it only explored the assignments along that particular run. An engineer reviewing this could say, 'Just keep the best of several starts.' What guarantee would we actually have? It reduces the risk of a poor start without certifying the global best. We separately checked every nonempty way to divide these eight points into two groups; 80 really is the best score for this input.

7:56 That exhaustive check is our small-example oracle, a separate way to verify the answer. It's not a step K-means performed behind the scenes. Right. A real implementation can use better starting choices and repeated runs, while still needing the caller to understand what its result guarantees. Here's the loop we've just run. Pick initial centers, assign points, calculate updated means, and repeat until the new centers equal the old ones. This is a toy core with exact arithmetic and nonempty groups.

8:27 A real library also handles groups with no points, stops when centers move less than a chosen amount, and limits the number of passes. Eight points and two centers mean 16 distance comparisons in one assignment. What if we double the points and keep two centers? 32 comparisons. Computing each distance uses all its coordinates, giving points times centers times dimensions per assignment pass. A whole run repeats that work for its passes. Those comparisons depend on the coordinates we chose. Suppose an engineer measures 1 coordinate in meters.

9:00 Test an observation with zero in both positions. Use center A at 1, 0. Put B at 0, two. Its squared distances are 1 and 4, so it chooses A. Now express only that horizontal coordinate in millimeters. A's horizontal coordinate becomes 1,000. The squared distances become one million and four; that same observation chooses B. A units cleanup could look like a new discovery. I don't trust a score until I understand those coordinates. Take a separate group-mean example. Keep those four left-group members together and add a 5th at 21, three.

9:36 Their average moves from one, three to 5, 3. In our main eight-dot run, we picked two as the group count, and both stable pictures obeyed. Which grouping would actually be useful for the task? We'd need to know what those coordinates represent and why we're grouping them. The score measures closeness in that representation; it can't tell us whether that's the similarity our task needs. The same loop can choose representative image brightness values. Suppose an image engineer has four pixels at 20, 30, 200 and 210.

10:07 Choose two representatives, initially 20 and 200. The two dark pixels join 20; the two bright ones join 200. Their averages are 25 and 205. On the next assignment, neither group changes. And the next averages stay there too. So the engineer can represent those four pixels with the 2 values we've just calculated. That's the same assign-and-average loop on one axis. It gives us fewer brightness values, but it doesn't by itself prove the saved image file will be smaller. Right. Lloyd's paper paired two choices: which representative signal values to keep, and which inputs map to each, while controlling squared error.

10:48 The Python library scikit-learn has an example that uses K-means on shades of gray. Our four pixels are a synthetic illustration, not a measured photo result. Both examples used the same loop. Back on our eight-dot picture, the score fell to 80, while another start settled at 208. That's the mistake I want to remember: treating an unchanged answer as proof that no better answer exists. With fixed centers, improve the labels. With fixed labels, improve the centers. Repeating those moves makes K-means understandable, including the limit it can't remove.

11:21 We can inspect the starting positions, distances and group count before trusting the result. Thanks for listening to Learning Podcasts.