ECE571 / Week 8 · Unsupervised learning

Week 8 · Unsupervised learning

K-means clustering

No labels this time. Given only points, k-means finds k groups by alternating two easy steps: send every point to its nearest center, then move every center to the mean of its points. Most of the craft is in where you start and how you pick k.

~30 min read 10 practice questions + 2 problems Reading: Géron Ch. 9, "Clustering" and "K-Means"
The big picture

Every model so far was supervised: each training point came with a label. This week the labels are gone, and the goal is to discover structure in the data itself. Clustering groups points so that points in the same group are close and points in different groups are far apart. k-means is the classic way to do it: you choose the number of clusters , and it finds centers by alternating "assign each point to its nearest center" and "move each center to the mean of its points". It is fast and simple, and the professor's advice is to try it first on any clustering problem. Its weak spots are that the answer depends on the starting centers, that you have to choose , and that it assumes round, similar-sized clusters.

After this you can
Section 1

Unsupervised learning and clustering

Lecture 00:00–22:04Slides 1–17Géron Ch. 9, "Clustering"

In supervised learning, each training example is a pair (features, label), and the model learns to predict the label. In unsupervised learning you get the features only. There is nothing to predict; the task is to understand how the data is laid out in feature space. The lecture names the two main families: clustering (this week: k-means) and dimensionality reduction (week 10: PCA). Between the two extremes sits semi-supervised learning, where only some points have labels.

With labels Without labels
Same 60 points; only the left plot has labels. A classifier needs the markers on the left. A clustering algorithm sees only the right plot and has to find the three groups on its own.

The pipeline on slide 7: take raw data (say, images), extract a feature vector for each item, then group the vectors into clusters. The clusters you get can only be as good as the features: if two kinds of objects look the same in feature space, no clustering algorithm can separate them.

Uses (slides 6, 12–13 and Géron): customer segmentation for marketing, image compression and color segmentation, grouping genes or motifs in bioinformatics, land-use maps from satellite data, grouping insurance policy holders, and as a preprocessing step for other models. The professor's example of that last use is the computer-vision bag of visual words (07:59): cluster small image-patch features, treat each cluster center as a "visual word", and describe each image by a histogram of how often each word occurs. That histogram then becomes the input to a classifier.

What makes a clustering good?

Slide 14 gives the two criteria, and the professor asked you to remember them:

  • High intra-cluster similarity: each cluster is compact; its points are close to one another.
  • Low inter-cluster similarity: different clusters are far apart.

Beyond that, quality is application-dependent and "ultimately subjective" (slide 14): the same data can be grouped several sensible ways. As an aside, the professor pointed out that LDA (linear discriminant analysis, a supervised linear classifier you can look up) uses exactly these two quantities to find a separating direction. A clustering algorithm has the same goal without the labels.

Flagged in lecture · 14:48

"High intra-class similarity, low inter-class similarity. Remember this." Compact clusters that sit far from each other: that is the definition of a good clustering, and k-means's objective (Section 3) measures the first half of it directly.

Heads up: slide 12

Slide 12 says "clustering is unsupervised classification". The professor disagrees (07:21: "I don't like the term"), and so does Géron. A classifier outputs a named class (cat, bicycle). A clustering outputs only cluster numbers (0, 1, 2), and the numbers carry no meaning. You can turn clusters into a classifier only if someone tells you what each cluster is, which is a form of labeling.

What a clustering algorithm should handle

Slide 15 lists the requirements. The professor stressed three: scalability (millions of points), noise and outliers (real data is never clean), and above all high dimensionality. Recall the curse of dimensionality from week 4: the data needed to cover a space grows exponentially with its dimension, so even millions of 2048-dimensional image features cover that space only thinly. "How can your algorithm deal with a large-scale data set in a high-dimensional space? This is the fundamental challenge" (20:03). The rest: mixed attribute types, clusters of arbitrary shape, needing little domain knowledge to set parameters, not depending on the order of the input, respecting user constraints, and producing clusters a person can interpret.

Families of clustering algorithms

Family (slide 16)IdeaExample
Partitioningsplit the data into k disjoint groups that optimize a criterionk-means, k-medoids
Hierarchicalbuild a tree of clusters by repeatedly merging (or splitting) groupssingle linkage (SSBD §22.1)
Model-basedassume each cluster follows a distribution and fit itGaussian mixture models (week 9)
Density-baseda cluster is a dense region separated by sparse spaceDBSCAN (Géron Ch. 9)

A partitioning algorithm (slide 17) is given k and must find the partition into k clusters that optimizes a criterion. Trying every partition would find the global optimum, but the number of partitions explodes, so in practice you use heuristics. Two classics: k-means represents each cluster by its center (the mean, which usually isn't a data point), and k-medoids represents each cluster by one of its actual points (the medoid).

A colleague clusters customer records into 5 groups and calls cluster 3 "the bargain hunters". Where did that name come from?

Not from the algorithm. k-means only outputs "cluster 3". A person looked at the records in that cluster (or at its centroid) and interpreted it. That interpretation step is why slide 15 lists "interpretability" as a requirement, and why the professor objects to calling clustering "classification".

Section 2

The k-means algorithm

Lecture 22:04–28:36Slides 18–30, 33Géron Ch. 9, "The K-Means algorithm"; Bishop §9.1

Imagine you were handed the cluster centers. Labeling the points would be easy: send each one to its closest center. Now imagine you were handed the labels instead. Finding the centers would be easy too: average the points with each label. k-means has neither, so it guesses the centers and then alternates these two easy steps (Géron's framing).

Input: the number of clusters and unlabeled points (slide 29: no bias feature here).

  1. Initialize: pick starting centroids at random. (Section 4 explains how.)
  2. Assignment step: for each point , set to the index of the centroid closest to .
  3. Update step: for each cluster , move to the mean of the points assigned to it.
  4. Repeat steps 2–3 until the assignments stop changing (or a maximum number of iterations is reached).

the cluster index (1 to ) currently assigned to point
the centroid (center) of cluster , a point in
the set of points assigned to cluster ; is how many there are
number of points, number of features, number of clusters (the slides' notation)

The professor's way to think about the assignment: it's a pseudo-label (25:32). Once every point has a pseudo-label, the update step is just "compute each class's mean", as if the labels were real. Then the labels are recomputed from the new means.

Each assignment step splits the space into Voronoi cells around the centroids, exactly like the 1-NN cells of week 4, except that the "training points" are now the centroids. With the boundary is the perpendicular bisector of the two centroids. This is the picture the professor told you to remember (26:59). Slides 19–28 animate it on 30 points; here is the same process on 6 points you can check by hand.

Iteration 1 A B C D E F J = 81 → 30.5 Iteration 2 J = 23.75 → 14 Iteration 3 J = 13 → 9.5 Converged J = 9.5, no change
Assign, move, repeat: the boundary swings until nothing changes. Crosses are the current centroids, shading shows which centroid is nearer (the Voronoi cells), and the dashed arrow shows where each centroid moves in the update step (ringed: its new position). Iteration 2's new centroids land exactly on E and B; iteration 3's blue centroid sits on E. After three updates the assignment repeats and k-means stops. The labels under each panel give J at the assignment and after the update.
Worked example: three iterations by hand

Points: A(1,1), B(2,2), C(2,4), D(3,3), E(4,5), F(6,6). . Start (deliberately badly, as in slide 21) with , . The table lists squared distances / ; the smaller one (bold) wins.

Iterationμ₁ / μ₂ usedABCDEFJ after assignNew μ₁ / μ₂J after update
1(0, 5) / (5, 1)17 / 1613 / 105 / 1813 / 816 / 1737 / 2681(3, 4.5) / (3, 3)30.5
2(3, 4.5) / (3, 3)16.25 / 87.25 / 21.25 / 22.25 / 01.25 / 511.25 / 1823.75(4, 5) / (2, 2)14
3(4, 5) / (2, 2)25 / 213 / 05 / 45 / 20 / 135 / 3213(5, 5.5) / (2, 2.5)9.5
4(5, 5.5) / (2, 2.5)36.25 / 3.2521.25 / 0.2511.25 / 2.2510.25 / 1.251.25 / 10.251.25 / 28.259.5same: stop9.5
  1. Iteration 1. C and E are nearer ; A, B, D, F are nearer . New means: and .
  2. Iteration 2. F switches to cluster 1 (11.25 < 18). Cluster 1 = {C, E, F}, mean ; cluster 2 = {A, B, D}, mean .
  3. Iteration 3. C switches to cluster 2 (4 < 5). Cluster 1 = {E, F}, mean ; cluster 2 = {A, B, C, D}, mean .
  4. Iteration 4. Every point keeps its cluster, so the centroids don't move: converged with . Checking all 31 ways to split six points into two groups confirms this is the best possible.

Two details the slides skip. Ties: if a point is equally close to two centroids, pick one by a fixed rule (say, the lower index) so the algorithm can't flip back and forth. Empty clusters: if no point is assigned to some centroid, its mean is undefined. Common fixes are to drop that cluster or to re-seed it at the point farthest from its centroid. That's one reason slide 36 insists on , and why starting centroids are usually taken from the data.

With centroids and , which cluster gets the point ? Then the cluster {(0,0), (2,0), (4,3)}: where does its centroid move?

Squared distances: to it is ; to it is . So joins cluster 1, though only narrowly.

The centroid moves to the mean, .

Section 3

The objective and why it converges

Lecture 29:46–34:26Slides 32, 44Bishop §9.1; SSBD §22.2

The two steps aren't arbitrary. Both are exact minimizations of one cost function, called the distortion (slide 32), the within-cluster SSE (slide 44), or the inertia (Géron, scikit-learn):

the centroid of the cluster that point is assigned to
squared Euclidean distance

In words: the average squared distance from each point to its own centroid. Small means compact clusters, which is the "high intra-cluster similarity" criterion from Section 1.

Cross-check with the textbook: three versions of "J"

Slide 32 divides by (a mean). Slide 44 and Bishop (Eq. 9.1) use the plain sum, . Géron describes inertia in words as the "mean squared distance", but scikit-learn's inertia_ (and the numbers Géron prints) is the sum; we checked this directly. The versions differ only by the constant factor , so they have the same minimizer and k-means does the same thing with any of them. Just be consistent when comparing numbers. The worked examples in this guide use the sum.

Alternating optimization

has two kinds of unknowns: the assignments and the centroids . Minimizing over both at once is hard (SSBD §22.2: finding the exact optimum is NP-hard in general). But fixing one kind makes the other easy. That is alternating optimization, and it is exactly k-means:

  • Fix , minimize over : each term involves only point 's own choice, so pick the nearest centroid for each point. That's the assignment step.
  • Fix , minimize over : is a convex quadratic in each . Set the gradient to zero:

The mean is the point that minimizes the total squared distance to a set of points. That's the update step, and the reason the algorithm is called k-means.

Why J never increases

Each step solves its own subproblem exactly, so it can't do worse than the solution it started from:

  • Assignment step: each point either keeps its centroid or switches to a strictly closer one. Each term stays the same or shrinks.
  • Update step: the mean is the minimizer for its cluster, so moving a centroid there can't raise that cluster's sum.

So goes down or stays put at every half-step. And since points can be split into groups in only finitely many ways, and no partition can come back once has dropped below its value, the algorithm must stop after a finite number of iterations (Géron: "it will not oscillate forever"). Usually it takes only a few.

0 20 40 60 80 A1 81 U1 30.5 A2 23.75 U2 14 A3 13 U3 9.5 A4 9.5 after assign step after update step step (A = assign, U = update; number = iteration)
J from the worked example after every half-step: it only goes down. Both kinds of step lower it: the update step (squares) by moving centroids to means, the assignment step (circles) by re-sorting points. The flat last segment is convergence. This matches Bishop's Fig. 9.2.
Heads up: lecture 31:51–32:21

The lecture says J is "not convex" overall but "given C or given μ, the function is convex", calling the problem biconvex. The first and the μ half are right: for fixed assignments, is a convex quadratic in the centroids. The other half is loose. The assignments are discrete labels, not continuous variables, so convexity in doesn't apply. What's true is that for fixed centroids the assignment problem is solved exactly by "nearest centroid". The conclusion is unchanged: each step is an exact minimization, J never increases, and the algorithm can still stop at a local minimum, which is the subject of the next section.

Heads up: slide 44, "like KNN, we use squared Euclidean distance"

k-NN (week 4) uses plain Euclidean distance. For the assignment it makes no difference, because squaring doesn't change which centroid is nearest. For the objective the square matters: the mean minimizes the sum of squared distances. If you minimized the sum of plain distances, the best center would be the geometric median instead (the idea behind SSBD's "k-median" objective), and the update step would no longer be "take the mean". Also note that slide 44 uses for the number of features, while slides 29–32 use for the number of points.

A cluster holds the 1-D points 1, 2 and 6. What is the best center under squared distance, and under plain distance?

Squared: the mean, . The cost is ; try 2 instead and you get .

Plain distance: the median, . The cost is , versus at the mean. k-means uses the squared version, so it uses the mean, which also makes it sensitive to outliers like the 6.

Section 4

Initialization and local minima

Lecture 34:32–37:34Slides 34–38Géron Ch. 9, "Centroid initialization methods"

"K-means is very sensitive to initialization" (34:46). Because is not convex, k-means can converge to a local minimum: a clustering that no single assign or update step can improve, but that is worse than the best one. Where you end up depends on where you start.

How to start. The slide 30 version places centroids at random points in space. If they land far from the data, a centroid can end up with no points or get stuck. Slide 36's better default: choose training examples at random and put the centroids on them. That guarantees the starting centroids lie on the data.

Worked example: a bad start gets stuck

Same six points as Section 2. Start at two data points, and .

  1. Assign. Squared distances to A / E: A 0 / 25, B 2 / 13, C 10 / 5, D 8 / 5, E 25 / 0, F 50 / 5. So {A, B} vs {C, D, E, F}, and .
  2. Update. and

    so .
  3. Assign again. The closest calls are C (6.5 vs 3.31) and D (4.5 vs 2.81), and both stay with . Nothing changes, so k-means stops at , worse than the 9.5 found in Section 2.

This isn't a rare fluke. Of the 15 possible pairs of data points as starting centroids, 5 (AB, AC, AD, AE, BD) end in this local minimum. That's one start in three.

Global minimum J = 88.5 Local minimum J = 410.3
Same data, same algorithm, different starts: 88.5 vs 410.3. On the right, two centroids share the lower-left blob and the third is stranded between the other two blobs. Every point is already at its nearest centroid and every centroid is at its cluster's mean, so neither step changes anything. This is slide 37's picture. On these 60 points, starting from 3 random data points reached the good answer in 899 of 1,000 runs.

The fix: restart and keep the best

Slide 38: run k-means many times (the slide says 100) from different random starts, compute for each result, and keep the clustering with the lowest . Comparing is fair here because every run uses the same data and the same . scikit-learn does this automatically: n_init sets the number of runs and the lowest-inertia run is kept (Géron).

Common trap

"Pick the lowest J" is right for choosing among restarts with the same K. It is wrong for choosing K itself, because J always gets smaller as K grows (Section 6). Don't mix up the two uses.

Two runs of k-means with K = 4 on the same data stop at J = 312 and J = 287. Which do you keep, and is 287 guaranteed to be the global minimum?

Keep the J = 287 run. It is the better of the two local minima found, but nothing guarantees it is the global one. More restarts (or a better start such as k-means++) only make a good answer more likely.

Section 5

k-means++: spread out the starting centers

Lecture 38:52–46:26Slides 42, 45–47Géron Ch. 9, "Centroid initialization methods"

The local minimum above happened because both starting centroids landed in the same natural group. k-means++ (Arthur & Vassilvitskii, 2007) makes that unlikely by choosing starting centers that tend to be far apart. Only the initialization changes; afterwards it is ordinary k-means.

  1. Choose the first center uniformly at random from the data points.
  2. For every data point , compute : its distance to the nearest center chosen so far.
  3. Choose the next center at random from the data points, picking with probability proportional to :

Points already chosen have , so they can't be picked again. Repeat steps 2–3 until there are centers, then run k-means from them.

Worked example: k-means++ from B

Six points as before, , and suppose the first center drawn is B(2,2).

PointABCDEFSum
to B2042133253
P(next center)0.03800.0750.0380.2450.6041
k-means then ends at14.75–9.514.759.59.5

The far points E and F get 85% of the probability. The bad local minimum happens only if A or D is drawn: . With a uniform second pick it would be . (Averaged over all six possible first picks, the bad outcome drops from 33% for two uniformly random data points to 27% for k-means++; the gain is larger with more clusters. On the 60-point data in the figure above, k-means++ reached the best answer in 1,000 of 1,000 runs, versus 899 for uniformly random data points.) This is why scikit-learn uses k-means++ by default.

Heads up: lecture 42:00 vs 44:58, max or sample?

While working through slide 46, the professor first wrote that the next center is the point with the maximum , then corrected it at 44:58: taking the max is deterministic, whereas k-means++ uses a "probability sampler". The sampling version is the correct one (slides 46–47, Géron). Always taking the farthest point is a different method (farthest-first traversal). Its weakness is that the farthest point is often an outlier, so a lone noisy point would get its own center every time. Sampling in proportion to still strongly favors far points while making any single outlier unlikely to be chosen.

Heads up: slide 46, step 5

Slide 46 numbers the steps 1 (create the empty set M), 2 (choose the first center), 3 (compute distances), 4 (sample the next center), then says "Repeat steps 2 and 3". It should say steps 3 and 4: repeating step 2 would draw another uniformly random center, which defeats the point. Slide 47 numbers its steps differently, and there "Repeat Steps 2 and 3" is correct.

1-D points 0, 1, 2, 10, 11. The first k-means++ center is 0. What is the probability that the second center comes from {10, 11}?

values: 0, 1, 4, 100, 121, which sum to 226. So

Section 6

Choosing k

Lecture 37:34–38:52Slides 39–41Géron Ch. 9, "Finding the optimal number of clusters"

k-means needs as input, and "with no prior knowledge it's hard to define K" (37:37). Slide 40's example shows why: two clear columns of points could be 2 clusters, or 4 if each column has an upper and a lower half. Domain knowledge beats any formula (T-shirt sizes S/M/L is a decision about the business, not about the data). Without it, there are two standard tools.

The elbow method

Run k-means (with restarts) for and plot the final against . J always falls as K grows, because more centroids are always at least as close to every point. Look for the elbow: the K after which adding clusters stops buying much. On the 60 points from Section 1:

K12345678
Inertia J (sum)729.4351.988.575.865.655.249.740.7
Drop from K − 1–377.5263.412.610.210.45.49.1
Silhouette–0.5240.6960.5530.4060.3150.3240.363
Inertia J 0 200 400 600 800 1 2 3 4 5 6 7 8 k (clusters) Silhouette score 0.0 0.2 0.4 0.6 0.8 1 2 3 4 5 6 7 8 k (clusters)
Both tools point to K = 3. Left: inertia falls steeply up to K = 3, then flattens (the elbow, like slide 41's plot). Right: the silhouette score peaks at K = 3. These are the 60 points from Section 1, run with 10 restarts per K.
Heads up: lecture 38:33

The lecture says to "run the k-means algorithm with different K, plot J, see which one gives the lowest one, and pick that value". Read literally, that always picks the largest K you tried: J keeps falling, and with (every point its own centroid) J = 0. Slide 41 itself says "the larger K we choose, the smaller SSE". The rule is to pick the elbow (slide 41 picks K = 3), not the minimum. The lecture's other comment (38:08) is the right instinct: once the curve has flattened, those larger K values all fit about equally well, and choosing among them needs prior knowledge.

The silhouette score (Géron)

The elbow is often vague. Géron's more precise alternative scores each point by how much closer it is to its own cluster than to the next-nearest one:

the point's mean distance to the other points in its own cluster
its mean distance to the points of the nearest other cluster

: well inside its cluster. : on a boundary. : probably in the wrong cluster. The silhouette score is the mean of over all points; choose the K that maximizes it. It costs more to compute (it needs pairwise distances), but unlike J it does not automatically improve as K grows.

A point has mean distance 2 to its own cluster and 5 to the nearest other cluster. What is its silhouette coefficient? What if the numbers were swapped?

: comfortably in the right cluster.

Swapped (, ): . The point sits closer to another cluster than to its own, so it is probably misassigned.

Section 7

Limits, cost and variants

Lecture 28:36–29:46, 46:26–48:20Slides 31, 43, 45Géron Ch. 9, "Limits of K-Means", "Accelerated K-Means and mini-batch K-Means"

Slide 45 sums k-means up. Strengths: simple, iterative, and the user controls K. Weaknesses: very sensitive to the initial centroids, and hard to guess the right K. The deeper limitation is built into the objective. J measures squared distance to a single center, so k-means looks for round (spherical) clusters of similar size, and every boundary is a straight perpendicular bisector between two centroids. When the true groups look different, k-means still lowers J, but the result is the wrong grouping.

Elongated clusters cuts both bands in half Unequal sizes steals the big cluster’s edge
k-means minimizes J, not "find the obvious groups". Point colors and shapes show the true groups; the black line is the k-means boundary and the crosses are its centroids. Left: the true top/bottom split has J = 393.5, but cutting both bands into left and right halves has J = 140.9, so k-means prefers the wrong answer. Right: the boundary sits halfway between the centroids, so 4 points from the big cluster's edge go to the small one (k-means J = 115.4, versus 128.0 for the true split).
  • Elongated or oddly shaped clusters (left): use a Gaussian mixture model (week 9), which fits an ellipse per cluster, or a density-based method like DBSCAN.
  • Different sizes or densities (right): same remedies. Géron's ladybug example is the image version: with too few colors, the small red ladybug gets no cluster of its own.
  • Feature scale: as with k-NN, squared Euclidean distance lets large-unit features dominate. Standardize features first (Géron's tip; Bishop standardizes before running k-means too).
  • Outliers: the mean gets pulled toward outliers. k-medoids (slide 17) is more robust because its center must be an actual data point.
  • No natural clusters (slide 31, T-shirt sizing): height and weight form one continuous cloud. k-means still splits it into K pieces (here S/M/L). That can be useful, but the professor's point (28:36) is that no algorithm can discover clusters that aren't there.

Computational cost

Flagged in lecture · 46:44–47:27

"We haven't talked about the computational complexity for k-means, but you can understand this from the number of data points, number of clusters, and dimensionality of the features. You can try to do the calculation by yourself." And: "How to accelerate k-means? You can think about it as well." Here is the calculation.

  • Assignment step: points × centroids distances, each costing , so .
  • Update step: each point is added into one mean: .
  • Total: for iterations, linear in every factor. is usually small (Géron: k-means is "generally one of the fastest clustering algorithms", though pathological inputs can need very many iterations).

Compare k-NN: each query costs . k-means does comparable work for all points at once, but per iteration and against only centroids.

Speed-ups (the lecture's "think about it"):

  • Elkan's accelerated k-means: use the triangle inequality and keep upper and lower bounds on point-to-centroid distances, so most distance computations can be skipped. It's scikit-learn's default.
  • Mini-batch k-means (Sculley 2010): update the centroids from a small random batch at each step. It's typically 3–4× faster and works on data that doesn't fit in memory, at the price of a slightly higher J.
  • Tree structures (Bishop §9.1) and the hashing ideas from week 4 can speed up the nearest-centroid search when is large.
Heads up: slide 43 describes a different k-means

Slide 43 (shown for a moment at 39:04) lists the steps as: pick one unclassified sample, assign it to the nearest center, then "re-calculate the center of the class with the new sample". That is sequential (online) k-means (MacQueen 1967; Bishop Eq. 9.5): centers move after every single point, . The algorithm on slides 18 and 30 and in the worked examples is batch k-means (Lloyd's algorithm): assign all points, then recompute all means. Both aim at the same J but can give different results, and the online version depends on the order of the points (slide 15's "insensitivity to order" requirement). If an exam says "k-means", use the batch version.

k-means with K = 10 runs on 1,000,000 points with 50 features for 20 iterations. Roughly how many scalar operations does the assignment step perform in total?

(one subtraction, squaring and addition per feature, so times a small constant). That's linear in each factor: doubling the data doubles the work.

Section 8

k-means vs k-NN: don't mix them up

Week 4 vs this lectureSlide 44

Both have a "k", both use Euclidean distance, and both produce Voronoi-cell pictures. They solve different problems.

k-NN (week 4)k-means (this week)
Tasksupervised: classify or regressunsupervised: group unlabeled points
Needs labels?yesno
What k meansnumber of neighbors that votenumber of clusters (centroids)
Trainingnone ("lazy"): store the dataiterative: assign/update until convergence
What's keptall training points centroids
New pointfind its k nearest training points, voteassign it to the nearest centroid (a 1-NN against the centroids)
Voronoi cells aroundevery training point (for 1-NN)each centroid
Choose k byvalidation errorelbow, silhouette, domain knowledge

The one real connection: once k-means is trained, labeling a new point is 1-NN classification with the centroids as the stored "training set". That's how KMeans.predict works in scikit-learn.

Section 9

Cheat sheet

Good clusteringhigh intra-cluster similarity (compact), low inter-cluster similarity (far apart)
Assign
Update = mean of the points in cluster
Objective (slide 32 divides by ; same minimizer)
Convergenceeach step exactly minimizes J over its variables, so J never increases; finite partitions mean it stops; it may stop at a local minimum
InitializationK random training examples; many restarts, keep the lowest J (same K)
k-means++first center uniform; next center sampled with ; then normal k-means
Choose Kelbow of J vs K (never "lowest J": K = m gives 0); or maximize the silhouette
Cost; speed-ups: Elkan (triangle inequality), mini-batch
Fails onelongated or non-convex shapes, very different sizes or densities, unscaled features, outliers
Batch vs onlineLloyd: assign all, then update all; MacQueen/slide 43: update after each point
vs k-NNk-NN: supervised, k = neighbors; k-means: unsupervised, k = clusters
Section 10

Practice

Score: 0 / 0

Q1Which statement about k-means is true?

Q2Centroids are and . In the assignment step, the point goes to:

Q3A cluster contains (0,0), (2,0) and (4,3). Where does its centroid move in the update step?

Q4During batch k-means (Lloyd's algorithm), the objective J:

Q5You run k-means for K = 1, …, 10 and pick the K with the lowest J. What goes wrong?

Q6k-means++ has chosen one center. Three remaining points are at distances 1, 2 and 3 from it. What is the probability that the next center is the farthest point?

Q7You run k-means 50 times with K = 5 from different random starts. Which run should you keep?

Q8The data is two long, thin, parallel horizontal bands, one above the other. What does k-means with K = 2 typically do?

Q9Cost of one k-means iteration with m points, n features and K clusters?

Q10Slide 43 says: pick one sample, assign it to the nearest center, re-calculate that center, repeat. How does this differ from slides 18 and 30?

Problem 1: Run k-means by hand on the 1-D points 1, 2, 3, 8, 9, 13 with K = 2, starting from μ₁ = 1, μ₂ = 2. Give the assignments, centroids and J (sum of squared distances) at every step until convergence.

Iteration 1, assign. 1 is closest to μ₁ = 1; every other point is at least as close to μ₂ = 2. Clusters {1} and {2, 3, 8, 9, 13}. .

Update. μ₁ = 1, μ₂ = (2 + 3 + 8 + 9 + 13)/5 = 35/5 = 7. .

Iteration 2, assign. The boundary is the midpoint (1 + 7)/2 = 4, so the clusters become {1, 2, 3} and {8, 9, 13}. .

Update. μ₁ = 2, μ₂ = 30/3 = 10. .

Iteration 3, assign. The midpoint is 6; the clusters are unchanged, so the algorithm stops with . The sequence 207 → 82 → 46 → 16 → 16 never increases. Checking every split of the six points confirms 16 is the global minimum here.

A start with both centroids inside the left group still worked here: the right group pulled μ₂ over in one update. Section 4 shows a start where that doesn't happen.

Problem 2: (a) Show that for fixed assignments the best centroid of a cluster is its mean. (b) Use that, together with the assignment rule, to explain why J can never increase. (c) Why can k-means still give a bad answer?

(a) For cluster , only depends on . Its gradient is . Setting it to zero gives , so is the mean. Because is a convex quadratic (its Hessian is ), this stationary point is the global minimum.

(b) In the assignment step each point moves to its nearest centroid, so its term can only shrink or stay the same. In the update step, by (a), each centroid moves to the minimizer of its cluster's sum, which can't be larger than the sum at the old centroid. Both steps therefore give .

(c) "Never increases" guarantees convergence, not optimality. J is not convex in the assignments and centroids jointly, so the algorithm can stop at a local minimum, where no single step helps (Section 4's start from A and E stops at 14.75 instead of 9.5). Even the global minimum of J can be the wrong grouping if the clusters aren't round and similar in size (the parallel bands in Section 7). Fixes: restarts, k-means++, scaling, or a different algorithm.