Unit 3 · Unsupervised Learning · Course Outcomes CO2, CO3

Nobody tells you the answer.

Every model in Unit 2 was handed the right answer during training and graded against it afterwards. Take the labels away and both halves of that break: there is nothing to fit and nothing to score. This unit is about finding structure with no answer key, and about the harder problem of deciding whether what you found is real.

Section 3.1

Twelve students, no labels

Is there structure here at all?

Practice hours across, assignments submitted up. No colour, because there is nothing yet to colour by — we have not been told who passed.

Look before reading on. Most people see three groups: a cluster near the origin, one far right at low height, one up the middle. That perception is what clustering algorithms try to formalise, and the interesting question is what happens when your intuition and the algorithm disagree.

Colour contract cluster 1 — L cluster 2 — P cluster 3 — A what the algorithm learns — centroids, k, ε noise, or unassigned
The colour contract has changed — deliberately

In Units 2A and 2B, rose meant fail and teal meant pass. Here there are no labels to colour by, so the three accents mark clusters instead, and cluster identity is the only thing colour encodes until section 3.4.

When the hidden outcome finally appears in 3.4, it is drawn as marker shape — filled for pass, hollow for fail — so that colour never means two things at once on the same figure. Watch for it: the moment a figure carries both cluster and outcome is the moment the two stop agreeing.

What you need before this chapter

From Unit 1: Euclidean distance and squared distance (1.1), entropy in the form H = −Σp log p (1.5), and eigenvalues of a 2×2 matrix. From Unit 2A: k-NN's distance geometry and the scaling requirement (2.3.2), and Naive Bayes' generative view (2.3.6), which returns here as Gaussian mixtures with the labels removed. From Unit 2B: the reasoning about what a validation number is entitled to claim (2.4.6) — it applies with more force here, because there is no ground truth at all.

If you can compute a squared distance, average four coordinates, and find the eigenvalues of a symmetric 2×2 matrix, you have everything this unit needs.

The spine: twelve students and one outsider

A new dataset for this unit, because clustering needs more than the eight students of Unit 2 to show anything interesting. Two features are recorded for each student, and the arithmetic has been arranged so that every centroid is a whole number and every point sits at distance exactly 1 from its own centroid.

The spine — practice hours and assignments submitted
Studentx₁ practice hrs/weekx₂ assignmentsmarks /20outcomegroup it will turn out to be in
S1125failL
S2327failL
S3214failL
S4238failL
S57211failP
S69213passP
S78110failP
S88314passP
S94816passA
S106819passA
S115715passA
S125918passA
S139512passnone — the outsider
Two things to be clear about before we start

The marks and the outcome are not available to any algorithm in sections 3.1 to 3.3. They are printed here because section 3.4 needs them to grade the clustering afterwards, and because it would be dishonest to hide them and then produce them as a surprise. Every clustering in this file uses x₁ and x₂ only. If you catch yourself using the outcome column to decide what the clusters should be, you have stopped doing unsupervised learning.

The three groups have a story, and it is not the same story as the outcome. Group L practises little and submits little. Group A submits a great deal. Group P — the one that matters — practises heavily but submits few assignments, and it contains two students who passed and two who failed. So the clusters and the outcome will partly agree, which is the realistic case and the one that makes section 3.4 worth doing.

The nine numbers this whole file is built fromn = 12 (plus S13, held aside) means: x̄₁ = 5 x̄₂ = 4 grand mean (5, 4) centred scatter: S₁₁ = Σ(x₁ − 5)² = 78 S₂₂ = Σ(x₂ − 4)² = 102 S₁₂ = Σ(x₁ − 5)(x₂ − 4) = 0 exactly zero — remember this for 3.3 total scatter TSS = S₁₁ + S₂₂ = 180 cluster centroids: L (2, 2) P (8, 2) A (5, 8) within-cluster scatter at k = 3: 4 + 4 + 4 = 12 between-cluster scatter: 168 12 + 168 = 180

That decomposition — total scatter splits exactly into within plus between — is the identity every method in section 3.1 and every index in section 3.2 is built on. It is worth checking once by hand now, because after that it can be used freely.


3.1.1

K-Means

Guess where the centres are, assign everyone to the nearest, move the centres to the middle of what they caught, repeat. Two lines of algorithm and a surprising number of ways to go wrong.

The question

You have twelve students and a suspicion that they fall into groups. Nobody has told you how many groups, which students belong together, or what the groups mean. What could you even optimise?

Here is one answer, and it is worth pausing on because everything follows from it. Suppose each group will be summarised by a single representative point. Then a good grouping is one where every student is close to their own group's representative. Make that precise and you have k-means.

The intuition

Three ice-cream vans must serve twelve houses, and each house walks to the nearest van. Where should the vans park?

Wherever they start, two improvements are always available. Each house should walk to whichever van is genuinely nearest — that is free, and it can only shorten walks. And each van should move to the middle of the houses currently walking to it — that is also free, and it can only shorten walks again.

Alternate the two and total walking distance falls every time until nothing changes. That alternation is the algorithm, and the fact that both steps can only improve things is the whole convergence proof.

The formal treatment

The objective: within-cluster sum of squareschoose clusters C₁ … Cₖ and centroids μ₁ … μₖ to minimise WCSS = Σₖ Σᵣ ∈ Cₖ ‖xᵢ − μₖ‖² note: SQUARED distance, not distance. That choice is not cosmetic — it is what makes the optimal μₖ the arithmetic mean.
Lloyd's algorithminitialise k centroids somehow repeat: ASSIGN each point to the nearest centroid c(i) = argminₖ ‖xᵢ − μₖ‖² UPDATE each centroid to the mean of its assigned points μₖ = (1/|Cₖ|) Σᵣ ∈ Cₖ xᵢ until no assignment changes cost per iteration: O(n k d) guaranteed to terminate

Two facts, and they matter more than the pseudocode.

Why the mean. Fix a cluster and ask which single point μ minimises Σ‖xᵢ − μ‖². Differentiate: −2Σ(xᵢ − μ) = 0, so μ = (1/m)Σxᵢ. The mean is not a convenient choice, it is the unique optimum of squared distance. Replace squared distance with absolute distance and the optimum becomes the median instead, which is the k-medians algorithm; require the representative to be an actual data point and you get k-medoids. The loss chooses the summary, exactly as in 1.3.

Why it stops but does not necessarily succeed. Both steps decrease WCSS, and there are finitely many partitions, so the algorithm cannot cycle and must halt. But it halts at a local minimum. Finding the global optimum of WCSS is NP-hard, so every implementation runs several random starts and keeps the best.

Depth — the assumptions hiding inside "nearest centroid"

Assigning each point to the nearest centroid draws a boundary exactly halfway between every pair of centroids, perpendicular to the line joining them. The resulting regions are a Voronoi tessellation: convex, straight-edged, and unbounded at the outside. Three consequences follow immediately, and each is a real limitation rather than a technicality.

k-means cannot find a non-convex cluster. A crescent wrapped around a blob is impossible, because no straight boundary separates them. k-means prefers clusters of similar size and spread, because a large diffuse cluster next to a small tight one will have its outer members captured by the tight one's centroid. And k-means is not scale-invariant: it inherits 2.3.2's problem exactly, since squared Euclidean distance adds the features' contributions, so a feature measured in larger units dominates the geometry. Standardise before clustering, and standardise using the whole dataset since there is no train/test split to leak across.

There is also a subtler statistical point. Minimising WCSS is equivalent to fitting a Gaussian mixture with equal, spherical, fixed covariances and hard assignments — which is why section 3.1.4 can present GMMs as k-means with the restrictions lifted.

The worked example

Worked 3.1.1a — k-means from a good start
converges in one iteration
Run k-means with k = 3 on the twelve students, initialising the centroids at S1 (1,2), S5 (7,2) and S9 (4,8). Show the assignment step in full and compute the final WCSS.
Step 1 — the assignment step, longhand

For each student compute the squared distance to all three centroids and take the smallest. Squared distance avoids square roots and the comparison is identical, exactly as in 2.3.2.

Squared distances to the three initial centroids
Studentto (1,2)to (7,2)to (4,8)nearest
S1 (1,2)03645L
S2 (3,2)41637L
S3 (2,1)22653L
S4 (2,3)22629L
S5 (7,2)36045P
S6 (9,2)64461P
S7 (8,1)50265P
S8 (8,3)50241P
S9 (4,8)45450A
S10 (6,8)61374A
S11 (5,7)41292A
S12 (5,9)65532A

Note S9's row: it is equidistant from the two initial centroids at 45 each, and is captured by the third only because that centroid is S9. Had the third seed been elsewhere, this row would have been a coin flip — a reminder of how much the initialisation decides.

Step 2 — the update step
cluster L = {S1, S2, S3, S4} μ₁ = ((1 + 3 + 2 + 2)/4, (2 + 2 + 1 + 3)/4) = (8/4, 8/4) = (2, 2) cluster P = {S5, S6, S7, S8} μ₂ = ((7 + 9 + 8 + 8)/4, (2 + 2 + 1 + 3)/4) = (32/4, 8/4) = (8, 2) cluster A = {S9, S10, S11, S12} μ₃ = ((4 + 6 + 5 + 5)/4, (8 + 8 + 7 + 9)/4) = (20/4, 32/4) = (5, 8)
Step 3 — second iteration, and termination

Repeat the assignment step with the new centroids. Every student is now at squared distance exactly 1 from its own centroid, and at least 25 from either other centroid — so no assignment changes, and the algorithm stops.

check S4 (2,3), the closest any student comes to a rival centroid: to μ₁ (2,2): 0 + 1 = 1 to μ₂ (8,2): 36 + 1 = 37 to μ₃ (5,8): 9 + 25 = 34 nearest is μ₁, unchanged ✓
Step 4 — the WCSS, and the scatter decomposition

By the design of the dataset every point sits at distance exactly 1 from its own centroid, so each cluster contributes 4 × 1² = 4.

WCSS = 4 + 4 + 4 = 12 total scatter about the grand mean (5,4): TSS = 78 + 102 = 180 between-cluster scatter: L: 4‖(2,2) − (5,4)‖² = 4(9 + 4) = 52 P: 4‖(8,2) − (5,4)‖² = 4(9 + 4) = 52 A: 4‖(5,8) − (5,4)‖² = 4(0 + 16) = 64 BSS = 168 check: WCSS + BSS = 12 + 168 = 180 = TSS ✓
Clusters {S1,S2,S3,S4}, {S5,S6,S7,S8}, {S9,S10,S11,S12} with centroids (2,2), (8,2) and (5,8). WCSS = 12, down from 180 with one cluster.
Converged after one update, because the seeds happened to lie one per group.
93.3% of the total scatter is now between clusters rather than within them.

That last figure, BSS/TSS = 168/180 = 0.9333, is the honest summary of how well this clustering compresses the data, and it is the quantity the Calinski–Harabasz index of section 3.2 is built from. Keep the decomposition in mind: clustering moves scatter from the within column to the between column, and every internal validation index is some way of asking how much got moved.

Worked 3.1.1b — the same algorithm from a bad start
a local minimum you cannot escape
Now initialise at S1 (1,2), S2 (3,2) and S3 (2,1) — three seeds that all happen to lie inside group L. Trace the algorithm.
Iteration 1

All three seeds are in the bottom-left corner, so the eight students of groups P and A are all nearest to whichever of the three is furthest right — S2 at (3,2). The other two seeds split the four L students between them.

assignments: {S1, S4} | {S2, S5, S6, S7, S8, S9, S10, S11, S12} | {S3} new centroids: (1.5, 2.5) | (6.1111, 4.6667) | (2, 1) WCSS = 117.8889
Iteration 2, and termination
assignments: {S1, S4} | {S5, S6, S7, S8, S9, S10, S11, S12} | {S2, S3} new centroids: (1.5, 2.5) | (6.5, 5) | (2.5, 1.5) WCSS = 100.0000 iteration 3 changes nothing. Converged.
Final WCSS = 100.0000, against the global optimum's 12.0000 — more than eight times worse.
The algorithm has split group L across two clusters and merged groups P and A into one.
Nothing is wrong with the code. Both steps improved WCSS at every iteration, and it converged correctly to a local minimum.

This is the failure mode to be able to describe, because it is silent. The algorithm reports success, the centroids look plausible if you do not plot them, and the answer is nonsense. Across all 220 possible three-student initialisations, 192 reach the global optimum of 12 and 28 do not — so roughly one start in eight fails, and when it fails it fails badly.

Every local minimum reachable from a data-point start, and how often
final WCSSreached fromclusters found
12.0000192 of 220the correct three groups
81.33334{1,2,3,5,6,7} {4,8} {9,10,11,12}
82.000011{1…8} {9,11} {10,12}
82.66676{1…8} {9,11,12} {10}
100.00007{1,4} {2,3} {5…12}

Notice the shape of every failure: a genuine cluster gets split, and two genuine clusters get merged. That is the characteristic signature, and it is why the fix is about spreading the seeds out.

k-means++ — the standard fix

Rather than choosing all seeds uniformly at random, choose them one at a time with a bias toward being far from the seeds already chosen.

k-means++ seedingpick the first centroid uniformly at random from the data for each remaining centroid: for every point x, let D(x) = distance to the NEAREST chosen centroid choose the next centroid at random with probability proportional to D(x)² then run Lloyd's algorithm as usual

Suppose the first seed lands on S1. The squared distances from S1 are 0, 4, 2, 2, 36, 64, 50, 50, 45, 61, 41, 65, summing to 420 — so the probability of picking S6 next is 64/420 = 0.1524 and of picking S2 next only 4/420 = 0.0095. The three L students, which caused the disaster in Worked 3.1.1b, together hold just 8/420 = 0.019 of the probability mass. The catastrophic start has been made about fifty times less likely, at the cost of one extra pass over the data.

It is still random and it can still fail, which is why the practical recipe is k-means++ and ten restarts, keeping the lowest WCSS. That is what n_init=10 means in a library, and it is why the number is a default rather than a hyperparameter you tune.

The visualization

Lloyd's algorithm, one step at a time
interactive — choose the seeds and watch it converge or fail
step0assign, then update
WCSS180.0best possible at k=3 is 12
BSS / TSS0.00fraction of scatter explained
convergednono assignment changed
 

The amber crosses are the centroids — the only thing the algorithm learns. Each press of Next step performs one half-step, assign then update, so the first press colours the points and the second moves the crosses.

At k = 3, good seeds settle at WCSS 12 after a single update while bad seeds converge, just as confidently, to 100. Both runs are correct executions of the same algorithm and only one found the structure. Then push k to 4 or 5 and try the good seeds again: they are chosen by farthest-first, so they are guaranteed spread out, and they still land above the optimum — 10.67 against 10, and 9.33 against 8. Spreading the seeds reduces the failure rate without eliminating it, which is precisely why the practical recipe is k-means++ and restarts rather than either alone. The third button runs ten k-means++ starts and keeps the best, and it reaches the optimum at every k.

The pitfalls

Where marks are lost
  • Running k-means once and trusting it. Worked 3.1.1b. Always use multiple restarts and report the best WCSS, not the first.
  • Forgetting to standardise the features. Squared Euclidean distance sums the features' contributions, so units decide the answer. This is 2.3.2's trap in a new setting and it is just as fatal.
  • Comparing WCSS across different k to choose k. WCSS falls monotonically as k rises and reaches exactly 0 when k = n. It cannot select k; section 3.2 is what does.
  • Expecting k-means to find elongated or nested shapes. The regions are convex by construction. A crescent around a blob is outside the hypothesis space, and no amount of data or restarts changes that.
  • Using the mean with non-Euclidean distance. The mean minimises squared Euclidean distance specifically. With Manhattan distance the correct centre is the median, which is a different algorithm.
  • Leaving an empty cluster unhandled. If a centroid catches nothing, its mean is undefined. Implementations re-seed it, usually at the point furthest from its own centroid; a hand computation should say what it did.
  • Reading the cluster numbering as meaningful. Cluster 1 and cluster 2 could swap on the next run with no change to the partition. Only the grouping is a result; the labels are arbitrary, which is exactly why section 3.4 needs metrics that ignore them.

Practice

P3.1.1.1 (direct) — Four points sit at (0,0), (2,0), (0,2), (2,2). Compute the centroid, each point's squared distance to it, and the WCSS if they form one cluster.
centroid = ((0+2+0+2)/4, (0+0+2+2)/4) = (4/4, 4/4) = (1, 1) each point: (0−1)² + (0−1)² = 2 and by symmetry all four give 2 distance from centroid = √2 = 1.4142 for every point WCSS = 4 × 2 = 8

The symmetry is worth noticing: any set of points arranged symmetrically about a centre has that centre as its centroid, and you can read the centroid off by inspection rather than by averaging. Each of the spine's three clusters is built this way, which is why every centroid there is a whole number.

P3.1.1.2 (variation) — Run one full iteration of k-means on the twelve students with k = 2, seeded at S1 (1,2) and S9 (4,8). What clusters result, and what is the WCSS?

Compute squared distances to (1,2) and (4,8). Group L is plainly nearer S1. For group P: S5 (7,2) gives 36 against 45, so it goes to S1's cluster; S6 (9,2) gives 64 against 61, so it goes to S9's cluster. Check S7 (8,1): 50 against 65, to S1. S8 (8,3): 50 against 41, to S9.

assignments: {S1,S2,S3,S4,S5,S7} | {S6,S8,S9,S10,S11,S12} new centroids: (3.8333, 1.6667) | (6.1667, 6.3333) second iteration reassigns S6 and S8 back, and the run settles at {S1,...,S8} | {S9,S10,S11,S12} centroids (5, 2) and (5, 8) WCSS = 84.0000

The stable k = 2 answer merges L and P and keeps A separate, because the vertical gap between A and the others is larger than the horizontal gap between L and P. WCSS 84 against 180 for one cluster and 12 for three — and that gap between 84 and 12 is what makes the elbow in section 3.2 so sharp. Note also that at k = 2 the two centroids are (5,2) and (5,8), both sitting at x₁ = 5, so the boundary is horizontal and the practice-hours feature has stopped mattering entirely.

P3.1.1.3 (interpretation) — A colleague clusters customer records with k = 4 and reports WCSS 4,182. They then try k = 8, get WCSS 1,930, and conclude that eight clusters describe the customers better. Diagnose.

The comparison is meaningless as stated. WCSS decreases monotonically in k for a simple structural reason: any k-cluster solution can be improved by splitting one cluster in two, so the optimum at k+1 is never worse than at k. At k = n, WCSS is exactly zero. So "lower WCSS at higher k" is guaranteed and carries no information about whether the extra clusters are real.

This is the unsupervised twin of 2B's problem with training accuracy: a number that improves automatically as capacity grows cannot be used to select capacity. In 1.6's vocabulary, WCSS is a training loss.

What would settle it. Plot WCSS against k and look for a knee rather than a minimum, and compute silhouette, Davies–Bouldin and Calinski–Harabasz, all of which have interior optima — that is section 3.2. Check stability by clustering bootstrap resamples and asking whether the same groups reappear. And look at the clusters: if two of the eight differ only in ways nobody can act on, they are not clusters worth having, whatever the arithmetic says.

P3.1.1.4 (synthesis) — Using 2.3.2 and 2.3.4, compare what k-means, k-NN and a decision tree each assume about the shape of a group in feature space.

k-means assumes convex, roughly spherical, similarly sized regions. Nearest-centroid assignment produces a Voronoi tessellation: straight boundaries placed halfway between centroid pairs. Squared Euclidean distance makes the regions isotropic, so an elongated cluster gets cut in half rather than recognised.

k-NN assumes only local smoothness. Its boundary is assembled from perpendicular bisectors between individual points rather than centroids, so it can trace any shape given enough data — the jagged outline of 2.3.7's comparison figure. It buys that flexibility with variance and with a complete dependence on feature scaling.

A decision tree assumes axis-aligned rectangles. It cannot draw the diagonal of 2.3.4, but it also does not care about scaling at all, since splits depend only on the ordering of values. Its regions are convex like k-means', but restricted to boxes rather than arbitrary half-space intersections.

The unifying point, and the reason all three appear in this course: each method's failure mode is the shape it cannot represent, and no amount of data fixes it. k-means will never find a crescent, a tree will never find a diagonal, and k-NN will never work in twenty dimensions. Choosing a method is choosing which shapes you are willing to miss — which is 2.3.7's closing point, restated with the labels removed.


3.1.2

Hierarchical Clustering

Do not choose k at all. Build the whole family of clusterings from twelve singletons up to one group, and cut it wherever you like afterwards.

The question

k-means needs k before it starts, and section 3.2 exists because choosing k is genuinely hard. Is there a method that defers the decision?

There is, and it produces something strictly more informative than a single partition: a nested family of them, one for every possible k, arranged so that you can see which merges were comfortable and which were forced.

The intuition

Biological taxonomy. Species group into genera, genera into families, families into orders. You do not decide in advance how many groups there are; you build the tree and read off whichever level you need.

The construction is greedy and almost embarrassingly simple. Start with every student in their own cluster. Repeatedly merge the two closest clusters. Stop when one cluster remains. Record the distance at which each merge happened, and that record is the tree.

The one real decision is what "closest" means for two groups rather than two points, and that choice changes the answer more than beginners expect.

The formal treatment

Agglomerative clusteringstart with n clusters, each a single point repeat n − 1 times: find the pair of clusters with the smallest linkage distance merge them, recording the height at which they merged
The four standard linkages, and what each one does to you
LinkageDistance between clusters A and BBehaviour
Singlemin over pairs a ∈ A, b ∈ BFollows thin bridges of points, so it can trace elongated and non-convex shapes — and chains, linking two real clusters through a single stray point.
Completemax over pairsRequires every member to be close, so it produces compact, balanced clusters and is sensitive to outliers.
Averagemean over all pairsA compromise; the usual default when you have no reason to prefer either extreme.
Wardthe increase in WCSS caused by mergingOptimises k-means' own objective greedily, so it gives similar answers and similar assumptions — compact, spherical, similarly sized.

The output is a dendrogram: a tree whose leaves are the data points and whose internal nodes sit at the height of the merge they represent. Cutting it horizontally at any height yields a partition, and the number of vertical lines the cut crosses is the resulting k. Cost is O(n²) memory for the distance matrix and O(n² log n) to O(n³) in time, which caps it at a few tens of thousands of points.

How to read a dendrogram, which is the actual skill. The height of a merge says how dissimilar the two groups were. A long vertical stretch with no merges means the structure below it is stable across a wide range of thresholds — that is where to cut. Horizontal position carries no information whatsoever; the leaf order is arbitrary and any subtree can be reflected without changing the tree.

The worked example

Worked 3.1.2 — single against complete linkage on the same twelve students
the linkage changes the tree
Build the dendrogram under single linkage and under complete linkage. Read off the three-cluster solution from each and compare the merge heights.
Step 1 — the distances you need

Inside each cluster the four points form a diamond about the centroid, so the distances are the same in all three groups: the two diagonal pairs are at √2 = 1.4142 and the two axis pairs at 2.

within any cluster, e.g. L = {S1(1,2), S2(3,2), S3(2,1), S4(2,3)}: S1–S3 = S1–S4 = S2–S3 = S2–S4 = √2 = 1.4142 S1–S2 = 2 S3–S4 = 2 between clusters, the CLOSEST pairs (single linkage): L to P: S2(3,2) – S5(7,2) = 4.0000 L to A: S4(2,3) – S11(5,7) = √(9 + 16) = 5.0000 P to A: S8(8,3) – S11(5,7) = √(9 + 16) = 5.0000 between clusters, the FURTHEST pairs (complete linkage): L to P: S1(1,2) – S6(9,2) = 8.0000 L to A: S3(2,1) – S12(5,9) = √(9 + 64) = √73 = 8.5440 P to A: S7(8,1) – S12(5,9) = √(9 + 64) = 8.5440
Step 2 — single linkage
Single linkage: minimum distance between groups
mergeheightjoins
11.4142S1 + S3
21.4142{S1,S3} + S2
31.4142{S1,S3,S2} + S4 — cluster L complete
4–61.4142the same three merges build cluster P
7–91.4142and again for cluster A
104.0000L + P
115.0000{L,P} + A

All nine within-cluster merges happen at the same height, 1.4142, because single linkage only needs one close pair — each new point joins via its nearest diagonal neighbour. Then a large jump to 4.0.

Merge 10 joins L and P at 4.0, their closest pair being S2 and S5. Merge 11 then attaches A at 5.0, the closest pair between the combined cluster and A being S4 (2,3) and S11 (5,7) at √(9 + 16) = 5. Note that L and P merge first even though A is no further away, because 4.0 < 5.0 — the horizontal gap between the two low clusters is smaller than the vertical gap up to A.

Step 3 — complete linkage
Complete linkage: maximum distance between groups
mergeheightjoins
1–61.4142the six diagonal pairs: S1+S3, S2+S4, S5+S7, S6+S8, S9+S11, S10+S12
72.0000{S1,S3} + {S2,S4} — cluster L complete
82.0000{S5,S7} + {S6,S8} — cluster P complete
92.0000{S9,S11} + {S10,S12} — cluster A complete
108.0000L + P
118.5440{L,P} + A   (√73)

Complete linkage builds each cluster in pairs first, because merging a third point into a pair would require the maximum distance to be small, and 2.0 is larger than 1.4142. So it forms the six diagonal pairs, then joins them at 2.0.

Both linkages recover the same three clusters. But look at the gaps.
Single linkage: within-cluster merges at 1.4142, then the jump to 4.0000 — a ratio of 2.8.
Complete linkage: within-cluster merges up to 2.0000, then the jump to 8.0000 — a ratio of 4.0.
Complete linkage's gap is the more decisive, so the three-cluster cut is easier to justify from its dendrogram.

Cut either tree anywhere between the last within-cluster merge and the first between-cluster merge — between 1.4142 and 4.0 for single, between 2.0 and 8.0 for complete — and you get exactly three clusters. That interval is the range of thresholds over which the answer is stable, and its width is the honest measure of how confident the tree lets you be.

The reason complete linkage separates more decisively here is structural, not luck. Single linkage's between-cluster distance is the closest pair, which is small whenever two clusters have any near-neighbours at all; complete linkage's is the furthest pair, which stays large. That makes single linkage the one that can follow a crescent, and also the one that can be fooled by a single point sitting between two groups — the chaining problem. With S13 added at (9,5), single linkage would happily use it as a stepping stone.

The visualization

The dendrogram, and the cut you choose
interactive — linkage and cut height
Dendrogram
The resulting clusters
clusters at this cut3lines the cut crosses
stable range6.00width of the gap giving this k
largest gap6.00between consecutive merges
merge heights11always n − 1
 

Drag the cut and the count on the right changes in steps, never smoothly — a dendrogram offers only certain values of k. Tick S13 and watch what single linkage does with it: the outsider becomes a bridge, and the clean gap that justified three clusters shrinks.

The pitfalls

Where marks are lost
  • Reading meaning into the horizontal order of the leaves. It is arbitrary. Any node's two children can be swapped freely, so two dendrograms that look different can be identical trees.
  • Using single linkage on data with points between clusters. Chaining will link genuine clusters through a stray point. If outliers are possible, prefer complete, average or Ward.
  • Expecting the merge heights to be comparable across linkages. Complete linkage's heights are systematically larger than single linkage's on the same data — 8.0 against 4.0 here. A cut height is meaningful only relative to its own tree.
  • Cutting at a fixed k without looking at the gaps. The whole advantage of the method is that it shows you which cuts are well supported. Cutting at k = 5 here would slice through a run of merges at identical heights, which is the tree telling you the split is arbitrary.
  • Forgetting that merges are irreversible. The algorithm is greedy with no backtracking, so an early bad merge is permanent. This is the same greediness as a decision tree's root split in 2.3.4, with the same consequence.
  • Applying it to a large dataset. The distance matrix is O(n²). At a million points that is 1012 entries, so this method is simply unavailable and k-means or a sampled approximation is required.
  • Not standardising. Same as everywhere in this unit. The linkage is computed from distances.

Practice

P3.1.2.1 (direct) — Five points on a line at positions 0, 1, 3, 7, 8. Build the single-linkage dendrogram and give every merge height.
pairwise distances: 0–1 = 1, 1–3 = 2, 3–7 = 4, 7–8 = 1 merge 1 at height 1: {0} + {1} (tie with 7+8; either order) merge 2 at height 1: {7} + {8} merge 3 at height 2: {0,1} + {3} min distance |3 − 1| = 2 merge 4 at height 4: {0,1,3} + {7,8} min distance |7 − 3| = 4

The largest gap between consecutive merge heights is from 2 to 4, so the natural cut gives two clusters: {0,1,3} and {7,8}. Under complete linkage the heights would be 1, 1, 3, 8 instead — merge 3 at |3 − 0| = 3 and merge 4 at |8 − 0| = 8 — giving the same two clusters with a more emphatic gap, exactly as in Worked 3.1.2.

P3.1.2.2 (variation) — Add S13 at (9,5) to the twelve students. Where does single linkage place it, and where does complete linkage?

First the distances from S13 to its nearest points in each cluster: to S6 (9,2) is 3; to S8 (8,3) is √(1+4) = 2.2361; to S10 (6,8) is √(9+9) = 4.2426, and to S11 (5,7) is √(16+4) = 4.4721; to S1 (1,2) is √(64+9) = 8.5440.

Single linkage. The nine within-cluster merges still happen first at 1.4142. Then the smallest remaining distance is S13 to cluster P at 2.2361, so S13 joins P before anything else merges. The tree then continues: P∪{S13} joins L at 4.0, and A joins at 5.0. So S13 is absorbed into P early and cheaply, and the dendrogram gives no hint that it is unusual.

Complete linkage. S13's distance to the whole of P is its furthest member: to S5 (7,2) is √(4+9) = 3.6056. That is larger than the 2.0 at which P completes, so P forms first and S13 joins at 3.6056 — still before the big merges at 8.0, but visibly later and at its own height. The dendrogram shows a lone leaf attaching high up, which is the visual signature of an outlier.

The lesson is that neither linkage can refuse S13. Hierarchical clustering, like k-means, partitions everything; only DBSCAN in the next section has the option of saying no.

P3.1.2.3 (interpretation) — A dendrogram of 200 genes shows merge heights of 0.1, 0.12, 0.13, … up to 0.4, then a single merge at 2.8. What does it tell you, and what would you check?

It says the data has two groups and the split between them is extremely clean. Everything below 0.4 merged gradually, then a gap of a factor of seven before the final merge. Cutting anywhere from 0.4 to 2.8 gives the same two clusters, so the two-cluster answer is stable across a very wide range of thresholds — the strongest evidence a dendrogram can offer.

What to check. First, the sizes: a "two-cluster" structure where one cluster has 199 genes and the other has 1 is an outlier, not a grouping, and the dendrogram alone does not distinguish those cases. Second, whether the split tracks a batch or processing artefact rather than biology — if the two clusters correspond to two sequencing runs, the structure is real and uninteresting. Third, the linkage: under single linkage a gap this clean is harder to achieve, so if this is complete or Ward linkage some of the gap may be the method's own bias toward compact balanced clusters.

And below 0.4 there is a second question worth asking. That range of gradual merges may contain sub-structure worth cutting at, and the way to find out is to look for the largest gap within it rather than treating everything below the big split as homogeneous.

P3.1.2.4 (synthesis) — Ward linkage merges the pair that increases WCSS least. Using 3.1.1, show that Ward's first merge on the twelve students is one of the diagonal pairs, and explain why Ward and k-means tend to agree.

Merging two singletons a and b creates a cluster whose centroid is their midpoint, so the new within-cluster scatter is ‖a − m‖² + ‖b − m‖² = ‖a − b‖²/2. Both singletons contributed 0 before, so the increase in WCSS is exactly half the squared distance. Minimising that increase is therefore the same as minimising the squared distance, and Ward's first merge is the closest pair — one of the six diagonal pairs at √2, costing 2/2 = 1 in WCSS.

Contrast the axis pairs at distance 2, which would cost 4/2 = 2. So Ward's opening moves match complete linkage's here, forming the six pairs before joining them.

Why they agree in general. Ward is greedy minimisation of precisely the objective k-means minimises. The two differ only in how they search: k-means iterates from an initialisation and can escape a poor early configuration by reassigning points, while Ward builds bottom-up and can never undo a merge. So Ward inherits k-means' assumptions — compact, spherical, similarly sized clusters — and adds greediness, which is why Ward's result is often used to initialise k-means rather than to replace it. The practical combination is Ward for the dendrogram and the choice of k, then k-means from Ward's centroids to polish the assignment.


3.1.3

DBSCAN

Stop asking how many clusters there are and start asking where the data is dense. The only method here that is allowed to say "this point belongs to nothing".

The question

Both previous methods share two properties that usually go unremarked and are sometimes disastrous. Every point must be assigned to some cluster, and the clusters must be roughly convex blobs. So what do you do with S13, sitting at (9, 5) between two groups and close to neither? And what do you do with a dataset shaped like two interleaved crescents?

The intuition

Think of a city at night from the air. You do not identify neighbourhoods by picking three centres and assigning every light to the nearest one. You identify them as regions where the lights are dense, separated by dark gaps — and a single lamp in the middle of a field is not a neighbourhood, it is a farmhouse.

That is DBSCAN. A cluster is a maximal region of connected density. Its shape is whatever the density happens to be, so crescents and rings are fine. And a point in a sparse region is not forced into anything; it is labelled noise, a genuine third answer that neither k-means nor hierarchical clustering can give.

Made precise, "dense" needs two numbers: how far you are willing to look, and how many neighbours count as crowded.

The formal treatment

Two parameters, three kinds of pointε the radius of the neighbourhood minPts how many points, INCLUDING itself, make a point dense N(p) = { q : dist(p, q) ≤ ε } the ε-neighbourhood of p CORE |N(p)| ≥ minPts the interior of a dense region BORDER not core, but within ε of a core point the edge of a cluster NOISE neither belongs to nothing
How clusters get builtq is DIRECTLY DENSITY-REACHABLE from p if p is core and q is in N(p) q is DENSITY-REACHABLE from p if a chain of such steps links p to q p and q are DENSITY-CONNECTED if both are density-reachable from one core point a CLUSTER is a maximal set of density-connected points for each unvisited point p: if p is not core: mark it NOISE for now else: open a new cluster and expand through every density-reachable point, following chains ONLY onward from core points a noise point may later be reclaimed as a BORDER point of a cluster

The restriction that chains extend only from core points is what stops clusters leaking across sparse bridges, and it is the one detail people drop when implementing this by hand. A border point is absorbed into a cluster but cannot pass the cluster on to its own neighbours.

One consequence worth stating: DBSCAN's output is not always unique. A border point within ε of core points from two different clusters is assigned to whichever cluster reached it first, so it depends on the order the points were visited. Core points and noise points are order-independent; only border points can flip.

Choosing the two parameters

The standard heuristics, and what each parameter controls
ParameterRule of thumbWhat goes wrong at each extreme
minPtsAt least d + 1, commonly 2d for d features; raise it for noisy dataToo small: chains of two points become clusters. Too large: everything is noise.
εPlot each point's distance to its minPts-th nearest neighbour, sorted, and take the value at the kneeToo small: everything is noise. Too large: all clusters merge into one.

The k-distance plot is the only principled way to pick ε and is worth knowing by name. Sort every point by its distance to its minPts-th neighbour and plot; points in clusters have small values and flat behaviour, noise points shoot up at the right-hand end, and the knee is the density threshold that separates them.

Depth — what DBSCAN can do that k-means cannot, and the reverse

In DBSCAN's favour. Arbitrary cluster shapes, because a cluster is defined by connectivity rather than by proximity to a centre — two interleaved crescents are separated correctly, and no choice of k lets k-means do that. The number of clusters is discovered rather than specified. Outliers are identified explicitly rather than absorbed. And the result is deterministic for core points, with no restarts needed.

Against. DBSCAN assumes a single density threshold applies everywhere, so a dataset with one tight cluster and one diffuse cluster cannot be handled by any single ε — you either merge the tight ones or lose the diffuse one entirely. That limitation is what HDBSCAN and OPTICS exist to fix, by considering all density thresholds at once and extracting a hierarchy. DBSCAN also degrades badly in high dimensions, for exactly 2.3.2's reason: distances concentrate, so every point ends up with a similar number of neighbours and the notion of density stops discriminating. And it gives no centroid, no model, and no way to assign a new point without recomputing.

The honest summary: use k-means when you expect compact blobs and want a model you can apply to new data; use DBSCAN when the shapes are unknown, outliers matter, and the data is low-dimensional.

The worked example

Worked 3.1.3 — DBSCAN on all thirteen students
every point classified by hand
Run DBSCAN with ε = 1.5 and minPts = 3 on the twelve students plus S13. Classify every point as core, border or noise, and give the clusters.
Step 1 — which pairs are within 1.5 of each other?

Inside each diamond cluster the diagonal pairs are at √2 = 1.4142 and the axis pairs at 2. So ε = 1.5 admits the diagonals and excludes the axis pairs — a deliberately tight choice that makes the density argument do real work.

in cluster L = {S1(1,2), S2(3,2), S3(2,1), S4(2,3)}: within 1.5: S1–S3, S1–S4, S2–S3, S2–S4 (the four diagonals, 1.4142) NOT within: S1–S2 (2.0), S3–S4 (2.0) S13(9,5) to its nearest neighbour S8(8,3): √(1 + 4) = 2.2361 > 1.5
Step 2 — classify every point
Neighbourhood counts at ε = 1.5, minPts = 3
Pointneighbours within 1.5|N| incl. selfverdict
S1 (1,2)S3, S43core
S2 (3,2)S3, S43core
S3 (2,1)S1, S23core
S4 (2,3)S1, S23core
S5 (7,2)S7, S83core
S6 (9,2)S7, S83core
S7 (8,1)S5, S63core
S8 (8,3)S5, S63core
S9 (4,8)S11, S123core
S10 (6,8)S11, S123core
S11 (5,7)S9, S103core
S12 (5,9)S9, S103core
S13 (9,5)none1NOISE

Every one of the twelve is core with exactly |N| = 3 = minPts — the boundary case, satisfied by equality. There are no border points at all in this run. S13 has an empty neighbourhood and is noise.

Step 3 — grow the clusters by density-connectivity

Start at S1. It is core, so open cluster 1 and expand.

cluster 1: start {S1} S1 is core, N(S1) = {S3, S4} → add S3, S4 S3 is core, N(S3) = {S1, S2} → add S2 S4 is core, N(S4) = {S1, S2} → S2 already in S2 is core, N(S2) = {S3, S4} → nothing new cluster 1 = {S1, S2, S3, S4} the same expansion gives cluster 2 = {S5, S6, S7, S8} and cluster 3 = {S9, S10, S11, S12}

Note what happened to S1 and S2. They are not within ε of each other — their distance is 2.0 — yet they are in the same cluster, reached through S3. That is density-connectivity doing its job, and it is the mechanism that lets DBSCAN follow a chain of density around a curve.

Three clusters, exactly matching the groups: {S1–S4}, {S5–S8}, {S9–S12}. S13 is noise.
Twelve core points, zero border points, one noise point.
The number of clusters was never specified — it came out of the density structure.

Compare with what k-means did to S13. Its squared distances to the three centroids are 58, 10 and 25, so k-means must place it in cluster P, dragging that centroid from (8, 2) to (8.2, 2.6) and raising the cluster's scatter from 4 to 12 — tripling it because of one point. The overall WCSS goes from 12 to 20. DBSCAN simply declines, and the three clusters it reports are exactly the ones a human would draw.

Worked 3.1.3b — the same data at four parameter settings
sensitivity, quantified
How much does the answer depend on ε and minPts?
DBSCAN on the thirteen students across parameter settings
εminPtsclusterscore ptsnoiseverdict
1.0300all 13ε below every pairwise distance — nothing is dense
1.53312S13correct
1.5400all 13each point has only 3 in its neighbourhood — one short
2.03312S13correct
2.53312noneS13 absorbed into cluster P as a border point
3.03313noneS13 is now core in its own right
The correct answer occupies a narrow window: ε between roughly 1.5 and 2.0 with minPts = 3.
One notch of minPts upward and everything becomes noise. A little more ε and the outlier is quietly absorbed.
DBSCAN removed the need to choose k and replaced it with two parameters that are at least as delicate.

That is the trade to be honest about, and it is the same trade as everywhere else in machine learning: a method that makes fewer assumptions about shape has to get its information from somewhere, and here it comes from ε. The failure at minPts = 4 is especially instructive — each point has exactly three neighbours including itself, so requiring four makes every point in the dataset noise and DBSCAN reports no structure at all in data that plainly has three clusters.

The visualization

Density, core points and noise
interactive — both parameters
clusters found3not specified in advance
core points12of 13
border points0reached, but not dense
noise1assigned to nothing
 

The faint circles are each point's ε-neighbourhood; a point is core when its circle contains at least minPts points counting itself. Shrink ε below 1.41 and every circle empties, so the whole dataset becomes grey noise. Grow it past 2.24 and S13's circle reaches S8, so the outlier joins a cluster. The window in which DBSCAN gets this dataset right is visible as the range where three colours and one grey point coexist.

The pitfalls

Where marks are lost
  • Forgetting that minPts counts the point itself. The most common arithmetic slip in the topic. With three neighbours plus itself, |N| = 4; conventions that exclude the point shift every threshold by one, so state which you are using.
  • Letting border points extend a cluster. Only core points propagate. A border point joins a cluster and stops there, and ignoring this merges clusters that should stay separate.
  • Expecting a unique answer. Border points equidistant from two clusters depend on visit order. Core and noise assignments are deterministic; border assignments are not.
  • Using one ε on data with varying density. The structural limitation of the method. If one cluster is tight and another diffuse, no single threshold works and you need HDBSCAN or OPTICS.
  • Applying it in high dimensions. Distance concentration makes every point's neighbourhood count similar, so density stops distinguishing anything. Reduce dimension first — carefully, per section 3.3.
  • Treating noise as a cluster. Noise points are not a group; they have nothing in common except sparsity. Reporting "four clusters, one of which is the noise label" is wrong.
  • Not standardising. A single ε applies to all features at once, so unequal units make it meaningless in a way that is even more direct than for k-means.

Practice

P3.1.3.1 (direct) — Six points on a line at 0, 1, 2, 6, 7, 20. With ε = 1.5 and minPts = 2, classify each point and give the clusters.
neighbourhoods within 1.5, including the point itself: 0: {0, 1} |N| = 2 → CORE 1: {0, 1, 2} |N| = 3 → CORE 2: {1, 2} |N| = 2 → CORE 6: {6, 7} |N| = 2 → CORE 7: {6, 7} |N| = 2 → CORE 20: {20} |N| = 1 → NOISE cluster 1 = {0, 1, 2} cluster 2 = {6, 7} noise = {20}

Note that 0 and 2 are 2.0 apart, beyond ε, yet they share a cluster because 1 is core and links them — density-connectivity again. Raise minPts to 3 and only the point at 1 stays core, so the cluster becomes {0,1,2} still (0 and 2 become border points) while {6,7} collapses entirely to noise. One notch of minPts destroyed a real cluster.

P3.1.3.2 (variation) — On the thirteen students, find the smallest ε that makes S13 a border point rather than noise, with minPts = 3.

S13 becomes a border point as soon as it falls within ε of some core point. Its distances to the nearest members of cluster P are: to S8 (8,3) √5 = 2.2361, to S6 (9,2) 3.0000, to S5 (7,2) √13 = 3.6056, to S7 (8,1) √17 = 4.1231.

at ε = 2.2361, S13 is within reach of S8 is S8 still core at that ε? N(S8) = {S5, S6, S13} plus itself = 4 ≥ 3 ✓ does S13 become core itself? N(S13) = {S8} plus itself = 2 < 3 ✗ so at ε = √5 = 2.2361 exactly, S13 is a BORDER point of cluster P

Two things follow. S13 joins the cluster but cannot extend it, so it contributes nothing further. And its status changed without any change to the data — a parameter moved by 0.74 and a point went from "anomaly worth investigating" to "ordinary member of group P". If the purpose of the analysis were outlier detection, that parameter choice is the analysis, and it should be justified from a k-distance plot rather than left at a default.

P3.1.3.3 (interpretation) — DBSCAN on 50,000 transactions returns 3 clusters and 31,000 noise points. What has gone wrong, and how would you diagnose it?

62% noise means the parameters are far too strict, or the data has no density structure at that scale. Noise is meant to be a small minority; when it is the majority, DBSCAN is not describing the data.

Three candidate causes, in order of likelihood. Features are unstandardised, so ε is being spent almost entirely on whichever feature has the largest units — check the feature ranges first, it costs nothing. ε is too small or minPts too large, which the k-distance plot will show directly: plot each point's distance to its minPts-th neighbour, sorted, and if the current ε sits well below the knee, that is the answer. Or the dimensionality is too high, which is the serious case — with fifty features, distances concentrate and no ε separates dense from sparse.

What to do about the third case. Do not simply raise ε until the noise count looks acceptable; that is fitting the parameter to the desired conclusion. Reduce dimension first, then re-plot the k-distance curve. And consider whether the density assumption suits the data at all: transaction data often has continuously varying density rather than dense islands in empty space, in which case DBSCAN's single global threshold is the wrong model and HDBSCAN or a mixture model is the better fit.

P3.1.3.4 (synthesis) — Using 3.1.1 and 3.1.2, explain what DBSCAN's noise label costs and what it buys, and name the situation where each of the three methods is the right choice.

What noise buys. Robustness of the cluster descriptions. In Worked 3.1.3 the three DBSCAN clusters have centroids exactly at (2,2), (8,2) and (5,8), because S13 was excluded; k-means' third centroid was pulled to (8.2, 2.6) and its scatter tripled. Every summary statistic you compute per cluster is contaminated by forced assignments, and noise labelling prevents that. It also turns outlier detection into a by-product rather than a separate analysis.

What it costs. Coverage. If those 31,000 transactions of P3.1.3.3 are real customers, refusing to describe them is not a result. It also costs the ability to score a new point: k-means assigns a new student by comparing to three centroids, and DBSCAN has no such rule, so deploying it requires re-running on the combined data or fitting a classifier to its output. And it costs determinism at the borders.

When to use which. k-means when you expect compact groups of similar size, need a reusable model, and have enough data that the restarts of 3.1.1 are cheap — it is the default for good reason. Hierarchical when n is small enough for an O(n²) matrix and the nesting is itself informative, as in taxonomy or document organisation, or when you want to see how well-supported each choice of k is before committing. DBSCAN when cluster shapes are unknown or non-convex, when outliers are the interesting part rather than a nuisance, and when the dimension is low enough for density to mean something.

And the meta-point, which is 2.3.7's again: all three ran on the same twelve students and agreed. That agreement is evidence the structure is real, and running more than one method is the cheapest robustness check available in unsupervised learning — because there is no test set to appeal to.


3.1.4

Gaussian Mixture Models

Naive Bayes from 2.3.6 with the class labels removed. Soft assignments, elliptical clusters, and a likelihood you can actually compare across models.

The question

k-means gives every point a hard verdict: you are in cluster 2, full stop. But S13 at (9, 5) is genuinely ambiguous — it sits between two groups — and a hard label throws that information away. Is there a method that can say "80% group P, 20% group A"?

And a second complaint. k-means' clusters are spherical by construction. Real groups are often elongated: a cluster of students who all practise a lot but vary widely in assignments is a long thin ellipse, and k-means will cut it in half.

The intuition

Turn the problem around. Instead of asking "which cluster is this point nearest", ask "what process could have generated this data?"

Suppose each student was produced in two stages. First a group was chosen at random — group L with probability π₁, P with π₂, A with π₃. Then their features were drawn from that group's own bell curve, with its own centre and its own spread and orientation. You observe the features but not which group was chosen.

That is a generative model, exactly the framing of 2.3.6, and the difference is that Naive Bayes was told the class of every training example while here the class is hidden. Fitting the model means recovering the groups' parameters and, as a by-product, the probability that each student came from each group. Those probabilities are the soft assignment we wanted.

The formal treatment

The modelp(x) = Σₖ πₖ · N(x | μₖ, Σₖ) with Σₖ πₖ = 1, πₖ ≥ 0 πₖ the MIXING WEIGHT of component k — how common that group is μₖ its mean vector — where it sits Σₖ its covariance matrix — its size, shape and orientation N(x | μ, Σ) = (2π)^(−d/2) |Σ|^(−1/2) exp( −½(x − μ)ᵀΣ⁻¹(x − μ) )

The quantity in the exponent, (x − μ)ᵀΣ⁻¹(x − μ), is the squared Mahalanobis distance — ordinary squared distance measured in units of the cluster's own spread along each direction. Set Σ = I and it reduces to squared Euclidean distance, which is the first hint of how GMMs contain k-means as a special case.

Expectation–maximisation

We cannot maximise the likelihood directly, because it involves a sum inside a logarithm. EM works around this by alternating — and the alternation is deliberately the same shape as k-means'.

The EM algorithminitialise π, μ, Σ (commonly from a k-means run) E-step compute the RESPONSIBILITY of component k for point i: γᵢₖ = πₖ N(xᵢ | μₖ, Σₖ) / Σⱼ πⱼ N(xᵢ | μⱼ, Σⱼ) each row sums to 1 — this is the soft assignment M-step re-fit each component, weighted by its responsibilities: Nₖ = Σᵢ γᵢₖ the EFFECTIVE number of points in k πₖ = Nₖ / n μₖ = (1/Nₖ) Σᵢ γᵢₖ xᵢ Σₖ = (1/Nₖ) Σᵢ γᵢₖ (xᵢ − μₖ)(xᵢ − μₖ)ᵀ repeat until the log-likelihood stops increasing

Compare the two algorithms side by side and the relationship is unmistakable. k-means' assign step is the E-step with responsibilities forced to 0 or 1; k-means' update step is the M-step with those hard weights and covariance held fixed at σ²I. k-means is EM for a Gaussian mixture with equal spherical fixed covariances and hard assignments — and as σ² → 0, the responsibilities of a GMM converge to exactly 0 and 1, so k-means is the zero-variance limit of a GMM.

EM has the same guarantee and the same weakness as Lloyd's algorithm: the log-likelihood increases at every iteration, so it converges, but only to a local maximum. Multiple restarts are required for the same reason.

Choosing the covariance structure, and choosing k

Covariance options, cheapest first
TypeParameters per component (d features)Cluster shape
spherical1Circles of one size — effectively k-means
diagonaldAxis-aligned ellipses
tiedd(d+1)/2, shared by allIdentically shaped and oriented ellipses
fulld(d+1)/2 eachAny ellipse, any orientation — most flexible, most prone to overfitting

Because a GMM is a probability model, it offers something no method so far in this unit has: a principled way to compare different k. The log-likelihood always rises with k, just as WCSS always falls, so it is penalised for the number of parameters.

Information criteria — lower is betterBIC = −2 ln L + p ln n AIC = −2 ln L + 2p L = the maximised likelihood, p = number of free parameters, n = points for k components, d features, FULL covariance: p = (k − 1)  +  k·d  +  k·d(d+1)/2 weights means covariances BIC penalises complexity more heavily than AIC once n > 8, and is the usual choice for selecting k

This is section 1.7's regularization idea in a third guise: an objective plus a penalty on complexity, with the penalty here derived rather than tuned. It is also the cleanest answer to "how many clusters" available anywhere in this unit, and it is available only because we committed to a probability model.

Depth — the singularity that will bite you

A Gaussian mixture's likelihood is unbounded. Put one component's mean exactly on a single data point and shrink its covariance toward zero: the density at that point goes to infinity, so the likelihood does too. The "optimal" solution is therefore degenerate — a spike on one point — and it explains nothing.

EM finds these in practice, particularly with full covariance, many components, or few points per component. The symptom is a component whose determinant collapses and whose responsibility for one point goes to 1. Three standard defences: add a small constant to the diagonal of every covariance (a regularization term, usually called reg_covar, typically 10⁻⁶); restrict the covariance type to diagonal or tied, which removes most of the freedom that causes it; or place a prior on the covariance and maximise the posterior instead, which is what a Bayesian GMM does.

The general lesson is worth extracting, because it recurs in Unit 5. A model flexible enough to place unbounded density on a single observation will do so if the objective rewards it. Maximum likelihood has no defence against this on its own; the penalty has to come from outside, exactly as ridge had to be added to least squares in 2.2.

The worked example

Worked 3.1.4 — one E-step by hand
soft assignments, three variance settings
Take a spherical GMM with equal weights πₖ = 1/3, means at the three cluster centroids (2,2), (8,2), (5,8), and shared covariance σ²I. Compute the responsibilities for S1, S5, S9 and S13 at σ² = 1, 4 and 9.
Step 1 — simplify the formula for spherical, equal-weight components

With Σₖ = σ²I and all πₖ equal, every constant in front of the exponential is the same for all three components and cancels in the ratio. So the responsibility depends only on the squared distances.

γᵢₖ = exp(−dᵢₖ² / 2σ²) / Σⱼ exp(−dᵢⱼ² / 2σ²) where dᵢₖ² = ‖xᵢ − μₖ‖² this is a SOFTMAX over negative half-scaled squared distances, which is the same function that appears in 1.8 and in Unit 4
Step 2 — the squared distances
Squared distance from each point to each component mean
Pointto (2,2)to (8,2)to (5,8)
S1 (1,2)14952
S5 (7,2)25140
S9 (4,8)40521
S13 (9,5)581025
Step 3 — S13 at σ² = 4, longhand
exponents −d²/(2σ²) = −d²/8: −58/8 = −7.2500 → e^(−7.2500) = 0.000710 −10/8 = −1.2500 → e^(−1.2500) = 0.286505 −25/8 = −3.1250 → e^(−3.1250) = 0.043937 sum = 0.331152 γ = (0.000710, 0.286505, 0.043937) / 0.331152 = (0.0021, 0.8652, 0.1327) check: 0.0021 + 0.8652 + 0.1327 = 1.0000 ✓
Step 4 — all four points, all three variances
Responsibilities: how the variance controls softness
Pointσ² = 1σ² = 4σ² = 9
S11.0000, 0.0000, 0.00000.9958, 0.0025, 0.00170.8863, 0.0616, 0.0521
S50.0000, 1.0000, 0.00000.0471, 0.9457, 0.00720.1913, 0.7256, 0.0831
S90.0000, 0.0000, 1.00000.0076, 0.0017, 0.99070.0976, 0.0501, 0.8522
S130.0000, 0.9994, 0.00060.0021, 0.8652, 0.13270.0462, 0.6649, 0.2889
At σ² = 4, S13 is 86.5% group P and 13.3% group A — the ambiguity k-means could not express.
At σ² = 1 the assignments are effectively hard and the GMM has become k-means.
At σ² = 9 even S1, sitting one unit from its own mean, is only 88.6% certain.

Read the table as a dial rather than three separate results. σ² controls how much distance it takes to change your mind, and the two extremes are both degenerate: as σ² → 0 every responsibility becomes 0 or 1 and you have k-means back; as σ² → ∞ every responsibility approaches 1/3 and every point belongs equally to everything. In a real GMM σ² is not a dial you set — the M-step fits it — which is precisely the flexibility k-means lacks.

One further reading of S13's row. Its responsibility never approaches 0.5 for any variance, so the model is consistently clear that group P is the better explanation. The soft assignment is not fence-sitting; it is a calibrated statement, and it is exactly the kind of output that section 2B's calibration material tells you to check before trusting.

The visualization

Soft assignment, and the shape a covariance allows
interactive — variance and covariance type
S13 → P0.865responsibility
S13 → A0.133responsibility
max responsibility0.991across all 13 points
effectively hard?noall γ above 0.99
 

Each point is drawn as a pie of its three responsibilities, so a point wholly in one cluster is a solid disc and an ambiguous one is visibly divided. Drag σ² to its minimum and every disc becomes solid — the GMM has collapsed to k-means. Drag it to the maximum and every disc becomes three equal thirds, which is the model declaring it has learned nothing.

The pitfalls

Where marks are lost
  • Forgetting to normalise the responsibilities. Each point's γ values must sum to 1 across components. The denominator is the whole point of the E-step.
  • Confusing πₖ with γᵢₖ. πₖ is one number per component — how common that group is overall. γᵢₖ is a number per point per component.
  • Using full covariance with few points. Each full component costs d(d+1)/2 covariance parameters. With 12 points and 3 components that is 9 covariance parameters plus 6 means plus 2 weights — more than one parameter per point, and the singularity of the depth box is close.
  • Reporting the log-likelihood to compare different k. It rises with k automatically, exactly like WCSS falls. Use BIC or AIC.
  • Treating a responsibility as a calibrated probability without checking. It is a probability under the assumed model. If the true clusters are not Gaussian, the number is confident and wrong — 2.4.6's problem, in a setting with no labels to check it against.
  • Running EM once. Local maxima, same as k-means. Initialise from k-means and restart several times.
  • Assuming a GMM will beat k-means. With genuinely spherical, well-separated, equal-sized clusters — this dataset, for instance — the extra flexibility buys nothing and costs parameters. The gain appears when clusters are elongated, overlapping, or of very different sizes.

Practice

P3.1.4.1 (direct) — A two-component spherical GMM has π = (0.6, 0.4), means (0,0) and (4,0), and σ² = 2. Compute the responsibilities for the point (1,0).
squared distances: to (0,0) is 1 ; to (4,0) is 9 now the weights do NOT cancel, because π₁ ≠ π₂ (the normalising constants still cancel, since σ² is shared) numerator₁ = 0.6 · exp(−1/4) = 0.6(0.778801) = 0.467281 numerator₂ = 0.4 · exp(−9/4) = 0.4(0.105399) = 0.042160 sum = 0.509441 γ = (0.9172, 0.0828)

The point is three times closer to the first mean in squared distance and the first component is also more common, so both effects push the same way. Note how to check this kind of answer: if the two means were equidistant, the responsibilities would be exactly the mixing weights (0.6, 0.4), so any deviation from that is the distance term talking.

P3.1.4.2 (variation) — For the spine, count the free parameters of a 3-component GMM with spherical, diagonal and full covariance, and compute the BIC penalty term for each at n = 12.
d = 2, k = 3. weights contribute k − 1 = 2 ; means contribute k·d = 6. spherical: p = 2 + 6 + 3(1) = 11 diagonal: p = 2 + 6 + 3(2) = 14 full: p = 2 + 6 + 3(3) = 17 d(d+1)/2 = 3 each BIC penalty = p ln n = p ln 12 = p (2.4849): spherical 11(2.4849) = 27.33 diagonal 14(2.4849) = 34.79 full 17(2.4849) = 42.24

Full covariance must improve −2 ln L by nearly 15 over spherical just to break even, and with 12 data points and 17 parameters it is very unlikely to earn that honestly — it is more likely to find the singularity of the depth box. On this dataset spherical is not merely adequate, it is the only defensible choice, and BIC says so before you run anything.

The general shape is worth remembering: full covariance costs O(kd²) parameters, so it becomes unusable in high dimensions long before the data does. At d = 50 and k = 5, full covariance needs 6,375 parameters and diagonal needs 504.

P3.1.4.3 (interpretation) — A GMM fitted with k = 5 and full covariance reports one component with mixing weight 0.004 and a covariance determinant of 3 × 10⁻&sup9;. What has happened and what would you do?

That component has collapsed onto a single data point. A weight of 0.004 on n points means an effective count of 0.004n — with 250 points, exactly one — and a near-zero determinant means the covariance has shrunk to a spike. This is the singularity of the depth box, found by EM exactly as predicted. The reported log-likelihood is inflated and meaningless, so any BIC computed from it is also meaningless, and the remaining four components have been fitted to the data with one point removed.

What to do, in order. Add covariance regularization — a small constant on the diagonal — which is one line and usually sufficient. Reduce the covariance type from full to diagonal or tied, which removes most of the freedom the collapse exploited. Reduce k, since a spurious component is often a sign that five is more than the data supports; refit at k = 2, 3, 4 and compare BIC properly. And check whether the point is a genuine outlier or a data error, because either way it deserves attention rather than a dedicated Gaussian.

What not to do is accept the fit because the likelihood is the highest you have seen. Unbounded objectives reward degenerate solutions, and a higher likelihood here is evidence of the pathology rather than against it.

P3.1.4.4 (synthesis) — Using 2.3.6 and 3.1.1, state precisely how a GMM relates to Naive Bayes and to k-means, and say what each relationship buys.

Against Naive Bayes. Both are generative: both model P(class) and P(x | class) and combine them with Bayes' theorem. Gaussian Naive Bayes is a Gaussian mixture with diagonal covariance — that is exactly what the conditional-independence assumption means geometrically, since a diagonal covariance has no off-diagonal terms and so no modelled correlation between features. The single difference is supervision: Naive Bayes is told each training point's class and estimates each class's parameters by direct counting in one pass, while a GMM must infer the classes and so needs EM. So a GMM is unsupervised Naive Bayes, and full covariance is what you gain by dropping the naive assumption.

Against k-means. k-means is EM for a mixture with equal, spherical, fixed covariances and hard assignments, and it is the limit of a GMM as σ² → 0 — Worked 3.1.4's σ² = 1 column already shows the responsibilities collapsing to 0 and 1. Lifting the three restrictions buys three things: elongated and rotated clusters, clusters of different sizes and spreads, and soft assignments that record ambiguity instead of discarding it.

What it costs, and the honest conclusion for this dataset. Parameters, and therefore variance — P3.1.4.2 counted 17 for full covariance against 12 data points. The spine's clusters are spherical, equally sized and well separated, which is precisely the case where k-means' restrictions are true rather than merely convenient, so the GMM's flexibility earns nothing here and BIC penalises it for asking. The value of knowing the relationship is not that GMMs are better; it is that you can now say what k-means assumes, because the assumptions are visible as the special case rather than hidden in the algorithm.


3.2

Internal Validation: How Many Clusters?

Four ways to grade a clustering with no labels to grade it against. They agree on this dataset, which is a luxury, and the second half of this section is about what to do when they do not.

The question

k-means needs k. DBSCAN needs ε. A dendrogram needs a cut. Every method in 3.1 pushed the hard decision out to the user, and this section is where the bill arrives.

The difficulty is sharper than it looks. In Unit 2 a hyperparameter was chosen by measuring performance on held-out labelled data. Here there are no labels, so there is nothing to hold out and no performance to measure. Whatever we compute has to be a property of the geometry alone.

The intuition

Without an answer key, only one kind of question is available: are the clusters tight, and are they far apart? Every index in this section is some ratio of those two quantities, and the differences between them are differences in how the ratio is formed.

Notice immediately what this cannot do. It measures whether the partition is geometrically clean, not whether it is correct or useful. A clustering that splits customers by screen resolution can be beautifully tight and completely worthless. Internal validation answers a question about shapes, and you should not let it answer a question about meaning.

The formal treatment

The elbow method

Plot WCSS against k and look for the kneeWCSS(k) falls monotonically: WCSS(1) = TSS and WCSS(n) = 0 so there is no minimum to find. Instead look for the k after which the improvement becomes small — the "elbow". equivalently, plot the fraction of variance explained BSS/TSS = 1 − WCSS/TSS and look for where the curve flattens.

The elbow is a heuristic and it is honest to call it one. There is no threshold, no formula, and on real data the curve is frequently smooth with no identifiable knee at all. It is included because it is universally used and because when the elbow is sharp, as it is here, it is genuinely informative.

Silhouette

Per point, then averagedfor point i: a(i) = mean distance from i to the OTHER points in its own cluster b(i) = mean distance from i to the points of the NEAREST other cluster s(i) = ( b(i) − a(i) ) / max( a(i), b(i) ) −1 ≤ s(i) ≤ +1 s(i) near +1 i is much closer to its own cluster than to any other s(i) near 0 i sits on a boundary s(i) negative i is closer on average to another cluster — probably misassigned silhouette score = mean of s(i) over all points (a singleton cluster is conventionally given s = 0)

Silhouette is the most informative of the four because it is defined per point. The average is a single number for choosing k, but the distribution is a diagnostic: a cluster whose points have low or negative silhouettes is a cluster that should not exist, and you can see which points are the problem.

Davies–Bouldin

Worst-case ratio of spread to separation — LOWER is betterSₖ = mean distance from the points of cluster k to its own centroid (spread) Mₖⱼ = distance between centroids k and j (separation) for each cluster k, find its worst rival: Rₖ = maxⱼ≠ₖ (Sₖ + Sₕ) / Mₖⱼ DB = (1/k) Σₖ Rₖ DB = 0 would mean zero spread. Typical good values are below about 1.

Calinski–Harabasz

The variance ratio — HIGHER is betterCH = [ BSS / (k − 1) ] / [ WCSS / (n − k) ] exactly an F-statistic: between-cluster scatter per degree of freedom divided by within-cluster scatter per degree of freedom. the degrees-of-freedom terms are what stop it rising automatically with k, which is why it has an interior maximum and WCSS does not.

The three indices are built from the same two ingredients — spread and separation — combined differently. Silhouette works from raw pairwise distances and averages over points. Davies–Bouldin works from centroids and takes a worst case, so it is the most pessimistic. Calinski–Harabasz works from the scatter decomposition of 3.1.1 and is the only one with an explicit complexity correction.

Depth — every one of these indices has a favourite shape

All four are built from centroids and Euclidean distances, so all four are biased toward the same thing k-means is biased toward: compact, spherical, similarly sized clusters. Run DBSCAN on two interleaved crescents, get the correct answer, and then score it with silhouette: it will report a mediocre value, because the points of one crescent are on average far from each other. The clustering is right and the index disagrees.

The consequence is uncomfortable and worth stating plainly. These indices do not measure whether a clustering is correct. They measure whether it is the kind of clustering k-means would like. Using silhouette to choose between a k-means result and a DBSCAN result on non-convex data is therefore rigged in advance, and the honest procedure is to use an index only to compare settings within one method, or to use a density-aware alternative such as DBCV.

There is a second, subtler problem: none of these indices has a null distribution. A silhouette of 0.55 sounds respectable, but uniformly random points in a square, clustered with k = 3, routinely score around 0.4 to 0.5 — k-means will happily cut structureless data into three tidy wedges. Without knowing what score random data would produce for your n and d, a silhouette value is uninterpretable. The gap statistic exists precisely to supply that baseline, comparing observed WCSS against WCSS on random data with the same bounding box.

The worked example

Worked 3.2a — silhouette at k = 3, every point by hand
the symmetry makes it tractable
Compute a(i), b(i) and s(i) for every one of the twelve students under the three-cluster solution, and the overall silhouette score.
Step 1 — a(i) is the same for all twelve

Each cluster is a diamond: every point has two neighbours at √2 and one at 2. So every point's mean distance to its own cluster is identical.

a(i) = (√2 + √2 + 2) / 3 = (1.414214 + 1.414214 + 2) / 3 = 4.828427 / 3 = 1.609476 for every point the symmetry of the design is doing the work here; on real data every point has its own a(i)
Step 2 — b(i) for S1, longhand

S1 sits at (1,2). Compute its mean distance to cluster P and to cluster A, then take the smaller.

to cluster P = {S5(7,2), S6(9,2), S7(8,1), S8(8,3)}: S1–S5 = 6.000000 S1–S6 = 8.000000 S1–S7 = √(49 + 1) = 7.071068 S1–S8 = √(49 + 1) = 7.071068 mean = 28.142136 / 4 = 7.035534 to cluster A = {S9(4,8), S10(6,8), S11(5,7), S12(5,9)}: S1–S9 = √(9 + 36) = 6.708204 S1–S10 = √(25 + 36) = 7.810250 S1–S11 = √(16 + 25) = 6.403124 S1–S12 = √(16 + 49) = 8.062258 mean = 28.983836 / 4 = 7.245959 b(S1) = min(7.035534, 7.245959) = 7.035534 (cluster P is nearer) s(S1) = (7.035534 − 1.609476) / 7.035534 = 5.426058 / 7.035534 = +0.7712
Step 3 — all twelve
Silhouette at k = 3. a(i) = 1.6095 throughout.
Pointa(i)b(i)nearest rivals(i)
S1 (1,2)1.60957.0355P+0.7712
S2 (3,2)1.60955.0495P+0.6813
S3 (2,1)1.60956.1237P+0.7372
S4 (2,3)1.60955.8741A+0.7260
S5 (7,2)1.60955.0495L+0.6813
S6 (9,2)1.60957.0355L+0.7712
S7 (8,1)1.60956.1237L+0.7372
S8 (8,3)1.60955.8741A+0.7260
S9 (4,8)1.60956.3641L+0.7471
S10 (6,8)1.60956.3641P+0.7471
S11 (5,7)1.60955.8741L+0.7260
S12 (5,9)1.60957.6486L+0.7896
silhouette score = mean of the twelve = 0.7368
Silhouette 0.7368, with every point positive and the lowest at +0.6813.
No point is anywhere near zero, so no point is on a boundary and nothing is misassigned.
S2 and S5 score lowest at +0.6813 — they are the pair facing each other across the L–P gap, which is the narrowest gap in the dataset.

The pattern in the "nearest rival" column is itself a map of the geometry. L and P name each other, because they are 6 apart horizontally. But S4 and S8 — the top corners of L and P — name A instead, because leaning upward puts A within reach. Reading that column tells you which clusters are at risk of merging if k were reduced, and it correctly predicts P3.1.1.2's finding that k = 2 merges L with P.

Worked 3.2b — all four indices across k = 1 to 6
and a unanimous verdict
For each k, take the best k-means solution and compute WCSS, silhouette, Davies–Bouldin and Calinski–Harabasz.
Step 1 — Calinski–Harabasz at k = 3, longhand

From 3.1.1: BSS = 168, WCSS = 12, n = 12, k = 3.

CH = [168 / (3 − 1)] / [12 / (12 − 3)] = [168 / 2] / [12 / 9] = 84 / 1.333333 = 63.0000 exactly
Step 2 — Davies–Bouldin at k = 3, longhand

Every point is exactly 1 from its centroid, so every cluster's spread is Sₖ = 1. Centroid separations: M₁₂ = 6 (L to P), and M₁₃ = M₂₃ = √(9 + 36) = √45 = 6.7082.

R₁ = max( (1+1)/6, (1+1)/6.7082 ) = max(0.333333, 0.298142) = 0.333333 R₂ = max( (1+1)/6, (1+1)/6.7082 ) = 0.333333 R₃ = max( (1+1)/6.7082, (1+1)/6.7082 ) = 0.298142 DB = (0.333333 + 0.333333 + 0.298142) / 3 = 0.964809 / 3 = 0.3216

Note that clusters L and P each pick each other as their worst rival, because 6 is the smallest centroid gap. Cluster A has no close rival, so its R is lower. Davies–Bouldin's worst-case construction means the tightest pair of clusters dominates the score.

Step 3 — the full table
Internal validation across k. Best value in each column is highlighted.
kWCSSdropBSS/TSSsilhouetteDavies–BouldinCalinski–Harabasz
1180.00000.0000
284.000096.00000.5333+0.50810.680211.4286
312.000072.00000.9333+0.73680.321663.0000
410.00002.00000.9444+0.54130.651845.3333
58.00002.00000.9556+0.35710.856537.6250
66.00002.00000.9667+0.17161.000034.8000
All four indicators point at k = 3.
The elbow is unmistakable: drops of 96 and 72, then 2, 2, 2. WCSS falls by 93.3% of its range by k = 3 and then essentially stops.
Silhouette peaks at 0.7368, Davies–Bouldin bottoms at 0.3216, Calinski–Harabasz maxes at exactly 63.
And DBSCAN found three clusters without being told, and both dendrograms had their widest gap at three.

Look at the WCSS column past k = 3. Every further cluster buys exactly 2.0, because it splits one diamond into two pairs and each pair contributes 2 × 0.5 = 1 instead of the diamond's 4 — a saving of 2 every time. That perfectly regular decline is the signature of splitting real clusters into arbitrary pieces, and it is what an elbow looks like from the far side.

Note also that BSS/TSS keeps rising all the way to k = 6, from 0.9333 to 0.9667. Like WCSS, the fraction of variance explained can never go the wrong way, so it cannot select k either — you must read the shape of that curve, not its maximum. Only silhouette, DB and CH have genuine interior optima, and that is the reason to prefer them.

The visualization

Four indices, one dataset, one answer
interactive — slide k and watch all four
WCSS and the elbow
Silhouette, per point
WCSS12.0always falls with k
silhouette0.737higher is better
Davies–Bouldin0.322lower is better
Calinski–Harabasz63.0higher is better
 

The right panel is the silhouette plot in its standard form: one horizontal bar per point, grouped by cluster and sorted within each. At k = 3 all twelve bars are long and even. Push k to 5 and short bars appear — those are the points that have been split away from their real cluster and now sit near a boundary. Tick S13 and the whole picture degrades, because one unassignable point contaminates whichever cluster is forced to take it.

The pitfalls

Where marks are lost
  • Choosing k by minimising WCSS. The minimum is always k = n. Same for maximising BSS/TSS. Read the shape, or use an index with an interior optimum.
  • Getting the direction of Davies–Bouldin wrong. It is a ratio of spread to separation, so lower is better. Silhouette and Calinski–Harabasz go the other way. Mixing these up is the most common error in the section.
  • Reading a silhouette of 0.5 as good without a baseline. Random points in a square score 0.4 to 0.5 at k = 3. Without a null comparison the number means little — that is what the gap statistic is for.
  • Using these indices to compare methods with different cluster shapes. All four are biased toward compact spherical clusters, so scoring a DBSCAN crescent with silhouette is rigged against it. Compare within a method, or use a density-aware index.
  • Forgetting that silhouette needs k ≥ 2. With one cluster there is no b(i), so silhouette is undefined and cannot tell you whether the data has any structure at all. None of these indices can rule out k = 1.
  • Averaging silhouette and stopping there. The distribution is the useful part. A mean of 0.6 could be all points at 0.6, or half at 0.9 and half at 0.3 — and only the second says a cluster is wrong.
  • Treating a geometrically clean clustering as a meaningful one. The deepest pitfall in the unit. These indices measure shape, and nothing in them knows what your features mean.

Practice

P3.2.1 (direct) — A point has mean distance 2.0 to its own cluster and mean distances 5.0 and 8.0 to the two other clusters. Compute its silhouette. Then recompute if its own-cluster distance were 6.0 instead.
a = 2.0, b = min(5.0, 8.0) = 5.0 s = (5.0 − 2.0) / max(2.0, 5.0) = 3.0 / 5.0 = +0.6000 now a = 6.0, b = 5.0 s = (5.0 − 6.0) / max(6.0, 5.0) = −1.0 / 6.0 = −0.1667

The negative value is the diagnostic. It says the point is on average closer to a different cluster than to its own, so it is very likely misassigned — and note the denominator switches from b to a as soon as a becomes the larger, which keeps s inside [−1, +1]. A silhouette plot with a run of negative bars in one cluster is telling you that cluster should be dissolved or merged.

P3.2.2 (variation) — Compute Calinski–Harabasz and Davies–Bouldin for the k = 2 solution on the twelve students, where L and P merge into one cluster of eight with centroid (5,2) and A stays as four points with centroid (5,8).
from P3.1.1.2, WCSS = 84, so BSS = 180 − 84 = 96 CH = [96 / (2 − 1)] / [84 / (12 − 2)] = 96 / 8.4 = 11.4286 (against 63.0000 at k = 3) Davies-Bouldin: cluster 1 = the eight points, centroid (5,2). Mean distance to centroid: the four L points are at distances √(16+0)=4, √(4+0)=2, √(9+1)=3.1623, √(9+1)=3.1623 the four P points are the mirror image: 2, 4, 3.1623, 3.1623 S₁ = (4+2+3.1623+3.1623+2+4+3.1623+3.1623)/8 = 24.64911/8 = 3.0811 cluster 2 = A, centroid (5,8), every point at distance 1, so S₂ = 1 M₁₂ = |8 − 2| = 6 R₁ = R₂ = (3.0811 + 1)/6 = 0.6802 DB = 0.6802 (against 0.3216 at k = 3)

Both indices are decisively worse at k = 2: CH falls by a factor of 5.5 and DB doubles. The reason is visible in S₁ = 3.0811 — the merged cluster's spread has tripled because it now spans two genuine groups, while the separation to A has not increased at all. That ratio of spread to separation is the whole content of both indices, and merging clusters attacks the numerator.

P3.2.3 (interpretation) — A team clusters 40,000 customers. Silhouette suggests k = 2, Davies–Bouldin suggests k = 4, Calinski–Harabasz suggests k = 9 and the elbow plot is a smooth curve. What now?

The disagreement is the finding, and it is a common one. Three indices built from the same two ingredients have picked three different answers, which means the data does not have a single clean cluster structure that all three can see. Do not pick the index whose answer you like.

First, check the mechanics. Were the features standardised? Are there dominant outliers pulling centroids around? Is a categorical variable being treated as numeric? These explain a surprising share of index disagreements and cost nothing to rule out.

Then test stability, which is more informative than any index. Cluster many bootstrap resamples at each candidate k and measure how often the same pairs of customers land together — the adjusted Rand index of section 3.4 applied between two clusterings rather than against truth. A k whose partition reproduces across resamples is real; one that changes every time is an artefact, whatever its silhouette. Add the gap statistic to get a null baseline, since with 40,000 points in high dimensions the indices may all be describing noise.

And then decide on external grounds, which is legitimate. Clustering here is presumably a means to something — targeted campaigns, tiered support, a product roadmap. If the business can act on four segments and not on nine, then k = 4 is the right answer regardless of Calinski–Harabasz, and the honest report says so: "the geometry does not strongly prefer any k; we chose 4 for actionability and verified it is stable under resampling." That is a better answer than a spurious optimum, and it is the shape of most real clustering work.

P3.2.4 (synthesis) — Compare choosing k here with choosing a hyperparameter in Unit 2.1. What is structurally different, and why can you not simply cross-validate?

What is the same. Both are model-selection problems in which a naive objective improves monotonically with capacity — training accuracy in 2.1, WCSS here — so the naive objective cannot be used, and both need either a held-out measurement or an explicit complexity penalty. Calinski–Harabasz's degrees-of-freedom terms and a GMM's BIC are penalty-based; 2.1's validation split is measurement-based.

What is structurally different, and it is decisive. In 2.1 there is a ground truth on the held-out fold, so "did the model get this right" is a well-posed question. Here there is no ground truth at all, so cross-validation has nothing to score. You can hold out points and assign them to the learned clusters, but the only thing you can then measure is how well they fit the clusters you already chose — and a clustering with more clusters will always fit them better, which reproduces exactly the problem you were trying to escape. There is no analogue of "correct" to appeal to.

What is available instead. Three things, in increasing order of value. Internal indices, which measure geometric quality and are biased toward spherical clusters. Stability, which asks whether the same partition reappears on resampled data — this is the closest genuine analogue of cross-validation, since it measures reproducibility rather than correctness. And external validation against labels you happen to have but did not cluster on, which is section 3.4 — the only one of the three that measures anything like correctness, and it is available only when you already have the answer you claimed not to need.

The honest conclusion is that unsupervised model selection is fundamentally weaker than supervised model selection, and no amount of index arithmetic changes that. Which is why the most valuable habit in this unit is running several methods and believing the structure only when they agree — as they did on this dataset, and as they usually will not on yours.


3.3

Dimensionality Reduction: PCA and t-SNE

Find the directions along which the data varies most, keep those, discard the rest. Then the payoff figure of this unit: a case where doing exactly that destroys the structure you were looking for.

The question

Every method in 3.1 relies on distances, and 3.1.3's depth box warned that distances stop discriminating in high dimensions. Real datasets have hundreds of features. So before clustering anything you often want to reduce the number of features — and you want to do it without throwing away what matters.

Two more reasons to care. You cannot plot more than three dimensions, and looking at your data is not optional. And features are usually correlated, so some of those hundreds of numbers are redundant rather than informative.

The intuition

Hold a pencil up and shine a light on it. The shadow on the wall is a two-dimensional picture of a three-dimensional object, and how informative it is depends entirely on the angle. Point the pencil straight at the wall and the shadow is a dot — you have lost the length. Hold it side-on and the shadow shows the full length.

PCA chooses the angle. Specifically, it chooses the direction in which the data is most spread out, projects onto that, then finds the most spread-out direction among what remains, and so on. Keep the first few and you have a low-dimensional shadow that preserves as much spread as possible.

Hold on to the word spread, because the whole of this section's punchline is that spread and usefulness are not the same thing.

The formal treatment

Setup1. CENTRE the data: zᵢ = xᵢ − x̄ (mandatory — PCA is about variance about the mean) 2. optionally STANDARDISE each feature to unit variance 3. covariance matrix: S = (1/(n−1)) Σᵢ zᵢ zᵢᵀ a symmetric d×d matrix
The problem PCA solvesfind the unit vector w maximising the variance of the projected data: maximise wᵀSw subject to wᵀw = 1 Lagrangian: L = wᵀSw − λ(wᵀw − 1) ∂L/∂w = 2Sw − 2λw = 0 Sw = λw so w is an EIGENVECTOR of S, and the variance it captures is wᵀSw = wᵀ(λw) = λ, the corresponding EIGENVALUE.

That derivation is worth being able to reproduce, because it is short and it explains every property of PCA at once. The principal components are the eigenvectors of the covariance matrix, ordered by eigenvalue. They are orthogonal because S is symmetric. The variance along component j is exactly λⱼ. And since the trace of S is both the sum of the feature variances and the sum of the eigenvalues, the fraction of total variance captured is simply λⱼ / Σλ.

Using itprojection onto the first m components: yᵢ = Wᵐᵀ zᵢ Wᵐ = [w₁ … wᵐ] reconstruction: ẑᵢ = Wᵐ yᵢ reconstruction error = Σᵢ ‖zᵢ − ẑᵢ‖² = (n−1) Σⱼ>ᵐ λⱼ — exactly the variance in the directions you threw away. explained variance ratio for m components: (λ₁ + … + λᵐ) / Σⱼ λⱼ choosing m: keep enough for 90–95% explained variance, or look for an elbow in the SCREE PLOT of λⱼ against j — the same heuristic, and the same weakness, as section 3.2's elbow.

PCA is also the optimal linear reconstruction: among all m-dimensional linear projections, the one onto the top m eigenvectors minimises squared reconstruction error. Maximising retained variance and minimising reconstruction error are the same problem, which is why one derivation serves both.

Depth — PCA is not scale-invariant, and the choice is not neutral

Covariance depends on units. Measure a length in millimetres instead of metres and its variance grows by a factor of 10⁶, so it dominates the covariance matrix and PC1 becomes essentially that feature alone. This is 2.3.2's scaling problem for a third time, and here it changes not just the answer but which question is being asked.

Standardising first — dividing each feature by its standard deviation — makes PCA operate on the correlation matrix instead. Every feature then contributes variance 1, so the total is d, and no feature can dominate by unit choice. This is the right default when features are in incommensurable units, which is most of the time.

But it is a genuine choice, not a formality. If all features are in the same meaningful units — pixel intensities, gene expression counts, marks out of 20 — then the differences in variance are real information, and standardising deliberately discards it. The rule: standardise when the units are arbitrary, do not when they are comparable, and say which you did.

One useful special case: for a standardised 2-feature dataset the correlation matrix is [[1, r], [r, 1]], whose eigenvalues are exactly 1 + r and 1 − r with eigenvectors exactly (1,1)/√2 and (1,−1)/√2 for any r. So PC1 always runs at 45° and the explained variance is (1 + r)/2. That is worth memorising as a sanity check.

The worked example

Worked 3.3a — the full PCA derivation on a 2×2 covariance matrix
exact eigenvalues
A centred dataset has covariance matrix S = [[4, 2], [2, 4]]. Find both principal components, their eigenvalues, the explained variance ratios, and the reconstruction error from keeping only the first.
Step 1 — the characteristic equation
det(S − λI) = 0 | 4−λ 2 | | 2 4−λ | = (4 − λ)² − 4 = 0 (4 − λ)² = 4 4 − λ = ±2 λ₁ = 6 λ₂ = 2

Two checks that catch almost every arithmetic error in this topic. The eigenvalues must sum to the trace: 6 + 2 = 8 = 4 + 4. ✓ And their product must equal the determinant: 6 × 2 = 12 = 16 − 4. ✓

Step 2 — the eigenvectors
for λ₁ = 6: (S − 6I)w = 0 [ −2 2 ] [w₁] [0] [ 2 −2 ] [w₂] = [0] −2w₁ + 2w₂ = 0 → w₁ = w₂ so w ∝ (1, 1); normalise: w₁ = (1/√2, 1/√2) = (0.7071, 0.7071) for λ₂ = 2: (S − 2I)w = 0 [ 2 2 ] [w₁] [0] [ 2 2 ] [w₂] = [0] 2w₁ + 2w₂ = 0 → w₁ = −w₂ w₂ = (1/√2, −1/√2) = (0.7071, −0.7071) verify: S w₁ = [[4,2],[2,4]](1,1) = (6, 6) = 6(1, 1) ✓ orthogonal: w₁ᵀw₂ = (1)(1) + (1)(−1) = 0, over 2 → 0 ✓
Step 3 — explained variance and reconstruction error
total variance = trace(S) = 8 = λ₁ + λ₂ PC1 explains 6/8 = 0.7500 PC2 explains 2/8 = 0.2500 keeping PC1 only: variance retained = 75.00% variance discarded = λ₂ = 2, which is 25.00% mean squared reconstruction error per point = 2
PC1 = (0.7071, 0.7071) with λ₁ = 6; PC2 = (0.7071, −0.7071) with λ₂ = 2. PC1 explains 75% of the variance.
The 45° direction is forced by the symmetry: equal diagonal entries always give eigenvectors at (1, ±1)/√2.
Here the two features have correlation 2/√(4 × 4) = 0.5, and (1 + 0.5)/2 = 0.75 — the depth box's shortcut, confirmed.
Worked 3.3b — PCA on the spine, and the point of this whole unit
the payoff
Apply PCA to the twelve students' two features. Then reduce to one dimension and check what happened to the three clusters.
Step 1 — the covariance matrix

From the spine's nine numbers: means (5, 4), and centred scatter S₁₁ = 78, S₂₂ = 102, S₁₂ = 0.

S = (1/11) [[78, 0], [ 0, 102]] = [[7.0909, 0.0000], [0.0000, 9.2727]] the off-diagonal entry is EXACTLY ZERO — the two features are perfectly uncorrelated in this dataset.

Verify the zero by hand, because it is the hinge of the whole example. Deviations from the mean (5,4) are: (−4,−2), (−2,−2), (−3,−3), (−3,−1) for L; (2,−2), (4,−2), (3,−3), (3,−1) for P; (−1,4), (1,4), (0,3), (0,5) for A. Products: 8 + 4 + 9 + 3 = 24 for L, −4 −8 −9 −3 = −24 for P, −4 + 4 + 0 + 0 = 0 for A. Total 24 − 24 + 0 = 0. ✓

Step 2 — the principal components, by inspection

A diagonal matrix's eigenvectors are the coordinate axes and its eigenvalues are the diagonal entries. No computation is required.

PC1 = (0, 1), the ASSIGNMENTS axis, λ₁ = 9.2727 explains 102/180 = 56.67% PC2 = (1, 0), the PRACTICE axis, λ₂ = 7.0909 explains 78/180 = 43.33% PC1 comes first because 102 > 78. That is the only reason.

Already something is odd. PCA has "found" nothing: the components are the original axes, and the only work it did was to notice which feature has more variance. That is the correct behaviour for uncorrelated features and it is worth seeing, because PCA is often described as though it always discovers hidden directions.

Step 3 — reduce to one dimension and look at the clusters

Project the three cluster centroids onto each component. Centroids are L(2,2), P(8,2), A(5,8); the grand mean is (5,4).

What each single component preserves
Clustercentroidon PC1 (assignments)on PC2 (practice)
L(2, 2)−2.0−3.0
P(8, 2)−2.0+3.0
A(5, 8)+4.00.0
KEEP PC1 (56.67% of the variance): L → −2.0 P → −2.0 A → +4.0 clusters L and P land on exactly the same point. They are GONE. a clustering run on this 1-D data can find at most TWO groups. KEEP PC2 (43.33% of the variance): L → −3.0 P → +3.0 A → 0.0 all three clusters remain distinct and evenly spaced.
Step 4 — reconstruction error, which points the other way
keep PC1: discarded variance = λ₂ = 7.0909 total squared reconstruction error = S₁₁ = 78 mean per point = 78/12 = 6.5000 keep PC2: discarded variance = λ₁ = 9.2727 total squared reconstruction error = S₂₂ = 102 mean per point = 102/12 = 8.5000

So by the criterion PCA actually optimises — reconstruction error — keeping PC1 is genuinely better: 78 against 102. PCA is not malfunctioning. It is doing precisely what it promises, optimally, and the result is useless for the task.

PCA's first component is the assignments axis. Keeping it preserves 56.67% of the variance and collapses two of the three clusters onto the same point.
Keeping the discarded component instead preserves less variance and all of the structure.
Variance is not information. PCA maximises variance because variance is what it can see without labels, and there is no guarantee that the directions with the most spread are the directions that matter.

This is the single most important idea in the unit, so it is worth saying in a second way. PCA is unsupervised: it never sees the cluster labels, the marks, or anything about what you intend to do next. So it optimises a proxy — retained variance — and a proxy is only as good as its correlation with the real objective. Here that correlation is negative.

The reason this dataset breaks PCA is geometric and diagnosable. The direction that separates L from P is horizontal, and the total spread happens to be slightly larger vertically because cluster A sits far above. So the separating direction is ranked second and discarded first. Nothing about the numbers is unusual: 102 against 78 is a difference of 31%, not a knife-edge.

What to do about it

Do not reduce dimension you do not need to reduce. Two features do not need PCA. This example is contrived in size but not in kind; the same thing happens at d = 200 → 10 and is invisible there.

Check the scree plot before trusting a cut. Here the eigenvalues are 9.27 and 7.09 — nearly equal, no elbow, and the ratio 56.67/43.33 says plainly that neither component is dispensable. A scree plot with no gap is PCA telling you it cannot compress this data, and the right response is to believe it.

If you have any labels, use a supervised method instead. Linear discriminant analysis maximises between-class separation relative to within-class scatter rather than total variance, and on this dataset it would keep the practice axis. PCA is the tool for when you have nothing to supervise with; it is not the tool for when you do.

And cluster on the full data, then use PCA only to draw the picture. Reducing for visualisation is safe because you are not making decisions from the reduced data. Reducing before clustering is where the damage happens.

The visualization

Choose a projection direction and watch the clusters survive or collapse
interactive — the payoff figure
variance retained0.567maximised at PC1
reconstruction error78.0minimised at PC1
cluster separation0.00smallest gap between centroids
clusters distinguishable2of 3, after projecting
 

The grey line is the projection direction and the marks below it are where each student lands. Watch the two right-hand readouts move in opposite directions to the two left-hand ones: at 90° the variance is maximal and the separation is zero; at 0° the variance is minimal and all three clusters are cleanly spaced. There is no angle that optimises both, and PCA is defined to pick the first pair.

t-SNE and UMAP, briefly and with a warning

PCA is linear: every component is a weighted sum of the original features. Data lying on a curved surface — a spiral, a rolled-up sheet — cannot be unrolled by any linear projection. t-SNE and UMAP are non-linear methods designed for one purpose: making a two-dimensional picture in which nearby points stay nearby.

t-SNE in outline1. in the ORIGINAL space, convert distances to probabilities: pᵢⱼ ∝ exp(−‖xᵢ − xⱼ‖² / 2σᵢ²) σᵢ set per point via PERPLEXITY 2. in the 2-D MAP, use a heavy-tailed Student-t kernel: qᵢⱼ ∝ (1 + ‖yᵢ − yⱼ‖²)⁻&sup9; 3. move the yᵢ by gradient descent to minimise KL(p ‖ q) the heavy tail is deliberate: it lets moderately distant points sit far apart in the map without penalty, which is what prevents everything collapsing into one blob.
What these methods do and do not preserve
PCAt-SNE / UMAP
TypeLinear, deterministicNon-linear, stochastic — different runs differ
PreservesGlobal variance and large distancesLocal neighbourhoods only
New pointsProject with Wᵀ, triviallyt-SNE cannot; UMAP can, approximately
Distances in the plotMeaningfulNot meaningful — neither between clusters nor within
Cluster sizes in the plotMeaningfulNot meaningful — a dense cluster is inflated, a diffuse one shrunk
Main useCompression, denoising, preprocessingVisualisation, and essentially nothing else

The warning matters because t-SNE plots are routinely over-read. Do not cluster on t-SNE output, and do not measure anything on it. Its optimisation is free to place well-separated groups at any distance from each other, so the gaps between blobs in a t-SNE plot carry no information about how different those groups actually are. Apparent clusters can also appear in genuinely structureless data at low perplexity — the parameter typically runs 5 to 50 and the picture changes qualitatively across that range, so a single plot at one setting is not evidence of anything. Use it to look, then verify what you saw on the real data.

The pitfalls

Where marks are lost
  • Forgetting to centre the data. Without centring, the first "component" points at the mean and PCA measures distance from the origin instead of variance. This is not a refinement; it makes the output meaningless.
  • Not standardising when the units differ. The largest-unit feature becomes PC1. See the depth box — and note that standardising is also a choice, so say which you made.
  • Assuming high explained variance means the reduction was safe. Worked 3.3b: 56.67% retained, structure destroyed. Variance is a proxy for information, not a synonym.
  • Interpreting a principal component as a real quantity. A component is a weighted combination of features chosen for orthogonality and variance. It need not mean anything, and the sign is arbitrary — w and −w are the same component.
  • Running PCA before clustering as a reflex. Sometimes helpful, sometimes exactly the wrong move. Reduce for visualisation freely; reduce before clustering only with a reason and a check.
  • Fitting PCA on all the data when there is a downstream supervised task. If a test set exists, fit the projection on training data only. Fitting on everything leaks, per 2.1.
  • Reading distances or cluster sizes off a t-SNE plot. Neither is preserved. The plot shows neighbourhoods and nothing else.

Practice

P3.3.1 (direct) — Find the principal components and explained variance ratios for S = [[5, 4], [4, 5]].
(5 − λ)² − 16 = 0 → 5 − λ = ±4 → λ₁ = 9, λ₂ = 1 trace check: 9 + 1 = 10 = 5 + 5 ✓ det check: 9 × 1 = 9 = 25 − 16 ✓ equal diagonals, so by symmetry: w₁ = (1, 1)/√2 with λ₁ = 9 w₂ = (1, −1)/√2 with λ₂ = 1 explained variance: 9/10 = 0.9000 and 1/10 = 0.1000

Correlation is 4/√(5 × 5) = 0.8, and the depth box's shortcut gives (1 + 0.8)/2 = 0.9. ✓ With 90% in one component and a clean gap between 9 and 1, this is a case where reducing to one dimension is well supported — the opposite situation to Worked 3.3b, where the eigenvalues were 9.27 and 7.09 with no gap at all.

P3.3.2 (variation) — Find the components for S = [[9, 3], [3, 1]] and interpret the result.
trace = 10, det = 9 × 1 − 3 × 3 = 9 − 9 = 0 so one eigenvalue is 0 and the other is 10: λ₁ = 10, λ₂ = 0 for λ₁ = 10: (9 − 10)w₁ + 3w₂ = 0 → w₂ = w₁/3 so w ∝ (3, 1); ‖(3,1)‖ = √10 w₁ = (3, 1)/√10 = (0.9487, 0.3162) w₂ = (1, −3)/√10, λ₂ = 0 explained variance: 100% and 0%

A zero eigenvalue means the covariance matrix is singular and the data has no spread in the direction (1, −3) — every point lies exactly on a line through the mean with direction (3, 1), so the second feature is a deterministic function of the first, x₂ = x₁/3 plus a constant.

Here reducing to one dimension is lossless: reconstruction error is exactly zero and nothing is given up. This is the ideal case for PCA and it is also a warning sign about the data — a perfectly redundant feature usually means an error in data collection or a derived column that should not have been included. Note the connection to 2.2: this is exact multicollinearity, which made the normal equations singular there and makes the covariance matrix singular here, for the same underlying reason.

P3.3.3 (interpretation) — A 200-feature dataset is reduced to 10 components capturing 92% of the variance. Clustering the 10-D data gives silhouette 0.61; clustering the original 200-D data gives 0.28. A colleague concludes PCA improved the clustering. Assess.

The comparison is not valid as evidence, because silhouette is not comparable across spaces of different dimension. Distance concentration means that in 200 dimensions all pairwise distances become similar, so a(i) and b(i) converge and every silhouette is pushed toward 0. A rise from 0.28 to 0.61 is largely a property of the dimension count, and you would see much of it even if PCA had projected onto ten random orthogonal directions. That is the control experiment to run.

That said, PCA may genuinely have helped, for a real reason. The discarded 8% of variance is spread across 190 directions, so those directions are individually almost pure noise, and removing them removes noise from the distance computation. Denoising before clustering is a legitimate and common use of PCA. The point is that the silhouette comparison does not demonstrate it.

What would. Check stability: does the 10-D clustering reproduce across bootstrap resamples more consistently than the 200-D one? Compare both against any labels you have that were not used for clustering, using section 3.4's metrics, which do not depend on dimension. Try 5, 10, 20 and 50 components and see whether the result is stable across that range or an artefact of choosing 10. And run the random-projection control, which is one line of code and settles the main question.

Finally, keep Worked 3.3b in view: 92% retained sounds safe and says nothing about whether the discarded 8% contained the separating direction. Check the scree plot for a genuine gap at 10.

P3.3.4 (synthesis) — Using 2.2, 3.1.1 and this section, explain what PCA, k-means and ridge regression have in common in how they handle redundant or low-variance directions.

All three are answering the question "what should I do with a direction in feature space that carries little information", and they give three different answers to it.

PCA discards it outright. Directions are ranked by variance and the tail is deleted, so a low-variance direction contributes nothing to the projection. The decision is made without reference to any task, which is why Worked 3.3b went wrong — low variance was mistaken for low value.

Ridge regression shrinks it. Section 2.2 showed that adding λI to the scatter matrix fixes singularity, and the mechanism is exactly this: a direction with small scatter has its coefficient shrunk hard, because λ is large relative to that direction's own eigenvalue. So ridge does not delete the direction, it distrusts it in proportion to how little data supports it. That is strictly gentler than PCA's cut, and it is why "principal component regression" — PCA then least squares — is generally worse than ridge: it makes a hard yes/no decision where a soft one is available.

k-means is blind to it. Squared Euclidean distance weights every direction equally regardless of variance, so a low-variance direction contributes to the clustering exactly as much as a high-variance one per unit of difference. This is why standardisation matters so much for k-means and why the scaling trap of 2.3.2 recurs here: k-means has no mechanism at all for down-weighting an uninformative feature, and you must do it yourself.

The unifying principle, which is 1.7's: every one of these is a statement about which directions to trust, and the only difference is whether the statement is hard, soft, or absent. Ridge's soft version is usually the best-behaved, which is a general lesson worth carrying into Unit 4, where weight decay is ridge under another name.


3.4

External Evaluation Metrics

Now the outcome column is allowed out. Four metrics that compare a clustering against labels it never saw, all of which must ignore the fact that cluster names are arbitrary.

The question

Sometimes you do have labels, and cluster anyway — to check whether a method works before trusting it on unlabelled data, to see whether the natural structure matches the categories you care about, or because the labels arrived after the clustering was done. How do you score the result?

Accuracy is unavailable, and the reason is worth being precise about. A clustering algorithm returns groups, not names. If it puts the four L students together, it might call that group 1, 2 or 3, and all three answers are equally correct. Comparing cluster numbers to class numbers directly would penalise a perfect clustering for the arbitrary choice of labelling. Every metric in this section must therefore be invariant to relabelling, and that requirement is what shapes all of them.

The intuition

Two ideas, and each gives rise to two metrics.

Count agreeing pairs. Forget names entirely and ask, for every pair of students: did the clustering and the truth agree about whether these two belong together? That is relabelling-invariant automatically, since it never mentions a label. This gives the Rand index and its chance-corrected version.

Measure shared information. How much does knowing a student's cluster tell you about their outcome? That is mutual information from 1.5, and it too is name-blind. This gives NMI, and its decomposition into homogeneity and completeness.

The formal treatment

The contingency table is the starting point for all fournᵢⱼ = number of points in cluster i AND class j aᵢ = row totals (cluster sizes) bⱼ = column totals (class sizes)

Adjusted Rand Index

Pair counting, corrected for chancethe RAND INDEX is (agreements on pairs)/(all pairs), but it is badly behaved: it approaches 1 as n grows even for random clusterings. So it gets adjusted: Σᵢⱼ C(nᵢⱼ, 2) pairs together in BOTH Σᵢ C(aᵢ, 2) pairs together in the CLUSTERING Σⱼ C(bⱼ, 2) pairs together in the TRUTH expected = [Σᵢ C(aᵢ,2) · Σⱼ C(bⱼ,2)] / C(n, 2) max = ½[ Σᵢ C(aᵢ,2) + Σⱼ C(bⱼ,2) ] ARI = ( Σᵢⱼ C(nᵢⱼ,2) − expected ) / ( max − expected ) ARI = 1 perfect ; ARI = 0 no better than random ; ARI < 0 worse than random

Mutual information and NMI

Information shared between clustering K and classes CH(C) = −Σⱼ (bⱼ/n) log(bⱼ/n) entropy of the classes H(K) = −Σᵢ (aᵢ/n) log(aᵢ/n) entropy of the clusters H(C|K) = −Σᵢⱼ (nᵢⱼ/n) log(nᵢⱼ/aᵢ) class entropy remaining once the cluster is known MI = H(C) − H(C|K) = H(K) − H(K|C) symmetric NMI = MI / mean(H(C), H(K)) the mean may be arithmetic or geometric

Homogeneity, completeness and V-measure

The two ways a clustering can be wrong, separatedhomogeneity h = 1 − H(C|K)/H(C) "each cluster contains only members of one class" perfect if no cluster mixes classes. Splitting a class in two does not hurt it. completeness c = 1 − H(K|C)/H(K) "all members of a class are in one cluster" perfect if no class is split. Merging two classes does not hurt it. V-measure = 2hc/(h + c) their harmonic mean

The pairing is deliberate and it is the same structure as precision and recall in 2.4.1, with the same trade-off. Splitting every point into its own cluster gives homogeneity 1 and completeness near 0. Putting everything in one cluster gives completeness 1 and homogeneity 0. V-measure is their F1, and there is a neat identity worth knowing: V-measure is exactly NMI computed with the arithmetic mean, which the worked example below confirms numerically.

Depth — why the Rand index needs adjusting at all

Take the twelve students, ignore the real clusters, and split them into three arbitrary groups of four that each happen to contain two passes and two fails — a clustering with literally no information about the outcome. The contingency table is [[2,2],[2,2],[2,2]].

The unadjusted Rand index for that table is 0.4545, which looks like partial credit and is entirely spurious. The reason is that with three clusters, most pairs of students are in different clusters, and most pairs are also in different classes, so the two "disagree about togetherness" verdicts coincide by sheer arithmetic. The Rand index counts those coincidences as agreements.

The adjustment subtracts what you would expect by chance. Here Σᵢⱼ C(nᵢⱼ,2) = 6 while the expected value is 18 × 30 / 66 = 8.1818, so the numerator is negative and ARI = −0.1379. A negative ARI is the correct verdict: this clustering is slightly worse than random with respect to the outcome.

The general point applies far beyond clustering. A similarity measure with a non-zero baseline is uninterpretable until you know the baseline — exactly the argument for quoting the majority-class rate beside accuracy in 2.4.2, and for Cohen's κ, which is the same chance correction applied to classification agreement.

The worked example

Worked 3.4 — scoring the three-cluster solution against the hidden outcome
all four metrics, by hand
The three clusters are L = {S1,S2,S3,S4}, P = {S5,S6,S7,S8}, A = {S9,S10,S11,S12}. The hidden outcome: S1–S5 and S7 failed, S6 and S8–S12 passed. Compute ARI, MI, NMI, homogeneity, completeness and V-measure.
Step 1 — the contingency table
Clusters against outcomes. Six failed, six passed.
Clusterfailpassrow total aᵢ
L404
P224
A044
column total bⱼ6612

Read the table before computing anything. Clusters L and A are pure — all four members share an outcome. Cluster P is a perfect 2–2 split, so it carries no information about the outcome at all. And both classes are split across two clusters. So we should expect decent homogeneity, poor completeness, and a middling overall score.

Step 2 — ARI
Σᵢⱼ C(nᵢⱼ, 2): C(4,2) + C(0,2) + C(2,2) + C(2,2) + C(0,2) + C(4,2) = 6 + 0 + 1 + 1 + 0 + 6 = 14 Σᵢ C(aᵢ, 2) = 3 × C(4,2) = 3 × 6 = 18 Σⱼ C(bⱼ, 2) = 2 × C(6,2) = 2 × 15 = 30 C(12, 2) = 66 expected = 18 × 30 / 66 = 540/66 = 8.1818 max = (18 + 30)/2 = 24.0 ARI = (14 − 8.1818) / (24.0 − 8.1818) = 5.8182 / 15.8182 = 0.3678
Step 3 — the entropies, in nats
H(K), clusters, three groups of four: = −3 × (4/12) ln(4/12) = −ln(1/3) = ln 3 = 1.0986 H(C), classes, six and six: = −2 × (6/12) ln(6/12) = ln 2 = 0.6931 H(C|K) = −Σᵢⱼ (nᵢⱼ/n) ln(nᵢⱼ/aᵢ): L: (4/12) ln(4/4) = 0 pure, contributes nothing P: (2/12) ln(2/4) + (2/12) ln(2/4) = 2 × (1/6)(−0.693147) = −0.231049 → contributes +0.2310 A: (4/12) ln(4/4) = 0 H(C|K) = 0.2310 H(K|C) = 0.6365 (by the same construction, columns given rows) MI = H(C) − H(C|K) = 0.6931 − 0.2310 = 0.4621 check: H(K) − H(K|C) = 1.0986 − 0.6365 = 0.4621

The H(C|K) = 0.2310 comes entirely from cluster P. That is the arithmetic saying exactly what we read off the table: L and A tell you the outcome with certainty, and P tells you nothing, so one third of the students retain a full bit of uncertainty. Indeed MI = 0.4621 nats = 0.6667 bits = 2/3 of a bit exactly, against H(C) = 1 bit — two thirds of the outcome information has been recovered.

Step 4 — the four normalised scores
homogeneity h = 1 − H(C|K)/H(C) = 1 − 0.2310/0.6931 = 1 − 1/3 = 0.6667 completeness c = 1 − H(K|C)/H(K) = 1 − 0.6365/1.0986 = 0.4206 V-measure = 2(0.6667)(0.4206)/(0.6667 + 0.4206) = 0.560798/1.087300 = 0.5158 NMI, arithmetic mean = 0.4621 / [(0.6931 + 1.0986)/2] = 0.4621/0.8959 = 0.5158 NMI, geometric mean = 0.4621 / √(0.6931 × 1.0986) = 0.5295

Note that V-measure and arithmetic-mean NMI came out identically at 0.5158. That is not a coincidence — they are algebraically the same quantity, which is why libraries report them as equal and why quoting both adds nothing.

ARI 0.3678 · NMI 0.5158 · homogeneity 0.6667 · completeness 0.4206 · V-measure 0.5158
Homogeneity = 2/3 exactly: two of the three clusters are pure, the third is useless.
Completeness is much lower, because both outcomes are split across clusters — the six passes are spread over P and A.
The clustering found real structure that is only partly about passing.

That last sentence is the honest interpretation and it is the interesting one. The algorithm was never trying to predict the outcome; it grouped students by study behaviour, and study behaviour turns out to be related to but not identical with passing. Cluster P — heavy practice, few assignments — is genuinely a coherent group of students, and it happens to contain two who passed and two who did not.

So a low external score is not automatically a bad clustering. It can mean the clustering is wrong, or it can mean the natural structure of the data is not the structure you happened to have labels for. Distinguishing those two requires looking at the clusters, which is why no number in this section replaces that. And if you had wanted to predict passing, you had labels all along and should have used Unit 2.

Worked 3.4b — the same metrics on a worse clustering
homogeneity against completeness
Suppose k-means had been run with k = 2, merging L and P into one cluster of eight and leaving A. Score it and compare.
contingency table: fail pass cluster L∪P 6 2 (a₁ = 8) cluster A 0 4 (a₂ = 4) Σᵢⱼ C(nᵢⱼ,2) = C(6,2) + C(2,2) + C(0,2) + C(4,2) = 15 + 1 + 0 + 6 = 22 Σᵢ C(aᵢ,2) = C(8,2) + C(4,2) = 28 + 6 = 34 Σⱼ C(bⱼ,2) = 30 C(12,2) = 66 expected = 34 × 30/66 = 15.4545 max = (34 + 30)/2 = 32.0 ARI = (22 − 15.4545)/(32.0 − 15.4545) = 6.5455/16.5455 = 0.3956
Three clusters against two, on the same data
Metrick = 3 (correct)k = 2 (merged)direction
ARI0.36780.3956merged is higher
homogeneity0.66670.4591correct is higher
completeness0.42060.5000merged is higher
V-measure0.51580.4787correct is higher
ARI actually prefers the wrong clustering, 0.3956 against 0.3678.
Merging clusters raises completeness (0.4206 → 0.5000) and lowers homogeneity (0.6667 → 0.4591), exactly as the definitions predict.
V-measure, being the harmonic mean, correctly prefers k = 3.

Two lessons. Different external metrics can rank two clusterings differently, so report more than one, and prefer the pair homogeneity and completeness over any single summary — they tell you which way the clustering is wrong, which no single number does.

And ARI's preference here is not a bug. With only two classes, a two-cluster solution has an intrinsic advantage in pair counting, because it makes fewer "these two are apart" claims that the truth can contradict. This is the same phenomenon as F1's dependence on prevalence in 2.4.2: a metric can be perfectly well-defined and still be influenced by the shape of the problem rather than the quality of the answer.

The visualization

The contingency table, live
interactive — k, and the hidden outcome revealed
ARI0.3680 = random
homogeneity0.667clusters are pure
completeness0.421classes are not split
V-measure0.516their harmonic mean
 

Filled markers passed, hollow markers failed — the only figure in this file where colour and outcome appear together, and the reason the colour contract was set up to keep them separate. Slide k upward and watch homogeneity climb toward 1 while completeness falls: more, smaller clusters are purer by construction and split the classes more. That trade-off is the whole content of the pair.

The pitfalls

Where marks are lost
  • Trying to use accuracy. Cluster labels are arbitrary, so accuracy is undefined until you match clusters to classes — and choosing the best matching inflates the score. Use a relabelling-invariant metric.
  • Quoting the unadjusted Rand index. It has a large, k-dependent baseline. The depth box's uninformative clustering scores 0.4545 on Rand and −0.1379 on ARI. Always adjust.
  • Reporting one number. Worked 3.4b: ARI and V-measure disagree on which clustering is better. Homogeneity and completeness together are the most informative pair.
  • Mixing up homogeneity and completeness. Homogeneity punishes mixed clusters; completeness punishes split classes. Splitting a class into two pure clusters leaves homogeneity at 1 and damages completeness.
  • Comparing MI across datasets. Raw mutual information is bounded by min(H(C), H(K)), so it grows with the number of classes and clusters. Normalise before comparing anything.
  • Using external metrics to tune the clustering. If you select k by maximising ARI against labels, you are doing supervised learning with extra steps — and if you then report that ARI, it is a training score. Tune on internal criteria or on a held-out label set.
  • Concluding a low score means a bad clustering. It may mean the data's natural structure is not the structure your labels describe, which is a finding rather than a failure.

Practice

P3.4.1 (direct) — Compute the ARI for the contingency table [[3,1],[1,3]] on n = 8.
Σᵢⱼ C(nᵢⱼ,2) = C(3,2) + C(1,2) + C(1,2) + C(3,2) = 3 + 0 + 0 + 3 = 6 row totals 4, 4 → Σᵢ C(aᵢ,2) = 6 + 6 = 12 col totals 4, 4 → Σⱼ C(bⱼ,2) = 6 + 6 = 12 C(8,2) = 28 expected = 12 × 12/28 = 144/28 = 5.1429 max = (12 + 12)/2 = 12.0 ARI = (6 − 5.1429)/(12.0 − 5.1429) = 0.8571/6.8571 = 0.1250

Six of the eight points are "correctly" placed, which sounds like 75% agreement, and the ARI is 0.125. The gap is the chance correction doing its job: with two clusters and two classes of equal size, a random assignment already gets most pairs right, so 6 out of 8 is barely above the baseline of 5.14. This is exactly why the adjustment exists.

P3.4.2 (variation) — Compute homogeneity and completeness when each of the twelve students is put in their own cluster, and when all twelve are put in one cluster.

Twelve singleton clusters. Each cluster contains one student, so knowing the cluster tells you the outcome exactly: H(C|K) = 0, so h = 1 − 0/H(C) = 1.0000. But each class of six is split across six clusters, so H(K|C) is large. With H(K) = ln 12 = 2.4849 and H(K|C) = ln 6 = 1.7918, completeness is 1 − 1.7918/2.4849 = 0.2789. V-measure = 2(1)(0.2789)/1.2789 = 0.4362.

One cluster of twelve. Knowing the cluster tells you nothing, so H(C|K) = H(C) and h = 0.0000. Completeness needs care here: with a single cluster H(K) = 0 and H(K|C) = 0, so the ratio H(K|C)/H(K) is 0/0 and the formula gives nothing. The convention is to define completeness as 1.0000 in this case, on the grounds that no class has been split — and libraries implement that convention rather than deriving it. V-measure is then 2(0)(1)/(0+1) = 0.0000.

Watch for that 0/0 whenever a degenerate clustering appears. The same thing happens to homogeneity if every point shares one class, since then H(C) = 0. These are not edge cases invented for exams — a clustering that collapses to one cluster is a common real failure, and a metric that returns nan rather than a number is often the first sign of it.

These are the two degenerate extremes, and they show why the pair is needed. Each measure alone can be driven to 1 by a clustering that is obviously worthless, and only their combination resists both. That is precisely the relationship precision and recall have in 2.4.2 — and it is why V-measure is a harmonic rather than arithmetic mean, since the harmonic mean is 0 whenever either component is 0.

P3.4.3 (interpretation) — A clustering of 5,000 patients into 4 groups scores ARI 0.04 against a known diagnosis, but silhouette 0.68. Reconcile these.

There is no contradiction: the two numbers measure different things and both are probably right. Silhouette 0.68 says the four groups are geometrically clean — tight and well separated in feature space. ARI 0.04 says those groups have almost nothing to do with the diagnosis. Both can be true simultaneously, and here they almost certainly are.

The most likely explanation is that the clustering has found real structure that is not the diagnosis. Patient records contain strong, clean structure along axes such as age, sex, site of care, referral route or which instrument recorded the measurements — and any of those can dominate the geometry while being irrelevant to disease. A clustering that separates patients by scanner model will look magnificent on silhouette and score zero against diagnosis. The first thing to do is characterise the four clusters: compute the mean of every feature in each, and the identity of the structure will usually be obvious.

What follows depends on the goal. If the aim was to discover diagnostic subtypes, this is a negative result honestly obtained, and the response is either better features or a supervised model, since the labels exist. If the aim was to find any structure, then discovering that scanner model dominates the variance is a valuable finding — it is a confound that will damage any downstream model, and it was found for free.

What not to do is tune k to raise the ARI. With labels in hand, maximising an external metric is supervised learning, and the resulting score is a training score. If the diagnosis is the target, use Unit 2.

P3.4.4 (synthesis) — Relate homogeneity and completeness to precision and recall from 2.4.1, and ARI to Cohen's κ from the same section. What is the shared structure?

Homogeneity and completeness are precision and recall, generalised. Precision asks what fraction of the points a model put in the positive class actually belong there — a per-prediction purity. Homogeneity asks what fraction of the information in a cluster's membership is accounted for by its class composition — a per-cluster purity. Recall asks what fraction of the actual positives were found; completeness asks whether a class's members ended up together. Both pairs have the same two degenerate extremes: predicting positive for one certain case maximises precision, and a singleton clustering maximises homogeneity; predicting positive for everything maximises recall, and one big cluster maximises completeness. Both pairs are combined by a harmonic mean — F1 and V-measure — for the same reason, that the harmonic mean refuses to reward either extreme.

ARI is Cohen's κ, applied to pairs instead of points. Both have the identical form (observed − expected) / (maximum − expected). Both exist because the raw agreement rate has a large baseline that depends on the marginal distributions rather than on the quality of the agreement. Both are 0 at chance, 1 at perfection, and negative when performance is worse than chance. The only difference is the unit of agreement: κ counts points on which two labellings agree, ARI counts pairs of points on which two partitions agree about togetherness — and ARI must use pairs precisely because cluster names are arbitrary, whereas κ can use points because class names are not.

The shared structure, stated once. Every honest evaluation metric in this course does one of two things: it subtracts a baseline so that 0 means "no skill", or it combines two quantities that can each be gamed alone. Accuracy does neither, which is why it needed the majority-class rate quoted beside it in 2.4.2; the Rand index does neither, which is why it needed adjusting. Once you see the pattern you can predict what a new metric must look like before you read its definition.


3.5

Hyperparameter Tuning Without Labels

Every method in this unit has knobs, and none of them can be set by cross-validation. What is actually available, and how to report it honestly.

The question

Section 2.1 gave a clean protocol: split the data, tune on validation, look at test once. That protocol needs labels at every stage. Remove them and the protocol collapses — so what replaces it?

What there is to tune

The hyperparameters of this unit, and how each is chosen
MethodHyperparametersHow to choose
k-meansk; n_init; init schemek from section 3.2's indices plus stability. n_init and k-means++ are not really tunable — more restarts are always at least as good, so set them as high as you can afford.
Hierarchicallinkage; cut height or kLinkage from what you know about cluster shape, not by search — single for elongated, Ward or complete for compact. Cut at the widest gap in merge heights.
DBSCANε; minPts; the metricminPts from dimension, commonly 2d. ε from the knee of the k-distance plot.
GMMk; covariance type; reg_covarBIC or AIC — the only genuinely principled selection in the unit, because a GMM is a probability model.
PCAnumber of components; standardise or notExplained-variance threshold or scree elbow; standardise when units are arbitrary. If a supervised task follows, tune the component count against that task's validation score, which is a real criterion.
t-SNEperplexity; learning rate; iterationsRun several perplexities between 5 and 50 and only trust structure that appears in all of them.

The three things that actually work

1. Stability under resampling. This is the closest genuine analogue of cross-validation, and it is under-used. Draw bootstrap resamples, cluster each, and measure how much the partitions agree with each other — using the adjusted Rand index of 3.4, computed between two clusterings rather than against truth. A k whose partition reproduces across resamples is describing something in the data; a k that gives a different answer every time is describing the sample. Note carefully what this measures: reproducibility, not correctness. A systematically wrong clustering can be perfectly stable.

2. A null baseline — the gap statistic. Section 3.2's depth box noted that a silhouette of 0.5 is meaningless without knowing what random data scores. The gap statistic supplies exactly that.

The gap statisticfor each candidate k: Wₖ = log WCSS on the real data E[Wₖ] = mean log WCSS over B datasets sampled uniformly from the real data's bounding box (or its PCA-aligned box) Gap(k) = E[Wₖ] − Wₖ choose the smallest k such that Gap(k) ≥ Gap(k+1) − sₖ₊₁ where s is the standard error of the reference runs crucially, this CAN select k = 1 — the only method here that can conclude the data has no cluster structure at all.

That last property is why the gap statistic is worth knowing. Silhouette, Davies–Bouldin and Calinski–Harabasz are all undefined at k = 1, so none of them can ever tell you not to cluster. The gap statistic can, and on structureless data it should.

3. Information criteria, where a likelihood exists. BIC and AIC for a GMM, as in 3.1.4. This is the only method in the unit with a real theoretical justification for its penalty, and it is a strong argument for reaching for a GMM when the choice of k genuinely matters.

Depth — the limitation you cannot engineer around

In supervised learning, "better" has an external referent: predictions are compared against outcomes that exist independently of the model. Every honest evaluation in Unit 2 traces back to that fact.

Unsupervised learning has no such referent. A clustering is not true or false; it is a summary, and summaries are judged by usefulness for a purpose. Which means the purpose has to come from outside the data, and no amount of index arithmetic can supply it. Two clusterings of the same customers — one by spending pattern, one by geography — can both be geometrically excellent, and which is better depends entirely on what you are going to do next.

This is not a gap in current technique that better methods will close. It is a consequence of the problem statement. The practical response is a habit rather than an algorithm: state the purpose before clustering, choose the features that serve it, run more than one method, believe the structure only where they agree, and report what you did rather than only what you found. That is less satisfying than a validation curve, and it is what the honest version of this work looks like.

Practice

P3.5.1 (direct) — You have 8 features and plan to use DBSCAN. Give starting values for both parameters and say how you would refine ε.

minPts: the common heuristic is 2d = 16, with d + 1 = 9 as the floor. Start at 16 and lower it if too much is labelled noise.

ε: do not guess. Standardise all 8 features first, since a single ε applies to all of them jointly. Then for every point compute the distance to its 16th nearest neighbour, sort those distances descending, and plot. The curve will be flat over most of its length and rise sharply at the left-hand end where the noise points sit; the knee is the value of ε that separates dense from sparse, and that is the starting point.

Then check the result rather than accepting it: what fraction is noise, how many clusters, and are they of plausible sizes? And with 8 features, be alert to the concentration problem of 3.1.3's depth box — if the k-distance curve has no knee, that is the symptom, and reducing dimension first is the response.

P3.5.2 (variation) — Design a stability check for the choice of k on the twelve students, and say what you would expect it to find.
for k in 2, 3, 4, 5: repeat B = 200 times: draw two bootstrap resamples of the 12 students cluster each with k-means, n_init = 10 for the students appearing in BOTH resamples, compute the ARI between the two partitions report the mean and spread of those ARIs choose the largest k whose mean ARI stays high (say above 0.8)

What to expect here. k = 3 should be extremely stable, close to ARI 1.0, because the three clusters are separated by gaps of 6 and 6.7 against within-cluster distances of at most 2 — no resample that retains a few members of each group will fail to find them. k = 2 should also be stable, reliably merging L and P, since that merge is forced by geometry. k = 4 and k = 5 should be visibly unstable: the fourth cluster is made by splitting a diamond, and which diamond gets split and along which diagonal will vary from resample to resample.

So stability should select 3 — agreeing with all four indices in 3.2. Two caveats worth stating. With n = 12 a bootstrap resample contains only about 8 distinct students, so the estimates will be noisy and the whole exercise is a demonstration rather than evidence. And stability would also endorse k = 2, which is not wrong so much as coarser — stability tells you which answers are reproducible, not which is best, so it belongs alongside the indices rather than instead of them.

P3.5.3 (interpretation) — A report states: "We used k-means with k = 7, chosen to maximise silhouette, giving 0.42. The clusters represent seven distinct customer personas." Critique it.

Three problems, in increasing order of seriousness.

The number is unbaselined. A silhouette of 0.42 is around what uniformly random points in a box score at moderate k. Without a gap statistic or a comparison against a null model, 0.42 is not evidence of structure — it may be evidence that k-means partitions anything. That single number is doing all the work in this report and it cannot bear the weight.

No stability or corroboration is reported. Nothing tells us whether the same seven groups appear on a resample, whether other values of k scored nearly as well, or whether another method agrees. If silhouette at k = 6 were 0.41, the choice of 7 is noise. Report the whole curve, not its argmax.

And "represent seven distinct personas" is not something the analysis can support. This is the deepest issue. k-means partitions any dataset into seven convex regions whether or not seven groups exist; producing seven clusters is what the algorithm does, not a finding. Calling them personas asserts that they are meaningful, coherent and actionable, and none of those was tested. Also missing: whether features were standardised, how many restarts were used, and what the seven clusters actually differ on — without cluster profiles the reader cannot judge any of it.

A defensible version. "Features standardised; k-means with 50 restarts. Silhouette across k = 2 to 12 peaked broadly at 6 to 8 with values 0.39 to 0.42, and the gap statistic favoured 3. Bootstrap stability was high for k = 3 (mean ARI 0.91) and moderate for k = 7 (0.62). We report k = 7 for operational reasons, with cluster profiles in Appendix B, and note that the geometric evidence for seven groups specifically is weak."

P3.5.4 (synthesis) — Compare tuning here with tuning in 2.1. Which techniques transfer, which have analogues, and which are simply unavailable?

Transfers unchanged. Grid and random search over the hyperparameter space; the discipline of not letting a final reported number come from data used to choose the setting; and the practice of reporting the whole search curve rather than only its optimum. All of these are about procedure rather than about labels, so they survive intact.

Has an analogue. Cross-validation becomes stability analysis. Both resample the data and ask whether the conclusion survives, but they measure different things: cross-validation measures expected performance against truth, stability measures reproducibility of a partition. Regularization becomes an information criterion — BIC's p ln n penalty plays the role that ridge's λ‖w‖² played in 2.2, penalising complexity, with the difference that BIC's penalty is derived rather than tuned. And the majority-class baseline of 2.4.2 becomes the gap statistic's null reference, serving the identical purpose: telling you what a useless answer would score.

Simply unavailable. A held-out performance estimate, because there is no performance to estimate. A learning curve against training-set size, since there is no error to plot. Early stopping on a validation metric. And most consequentially, the guarantee that a better validation score means a better model — there is no quantity here that plays the role validation accuracy plays there.

The one-sentence version. Supervised tuning asks "which setting predicts held-out labels best" and gets a real answer; unsupervised tuning asks "which setting produces a partition that is geometrically clean, reproducible, and better than what random data would give" — three weaker questions that together are the best available substitute, and a substitute is what they remain.


R1

Cheat Sheet

Every formula in this unit, plus the spine's numbers so you can check your arithmetic against a case you have already seen worked.

3.1.1 k-means

WCSS = Σₖ Σᵢ∈Cₖ ‖xᵢ − μₖ‖²
ASSIGN to nearest centroid, UPDATE to the mean, repeat.
The mean is optimal because the loss is squared; absolute loss gives the median.
TSS = WCSS + BSS always.
Converges to a LOCAL minimum. Use k-means++ and n_init ≥ 10.
Voronoi regions → convex clusters only. Standardise first.

3.1.2 Hierarchical

Single = min pair → chains, follows shapes
Complete = max pair → compact, outlier-sensitive
Average = mean pair → the compromise
Ward = increase in WCSS → k-means' objective, greedily
Merges are irreversible. n − 1 merges always.
Cut at the WIDEST GAP between consecutive heights. Leaf order means nothing.
O(n²) memory — unusable past ~10⁴ points.

3.1.3 DBSCAN

CORE |N(p)| ≥ minPts, counting itself
BORDER within ε of a core point, not core
NOISE neither
Only CORE points propagate a cluster.
Finds k itself; handles any shape; flags outliers.
Fails when densities differ — one global ε. Border points depend on visit order.
Choose ε from the k-distance plot knee; minPts ≈ 2d.

3.1.4 Gaussian mixtures

p(x) = Σₖ πₖ N(x | μₖ, Σₖ)
E-step: γᵢₖ = πₖNₖ / Σⱼ πⱼNⱼ — rows sum to 1
M-step: Nₖ = Σᵢγᵢₖ, πₖ = Nₖ/n, μₖ and Σₖ weighted by γ
k-means = GMM with hard γ, equal spherical fixed Σ, and is its σ² → 0 limit.
Likelihood is UNBOUNDED — regularize the covariance.
BIC = −2 ln L + p ln n · AIC = −2 ln L + 2p

3.2 Silhouette

s(i) = (b − a) / max(a, b)
a = mean distance to own cluster, b = to the nearest other cluster
+1 well placed · 0 on a boundary · negative probably misassigned
Needs k ≥ 2. Report the DISTRIBUTION, not just the mean.
Random points in a box score 0.4–0.5, so a bare value proves nothing.

3.2 DB and CH

DB = (1/k) Σₖ maxⱼ≠ₖ (Sₖ + Sⱼ)/Mₖⱼ   LOWER is better
Sₖ = mean distance to own centroid, Mₖⱼ = centroid separation
CH = [BSS/(k−1)] / [WCSS/(n−k)]   HIGHER is better — an F-statistic
WCSS and BSS/TSS are MONOTONE in k and cannot select it.
All four indices are biased toward compact spherical clusters.

3.3 PCA

Centre, optionally standardise, then Sw = λw
Components are eigenvectors of the covariance matrix, ordered by eigenvalue.
Variance along component j is λⱼ; explained ratio λⱼ/Σλ
reconstruction error = (n−1)Σⱼ>ᵐ λⱼ — the variance you dropped
2×2 checks: Σλ = trace, ∏λ = det
Standardised pair: λ = 1 ± r, eigenvectors at 45°, explained (1+r)/2

3.3 t-SNE and UMAP

Non-linear, stochastic, for VISUALISATION only.
Preserve local neighbourhoods; do not preserve distances between clusters or cluster sizes.
Never cluster on the output. Never measure on the output.
Perplexity 5–50 — run several and trust only what appears in all of them.
t-SNE cannot embed new points; UMAP approximately can.

3.4 ARI

ARI = (ΣC(nᵢⱼ,2) − E) / (max − E)
E = ΣC(aᵢ,2)·ΣC(bⱼ,2)/C(n,2)   max = ½[ΣC(aᵢ,2) + ΣC(bⱼ,2)]
1 perfect · 0 chance · negative worse than chance
Counts PAIRS, so it ignores cluster names.
Same (obs − exp)/(max − exp) form as Cohen's κ.
Unadjusted Rand has a large baseline — never quote it.

3.4 Entropy metrics

MI = H(C) − H(C|K) = H(K) − H(K|C)
homogeneity h = 1 − H(C|K)/H(C) — clusters are pure
completeness c = 1 − H(K|C)/H(K) — classes are not split
V = 2hc/(h+c), and V ≡ NMI with the arithmetic mean
Singletons: h = 1, c → 0. One cluster: h = 0, c = 1 by convention.
Precision/recall's structure, in entropy form.

3.5 Choosing settings

Stability — cluster bootstrap resamples, compare with ARI. Measures reproducibility, NOT correctness.
Gap statisticGap(k) = E[log Wₖ] − log Wₖ against a uniform reference. The only method that can select k = 1.
BIC / AIC — only where a likelihood exists, i.e. a GMM.
Cross-validation is unavailable: no labels, so nothing to score.

Which method when

k-means compact similar-sized blobs, need a reusable model, large n
Hierarchical small n, the nesting itself is informative, want to see which k are supported
DBSCAN unknown shapes, outliers matter, low dimension
GMM overlapping or elliptical clusters, want soft assignments or a principled k
Run more than one. Believe the structure where they agree.

The spine, end to end

Twelve students at (1,2) (3,2) (2,1) (2,3) (7,2) (9,2) (8,1) (8,3) (4,8) (6,8) (5,7) (5,9), plus S13 at (9,5). Every number below is derived in this file from those coordinates alone.

Reproduce this column and you have the unit
QuantityValueSection
Grand mean(5, 4)3.0
Scatter S₁₁, S₂₂, S₁₂78, 102, 03.0
Total scatter TSS1803.0
Centroids at k = 3(2,2), (8,2), (5,8)3.1.1
WCSS at k = 3, and BSS12 and 1683.1.1
BSS/TSS at k = 30.93333.1.1
WCSS from bad seeds S1,S2,S3100.00003.1.1
Data-point starts reaching the optimum192 of 2203.1.1
WCSS at k = 1…6180, 84, 12, 10, 8, 63.2
Single linkage: within, then L+P, then A1.4142, 4.0000, 5.00003.1.2
Complete linkage: pairs, diamonds, L+P, A1.4142, 2.0000, 8.0000, 8.54403.1.2
DBSCAN ε = 1.5, minPts = 33 clusters, 12 core, S13 noise3.1.3
DBSCAN ε = 1.5, minPts = 40 clusters, all 13 noise3.1.3
S13's squared distances to the centroids58, 10, 253.1.3
Cost of forcing S13 into Pcentroid → (8.2, 2.6), SSE 4 → 123.1.3
GMM responsibilities for S13 at σ² = 40.0021, 0.8652, 0.13273.1.4
a(i), identical for all twelve1.60953.2
Silhouette at k = 30.73683.2
Davies–Bouldin at k = 30.32163.2
Calinski–Harabasz at k = 363.00003.2
PCA eigenvalues9.2727 and 7.09093.3
PC1 explained variance0.56673.3
Cluster centroids projected on PC1−2.0, −2.0, +4.0 — L and P collapse3.3
Reconstruction error, PC1 vs PC278 vs 1023.3
Contingency table against the outcome[[4,0], [2,2], [0,4]]3.4
ARI0.36783.4
Homogeneity, completeness, V-measure0.6667, 0.4206, 0.51583.4
Mutual information0.4621 nats = 2/3 bit3.4

R2

Mixed Self-Test

Ten questions, unlabelled by section. Attempt all before opening any solution.

Q1. Four points sit at (0,0), (4,0), (0,3), (4,3). Run k-means with k = 2 seeded at (0,0) and (4,3). Give the clusters, the centroids and the WCSS. Then say what happens if the seeds are (0,0) and (4,0).
seeds (0,0) and (4,3). Squared distances: (0,0): 0 vs 16+9 = 25 → cluster 1 (4,0): 16 vs 9 → cluster 2 (0,3): 9 vs 16 → cluster 1 (4,3): 25 vs 0 → cluster 2 clusters {(0,0), (0,3)} and {(4,0), (4,3)} centroids (0, 1.5) and (4, 1.5) each point is 1.5 from its centroid → WCSS = 4 × 2.25 = 9 seeds (0,0) and (4,0): (0,0)→1, (4,0)→2, (0,3): 9 vs 25 →1, (4,3): 25 vs 9 →2 the SAME partition, centroids (0,1.5) and (4,1.5), WCSS = 9

Both seedings converge to the same answer, which is the split along the longer dimension — the rectangle is 4 wide and 3 tall, so cutting vertically leaves less residual scatter. Check the alternative: splitting horizontally into {(0,0),(4,0)} and {(0,3),(4,3)} gives centroids (2,0) and (2,3) with each point 2 from its centroid, so WCSS = 16. Worse, as expected.

Q2. A point has a(i) = 3.0 and mean distances 3.5 and 9.0 to the two other clusters. Compute its silhouette and interpret. What would s(i) be if the nearest other cluster were at 2.0 instead?
b = min(3.5, 9.0) = 3.5 s = (3.5 − 3.0)/max(3.0, 3.5) = 0.5/3.5 = +0.1429 with b = 2.0: s = (2.0 − 3.0)/max(3.0, 2.0) = −1.0/3.0 = −0.3333

The first value is weakly positive: the point is on a boundary. It is in the right cluster, but only just, and its own cluster is barely tighter around it than the neighbouring one. A silhouette plot full of bars near 0.14 says the clusters are touching rather than separated.

The second is clearly negative and means the point is closer on average to another cluster than to its own — almost certainly misassigned. Note that the denominator switched from b to a, which is what keeps s within [−1, +1]. Note also that the far cluster at 9.0 never entered either calculation: silhouette only ever looks at the nearest rival.

Q3. Six points lie at 0, 1, 2, 10, 11, 30 on a line. Apply DBSCAN with ε = 1.5, minPts = 2, then with ε = 1.5, minPts = 3. Explain the difference.
neighbourhoods within 1.5, INCLUDING the point itself: 0: {0,1} |N| = 2 10: {10,11} |N| = 2 1: {0,1,2} |N| = 3 11: {10,11} |N| = 2 2: {1,2} |N| = 2 30: {30} |N| = 1 minPts = 2: core = {0, 1, 2, 10, 11}, 30 is noise clusters {0,1,2} and {10,11}, noise {30} minPts = 3: core = {1} only cluster grown from 1 = {0, 1, 2}, with 0 and 2 as BORDER points 10 and 11 are not core and not within ε of any core point → NOISE cluster {0,1,2}, noise {10, 11, 30}

Raising minPts by one destroyed a real cluster. {10,11} is a genuine pair, well separated from everything else, and it vanished because two points can never satisfy a three-point density requirement. This is Worked 3.1.3b's failure at minPts = 4 in miniature, and it is why minPts should be set from the dimensionality rather than nudged until the output looks nice.

Note also that 0 and 2 changed status from core to border without moving. Their cluster membership survived only because 1 remained core and could reach them.

Q4. Find the principal components of S = [[10, 6], [6, 10]], the explained variance ratios, and the reconstruction error per point from keeping one component.
(10 − λ)² − 36 = 0 → 10 − λ = ±6 → λ₁ = 16, λ₂ = 4 trace check: 16 + 4 = 20 = 10 + 10 ✓ det check: 16 × 4 = 64 = 100 − 36 ✓ equal diagonals → eigenvectors forced to 45°: w₁ = (1,1)/√2 with λ = 16 w₂ = (1,−1)/√2 with λ = 4 explained: 16/20 = 0.8000 and 4/20 = 0.2000 reconstruction error per point from keeping PC1 = λ₂ = 4

Cross-check with the shortcut: correlation is 6/√(10 × 10) = 0.6, and (1 + 0.6)/2 = 0.8. ✓ With 80% in one component and eigenvalues of 16 against 4, this is a case where reducing to one dimension is reasonable — unlike the spine, where 9.27 against 7.09 offered no gap at all and reduction destroyed the clusters.

Q5. A clustering produces the contingency table [[5,0],[0,5]] on n = 10. Compute ARI, homogeneity, completeness and V-measure. Then do the same for [[5,5]], a single cluster.
TABLE [[5,0],[0,5]] — a perfect clustering: ΣC(nᵢⱼ,2) = C(5,2) + C(5,2) = 10 + 10 = 20 ΣC(aᵢ,2) = 20 ΣC(bⱼ,2) = 20 C(10,2) = 45 expected = 20 × 20/45 = 8.8889 max = 20 ARI = (20 − 8.8889)/(20 − 8.8889) = 1.0000 H(C|K) = 0 → h = 1.0000 H(K|C) = 0 → c = 1.0000 V = 1.0000 TABLE [[5,5]] — one cluster: ΣC(nᵢⱼ,2) = 10 + 10 = 20 ΣC(aᵢ,2) = C(10,2) = 45 ΣC(bⱼ,2) = 20 expected = 45 × 20/45 = 20 max = (45 + 20)/2 = 32.5 ARI = (20 − 20)/(32.5 − 20) = 0.0000 h = 0.0000, c = 1.0000 by convention, V = 0.0000

The single-cluster case is the sanity check every one of these metrics must pass, and ARI passes it exactly: the observed pair count equals the expected pair count, so the numerator is precisely zero. A metric that gave partial credit for putting everything in one bucket would be useless, which is exactly the criticism of the unadjusted Rand index — it scores this table 20/45 = 0.4444.

Q6. A two-component spherical GMM has π = (0.5, 0.5), means (0,0) and (6,0), and shared σ². At what point on the x-axis is the responsibility exactly 0.5 for each, and does the answer depend on σ²? What if π = (0.8, 0.2)?
equal weights: γ₁ = γ₂ requires the two exponents equal, so d₁² = d₂² x² = (x − 6)² → 0 = −12x + 36 → x = 3 the midpoint, and INDEPENDENT of σ² weights (0.8, 0.2): 0.8 exp(−x²/2σ²) = 0.2 exp(−(x−6)²/2σ²) ln 4 = [x² − (x − 6)²]/(2σ²) = (12x − 36)/(2σ²) x = 3 + σ² ln4 / 6 = 3 + 0.2310 σ² now it DOES depend on σ²: at σ² = 1, x = 3.231; at σ² = 9, x = 5.079

With equal weights the decision boundary is the perpendicular bisector regardless of spread, which is exactly k-means' boundary — another way of seeing that k-means is a GMM with equal weights and shared spherical covariance. Unequal weights shift the boundary toward the less common component, and the shift grows with σ², because a larger spread makes the distance evidence weaker relative to the prior. That is Bayes' theorem behaving exactly as 2.3.6 said it would.

Q7. On a 500-point dataset, silhouette gives 0.71 at k = 2 and 0.44 at k = 5. Bootstrap stability gives mean ARI 0.55 at k = 2 and 0.93 at k = 5. Which k would you report and why?

The two criteria disagree, and the disagreement is informative rather than a tie to be broken. Silhouette says the two-cluster partition is geometrically cleaner. Stability says the five-cluster partition is the one that reproduces — resample the data and you get the same five groups 93% of the time, whereas the two-group answer changes substantially between resamples.

The most likely explanation is hierarchical structure. The data has five real groups arranged in two loose super-groups. Silhouette prefers k = 2 because the super-groups are further apart, so b(i) is large; stability prefers k = 5 because the five groups are the reproducible unit while the boundary between super-groups is arbitrary and moves with the sample. A stability of 0.55 at k = 2 is genuinely poor and is the stronger signal here, since a clustering that does not survive resampling is not describing the population.

What to report. Both, with the structure made explicit: run hierarchical clustering to check whether the five groups nest inside the two, and if they do, report the hierarchy rather than a single k. If forced to one number, k = 5 — reproducibility is the more demanding test, and 0.44 is a perfectly ordinary silhouette for five clusters while 0.55 stability is a red flag. And add the gap statistic, which will say whether either beats a null model at all.

Q8. Explain why running PCA to two components and then k-means can give a different answer from running k-means on the full data, and give one case where the PCA step helps and one where it hurts.

Why they differ. k-means minimises squared Euclidean distance, which sums every feature's contribution. Projecting onto two components changes those distances: any difference lying in the discarded directions vanishes entirely, so two points far apart in the full space can be adjacent after projection. Since the distances change, the partition minimising WCSS changes too.

Where it helps. High dimension with most directions carrying noise. With 500 features of which 10 are informative, the 490 noise directions each add a small random amount to every pairwise distance; summed, they can swamp the real signal, and this is the concentration problem of 3.1.3's depth box. Projecting onto the top components removes most of that noise, and the clustering improves genuinely rather than as an artefact.

Where it hurts. Worked 3.3b, exactly. The discarded direction was the one separating two of the three clusters, so PCA merged them before k-means ever ran — and it did so while retaining 56.67% of the variance, which by its own criterion was the optimal choice. The danger is that this failure is silent: the clustering that follows looks fine, and nothing in the output says a cluster was destroyed upstream.

The distinguishing question is whether the discarded variance is noise or structure, and variance alone cannot tell you. Check the scree plot for a genuine gap; if the eigenvalues decline smoothly there is no safe cut. And cluster both ways — if the answers agree, the reduction was harmless.

Q9. Single linkage on 8 points gives merge heights 0.5, 0.6, 0.6, 0.7, 0.8, 4.2, 4.4. Complete linkage on the same data gives 0.5, 0.9, 1.1, 1.4, 1.9, 7.0, 9.5. How many clusters, and which dendrogram supports the answer more strongly?
single: gaps between consecutive heights 0.1, 0.0, 0.1, 0.1, 3.4, 0.2 largest gap before merge 6 → cut there, leaving 3 clusters (8 points, 5 merges done) complete: gaps 0.4, 0.2, 0.3, 0.5, 5.1, 2.5 largest gap in the same place → also 3 clusters

Both agree on three, which is reassuring — agreement between linkages is a genuine robustness check, since the two methods have opposite biases.

Complete linkage supports it more strongly, and in two distinct ways. Its decisive gap is 5.1 against single's 3.4 in absolute terms, and more tellingly the ratio of the first between-cluster merge to the last within-cluster merge is 7.0/1.9 = 3.7 for complete against 4.2/0.8 = 5.25 for single. So on the ratio measure single linkage looks better, which is a reminder to say which measure you are using. The stronger argument for complete here is its final merge at 9.5 against 7.0: it also separates the top two clusters decisively, whereas single linkage's last two merges at 4.2 and 4.4 are nearly identical, meaning the three-cluster and two-cluster solutions are almost equally supported. That near-tie is exactly the chaining signature of 3.1.2.

Q10. A team clusters 30,000 job applicants into 5 groups to route applications. Silhouette 0.58, stability ARI 0.88. One cluster is 71% one ethnic group against a 22% base rate. What should happen next?

The clustering is technically sound and that is not the relevant question. Silhouette 0.58 and stability 0.88 say the five groups are real and reproducible. Neither number says anything about whether routing applicants by them is acceptable, and the ethnic concentration means it very likely is not.

The mechanism is 2.6's, and clustering does not escape it. Nobody fed ethnicity to the algorithm, and it made no difference — features like postcode, school, previous employer and phrasing are all correlated with it, so the geometry reproduces the demographic structure without ever naming it. That is fairness through unawareness failing exactly as 2.6 said it would, and if that cluster is routed differently, applicants receive different treatment by ethnicity through a proxy.

What to do. Audit the routing outcomes by group using 2.6's metrics — selection rate, and if any downstream outcome is observable, recall and precision by group. Identify which features drive the concentrated cluster, since the answer is usually one or two proxies that can be removed or coarsened. Ask whether clustering is the right tool at all: if the goal is to route applications well, that is a supervised problem with a measurable outcome and Unit 2's machinery, including its fairness constraints, applies. And check the legal position, because in many jurisdictions this is disparate impact regardless of intent.

What not to do is treat the internal metrics as a defence. "Silhouette 0.58, stability 0.88" describes geometry. The applicants are people, the clusters determine what happens to them, and no unsupervised metric in this unit is capable of noticing that.


R3

Where This Goes Next

Half the course is behind you. Everything after this point is representation learning, which is this unit's ideas with the linear restriction removed.

What Unit 3 established, in one paragraph

Four ways to find groups with no answer key, run on the same twelve students, all agreeing on three clusters — and that agreement is the strongest evidence available when there is nothing to validate against. Then the harder half: four indices that measure whether a partition is geometrically tidy, none of which can tell you whether it is right, all biased toward the compact spherical shapes k-means already prefers, and none able to rule out that there are no clusters at all. Then PCA, derived from a one-line Lagrangian, applied to the spine, and shown to discard exactly the direction that mattered while optimally retaining variance. Then the metrics that grade a clustering against labels it never saw, which required abandoning accuracy because cluster names are arbitrary. And underneath all of it, a limitation that is structural rather than technical: without labels there is no external referent for "better", so the purpose has to be supplied from outside the data.

Unit 3 → the rest of the course
From hereReappears as
3.1.1 k-means and the Voronoi pictureVector quantisation in Unit 5's discrete representations, and the nearest-centroid step inside embedding lookups. The convexity limitation is also the clearest motivation for non-linear methods.
3.1.4 EM and latent variablesThe conceptual ancestor of every latent-variable model in Unit 5. A variational autoencoder is EM with a neural network doing the E-step, and the responsibility γ becomes the posterior over a learned latent code.
3.1.4 Softmax over negative distancesLiterally the attention mechanism's normalisation, and the output layer of every classifier in Units 4 and 5.
3.2 Selecting complexity without a validation scoreRecurs whenever a deep model is trained without labels — Unit 5's pre-training has exactly this problem, and solves it by inventing a supervised proxy task.
3.3 PCA as optimal linear reconstructionAn autoencoder with linear activations and squared loss is PCA. Unit 5 replaces the linear map with a network, which is the single clearest statement of what deep learning added.
3.3 Variance is not informationThe permanent caution about learned representations. A model can compress beautifully and discard the thing you needed.
3.4 Metrics invariant to arbitrary labellingEvaluating any model whose output has no canonical naming — topic models, learned embeddings, and the discovered-structure half of Unit 6's state abstractions.
3.5 No external referent for "better"Reinforcement learning's central difficulty in Unit 6, where the reward signal is the substitute for labels and designing it badly is the standard failure.
Before you move on

Eight things you should be able to do from a blank page. Run k-means by hand for two iterations and compute WCSS. Decompose total scatter into within and between and check they sum. Build both single- and complete-linkage dendrograms from a distance matrix and cut at the widest gap. Classify every point as core, border or noise for given ε and minPts. Compute one E-step of a spherical GMM. Compute a silhouette, a Davies–Bouldin and a Calinski–Harabasz, and state which direction each is good in. Find the eigenvalues and eigenvectors of a 2×2 covariance matrix and give the explained variance. And build a contingency table and compute ARI, homogeneity and completeness from it.

If any is shaky, that section's practice ladder is the fastest repair. Unit 4 assumes the softmax of 3.1.4 and the gradient descent of Unit 1.

Further reading

  • Géron, Hands-On Machine Learning, 3rd ed., ch. 8–9 — the prescribed textbook. Chapter 8 is dimensionality reduction including PCA and its variants; chapter 9 covers k-means, DBSCAN and Gaussian mixtures with worked code. The closest match to this unit's scope.
  • Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, ch. 14 — the rigorous treatment of unsupervised learning, including the gap statistic in section 14.3.11 and a careful account of why cluster validation is hard.
  • Bishop, Pattern Recognition and Machine Learning, ch. 9 and 12 — the standard derivations for EM and for PCA. Chapter 9 derives the k-means-as-limiting-case result properly; chapter 12 gives PCA from three different starting points, all reaching Sw = λw.
  • Ester, Kriegel, Sander and Xu (1996) — the original DBSCAN paper. Short, readable, and the definitions of core, border and density-reachability are clearer in the original than in most textbook restatements.
  • Rousseeuw (1987) — the paper that introduced silhouettes, and still the best explanation of why the per-point plot matters more than the average.
  • Wattenberg, Viégas and Johnson, "How to Use t-SNE Effectively" (Distill, 2016) — interactive and genuinely essential before you read a t-SNE plot. It demonstrates the failure modes of section 3.3's warning far better than prose can.
CSUC301 Machine Learning · Unit 3 of 6 · Unsupervised Learning · CO2, CO3
Spine: twelve students in three diamond clusters at (2,2), (8,2) and (5,8), plus S13 at (9,5) who belongs to none of them. Total scatter 180 splits into 12 within and 168 between. Every numerical value in this file was computed rather than estimated, and every widget was driven through its range and checked against the printed worked examples.
Previous: Unit 2B — Evaluation & Responsible AI · Next: Unit 4 — Neural Networks