Python helpers — run once, the checks below reuse them
import numpy as npfrom scipy.cluster.hierarchy import linkage, fclusterfrom sklearn.cluster import DBSCANdef lloyd(X, mu): """Lloyd's k-means from given seeds. Returns (labels, centroids, J).""" X2 = np.asarray(X, float).reshape(len(X), -1); mu2 = np.asarray(mu, float).reshape(len(mu), -1) while True: a = np.argmin(((X2[:, None] - mu2[None])**2).sum(-1), axis=1) # assign new = np.array([X2[a == j].mean(0) for j in range(len(mu2))]) # update if np.allclose(new, mu2): break mu2 = new J = sum(((X2[a == j] - mu2[j])**2).sum() for j in range(len(mu2))) return a, mu2.squeeze(), JJsq = lambda parts: sum(((np.array(p, float) - np.mean(p))**2).sum() for p in parts) # 1-D squared lossdef cluster_F(T): # T = contingency table (rows categories, cols clusters) T = np.asarray(T, float); r, s, N = T.sum(1), T.sum(0), T.sum(); Fi = [] for i in range(len(r)): f = [2*(T[i,j]/r[i])*(T[i,j]/s[j]) / (T[i,j]/r[i] + T[i,j]/s[j]) for j in range(len(s)) if T[i,j]] Fi.append(max(f)) return np.round(Fi, 4), round(float((r / N * Fi).sum()), 4)def NMI(T): # bits; returns MI, E(R), E(S), NMI T = np.asarray(T, float); N, r, s = T.sum(), T.sum(1), T.sum(0) MI = sum(T[i,j]/N*np.log2(N*T[i,j]/(r[i]*s[j])) for i in range(len(r)) for j in range(len(s)) if T[i,j]) ER = -(r/N*np.log2(r/N)).sum(); ES = -(s/N*np.log2(s/N)).sum() return MI, ER, ES, MI / np.sqrt(ER * ES)
C35. What Clustering Is: Formulation, Types, and Convexity
Intuition
Group objects so that members of a group resemble each other and differ from other groups — without anyone telling you the groups, like sorting a shop’s customers into segments. Quality depends entirely on how “similar” is measured.
Formal definition
A clustering of S into k clusters is a partition satisfying
(i) Ci=∅; (ii) Ci∩Cj=∅ for i=j; (iii) ⋃i=1kCi=S.
Types.Hierarchical (a tree of clusters, a dendrogram; agglomerative = bottom-up merging, divisive = top-down splitting) and partitional (a fixed, pre-chosen number k of clusters).
Partitional loss (lecture):
L(P(C1,…,Ck))=∑j=1k∑Xi∈Cjρ(Xi,μj),
and the aim is a partition P′ with L(P′)≤L(P) for all partitions P.
Mathematical consequence: clusters are convex
For Euclidean ρ, a point is assigned to C1 rather than C2 iff ∥X−μ1∥≤∥X−μ2∥, i.e.
2XT(μ2−μ1)≤∥μ2∥2−∥μ1∥2,
a half-space (a set bounded by a hyperplane — convex). The intersection of such half-spaces is convex. So the optimum of L always produces convex-shaped clusters, which may not match the structure you want (ring-shaped or crescent-shaped clusters).
Key insights
The number of partitions of n points into exactly 2 non-empty clusters is 2n−1−1 (Stirling number S(n,2)) — exhaustive search is hopeless in general.
Clustering is unsupervised: validity must be judged by external labels (C41–C42) or by internal criteria.
Worked examples
Example 1 — Very Easy · Valid partitions
Problem: For S={a,b,c,d} which are valid partitions? (i) {a,b},{c,d}; (ii) {a,b},{b,c,d}; (iii) {a},{b},{c}; (iv) {a,b,c,d},∅.
Asked: Validity.
Concept: Partition axioms.
Approach: Test the three conditions.
Solution: (i) valid. (ii) b is in both ⇒ violates disjointness. (iii) d is missing ⇒ violates covering. (iv) an empty cluster ⇒ violates non-emptiness.
Final answer: Only (i).
Key lesson
Hard clustering ⇒ each point belongs to exactly one non-empty cluster.
Example 2 — Easy · Scoring two clusterings
Problem:S={1,2,3,10,11} (1-D). Compute L with ρ=∣⋅∣ for A={1,2,3},{10,11} and B={1,2},{3,10,11}.
Problem: How many ways can 4 labelled points be split into exactly 2 non-empty clusters? How many partitions in total (any k)?
Asked: Counts.
Concept: Combinatorics of partitions.
Approach: Pin one point; the others choose a side.
Solution: Fix point 1 in cluster A; each other point is in A or B: 23=8 assignments; exclude “all in A” ⇒ 7=23−1. Total over all k: Bell number B4=1+7+6+1=15 (S(4,1)=1,S(4,2)=7,S(4,3)=6,S(4,4)=1).
The search space grows super-exponentially (20 points already have 5×1013 partitions).
Example 4 — Hard · The loss cannot find nested clusters
Problem: Points {−10,10} (an “outer” cluster) and {−0.5,0,0.5} (an “inner” cluster). The desired clustering is inner vs outer. Compute L (ρ=∣⋅∣) for it and compare with the best two-cluster partition.
Asked: Is the desired clustering optimal?
Concept: The optimum of L is convex-shaped.
Approach: Enumerate the 24−1=15 partitions.
Solution: Desired: {−10,10}: μ=0 ⇒ 20; {−0.5,0,0.5}: μ=0 ⇒ 1. L=21. Enumerating all 15 partitions, the minimum is L=15 for {−10,−0.5,0,0.5}∣{10} (and its mirror image): centroids −2.5 and 10: 7.5+2+2.5+3=15. Next: 20.5 (×2), 20.83 (×2) — six partitions beat the desired one.
Final answer: Desired L=21; optimal L=15 with interval clusters.
Python check
import itertoolsS = [-10, 10, -.5, 0, .5]; L1 = lambda parts: sum(np.abs(np.array(p) - np.mean(p)).sum() for p in parts)res = []for mask in range(1, 2**4): A = [S[0]] + [S[i] for i in range(1, 5) if not (mask >> (i-1)) & 1]; B = [S[i] for i in range(1, 5) if (mask >> (i-1)) & 1] if B: res.append(round(L1([A, B]), 3))print(sorted(res)[:7], L1([[-10, 10], [-.5, 0, .5]])) # [15.0, 15.0, 20.5, 20.5, 20.833, 20.833, 21.0] 21.0
Key lesson
A non-convex cluster (outer points surrounding the inner ones) can never be an optimum of this criterion.
Example 5 — Very Hard · Concentric rings
Problem: Concentric “rings”: inner (±1,0),(0,±1); outer (±4,0),(0,±4). (a) Show that for the desired ring partition both centroids coincide at the origin. (b) Compute L (Euclidean distances) for the desired partition and for the half-space partition ”x1<0 vs x1≥0”. (c) What is the optimum over all 127 two-cluster partitions?
Asked: Three computations.
Concept: Half-space limitation.
Approach: Centroids; sum distances.
Solution: (a) Inner mean =(0,0); outer mean =(0,0). Equal centroids ⇒ the bisector is empty — a centroid-based assignment cannot even represent nested clusters. (b) Desired: inner distances 4×1=4; outer 4×4=16 ⇒ L=20. Half-space: left {(−1,0),(−4,0)}, μ=(−2.5,0) ⇒ 3; right (6 points) μ=(65,0): d(1,0)=0.1667; d(4,0)=3.1667; d(0,±1)=1.3017 each; d(0,±4)=4.0858 each; sum =14.108 ⇒ L=17.11. (c) Exhaustive minimum =15.81 (isolating one outer point).
Final answer: Desired ring partition L=20 is worse than a plain half-space split 17.11 and than the optimum 15.81.
Python check
pts = np.array([(1,0),(-1,0),(0,1),(0,-1),(4,0),(-4,0),(0,4),(0,-4)], float)Lp = lambda parts: sum(np.linalg.norm(p - p.mean(0), axis=1).sum() for p in parts)print(Lp([pts[:4], pts[4:]]), Lp([pts[pts[:, 0] < 0], pts[pts[:, 0] >= 0]])) # 20.0 17.1085best = 1e9for mask in range(1, 2**7): # point 0 always on side 0 side = np.array([0] + [(mask >> (i - 1)) & 1 for i in range(1, 8)]) if side.min() != side.max(): best = min(best, Lp([pts[side == 0], pts[side == 1]]))print(best) # 15.8133
Key lesson
For non-convex clusters use density-based (C40) or single-linkage methods, not centroid-based ones.
Common mistakes
Allowing overlapping or empty clusters in a hard clustering.
Assuming the optimum of L finds “natural” shapes.
Exam traps
Partitional ⇒ k fixed in advance; hierarchical ⇒ no k in advance (but a cut level or stopping criterion is needed).
Alternate two easy steps: (1) assign every point to its nearest centre; (2) move every centre to the mean of its points. Each step lowers (or keeps) the total squared distance, so the process settles.
flowchart LR
I["choose k seeds"] --> A["Assign each point<br/>to nearest centroid"]
A --> U["Update each centroid<br/>to its cluster mean"]
U --> Q{"centroids<br/>unchanged?"}
Q -->|no| A
Q -->|yes| S([stop])
Algorithm (Lloyd, as in the lecture)
Choose k initial centroids μj(0) randomly from the data. Set I←0.
Final answer: Seeds {2,4,18} give J=45 (local optimum); the global optimum has J=6.667.
Python check
S = [2, 4, 18, 24, 25, 27]print(lloyd(S, [2, 4, 18])[2]) # 45.0 (stuck)print(min((Jsq([S[:i], S[i:j], S[j:]]), i, j) for i in range(1, 5) for j in range(i+1, 6))) # (6.667, 2, 3)
Key lesson
k-means converges, but not necessarily to the best answer — run several seeds.
Example 5 — Very Hard · Why Lloyd always terminates
Problem: Prove that Lloyd’s algorithm (squared Euclidean) never increases J and terminates; then verify numerically on Example 2.
Asked: Proof and check.
Concept: Coordinate descent.
Approach: Two-step monotonicity.
Solution: Let J(C,μ)=∑j∑X∈Cj∥X−μj∥2. Assign step: with μ fixed, moving a point from Ca to the nearest Cb replaces ∥X−μa∥2 by ∥X−μb∥2≤∥X−μa∥2 ⇒ J does not increase. Update step: with C fixed, the mean minimises each cluster’s sum of squares ⇒ J does not increase. The sequence J0≥J1≥⋯≥0 is bounded below. Because the number of partitions kn is finite and J strictly decreases whenever the partition changes, no partition repeats ⇒ termination. Check: Example 2 gave J=89.2 then 4.0 ✓.
Final answer: Monotone decreasing, finite termination at a local minimum.
Key lesson
The proof requires the mean — it is the minimiser only for squared distances (for ∣⋅∣ the minimiser is the median, giving k-medians / k-medoids, C38).
Common mistakes
Using k-means with arbitrary distances and still taking the mean.
Stopping after one iteration.
Exam traps
Stop rule: centroids unchanged for consecutive iterations (or an iteration cap).
Complexity is linear in n but iterations may be many.
Two repairs to k-means. Bisecting: build k clusters top-down by repeatedly splitting the largest cluster with 2-means (deterministic structure, near-uniform sizes). Buckshot: get good seeds by clustering a small random sample hierarchically first.
Algorithms
Bisecting k-means: start with all data as one cluster; while fewer than k clusters, pick the largest cluster and split it into two with (k=2) k-means.
Buckshot: (1) draw a random sample of size kn; (2) cluster the sample by (agglomerative) hierarchical clustering down to k clusters; (3) use their k centroids as seeds for ordinary k-means on all n points.
Properties
Bisecting produces clusters of almost uniform size: good when true clusters are balanced, poor when sizes differ greatly. It still needs k and 2-means seeds.
Buckshot: the hierarchical step is cheap (small sample); repeated runs give different partitions; poor if the sample is unrepresentative; still needs k.
Worked examples
Example 1 — Very Easy · Which cluster to split?
Problem: Current clusters have sizes 10,6,4. Which does bisecting k-means split next?
Asked: Choice.
Concept: “Largest cluster” rule.
Approach: Max size.
Solution: The size-10 cluster.
Final answer: The size-10 cluster.
Key lesson
Selection is by size, not by within-cluster scatter.
Example 2 — Easy · Buckshot sample size
Problem: Buckshot sample sizes for (n=100,k=4) and (n=106,k=10).
Asked: Two sizes.
Concept:kn.
Approach: Compute.
Solution:400=20; 107=3162.
Final answer:20 and 3162.
Key lesson
The sample is a vanishing fraction of the data for large n (0.3% in the second case).
Example 3 — Moderate · Bisecting with k = 3
Problem: Bisecting k-means with k=3 on {1,2,3,10,11,12,30,31} (assume each 2-means finds the optimal split).
Asked: Final clusters.
Concept: Bisecting procedure.
Approach: First split, then split the largest.
Solution: 2-means on all 8: best contiguous split {1,2,3,10,11,12},{30,31} (J=126; the competing split {1,2,3},{10,11,12,30,31} has J=460.8). The largest cluster is the six-point one ⇒ 2-means: {1,2,3},{10,11,12}.
Splitting the largest cluster recovers the true structure here.
Example 4 — Hard · Buckshot step by step
Problem: Buckshot on {1,2,3,4,20,21,22,23}, k=2: sample size 2⋅8=4; suppose the sample is {2,4,20,23}. Cluster it by single linkage to 2 clusters, then run k-means from those centroids.
Asked: Seeds and final result.
Concept: Buckshot.
Approach: Hierarchical clustering on the sample.
Solution: Sample distances: 2–4: 2; 20–23: 3; 4–20: 16. Single linkage merges (2,4) then (20,23) ⇒ clusters {2,4},{20,23} with centroids 3 and 21.5 (seeds). k-means on all 8: 1,2,3,4→3; 20..23→21.5. Update: 2.5 and 21.5; assignments unchanged ⇒ converged. J=10.
Seeds from a hierarchical pass avoid pathological starts.
Example 5 — Very Hard · Bisecting vs plain k-means
Problem: Data {2,4,18,24,25,27}, k=3 (as in C36 Ex. 4). Compare bisecting k-means with plain k-means seeded {2,4,18}.
Asked:J of each.
Concept: Bisecting as deterministic top-down.
Approach: Optimal 2-splits.
Solution: First split of all six: {2,4}∣{18,24,25,27}: 2+45=47; {2,4,18}∣{24,25,27}: 156.7; others larger ⇒ choose the first. The largest is the 4-point cluster: {18}∣{24,25,27}: 4.667; {18,24}∣{25,27}: 20 ⇒ choose the first. Final: {2,4},{18},{24,25,27}: J=6.667 (global optimum). Plain k-means from the unlucky seeds: J=45.
Final answer: Bisecting 6.667 vs plain k-means 45.
Top-down splitting can avoid bad seeds — but is not guaranteed optimal in general.
Common mistakes
Splitting the cluster with largest variance (the lecture’s rule is largest size).
Taking a sample of size kn.
Exam traps
Bisecting ⇒ near-uniform sizes; fails with very unequal true sizes.
Buckshot needs k and a hierarchical step on kn points.
Connections: C36, C39.
Mastery checklist
Execute bisecting k-means.
Compute Buckshot’s sample size.
State the weaknesses of each.
C38. k-Medoids
Intuition
The mean can be dragged away by an outlier and need not be a real data point. A medoid is an actual data point near the centre — robust, and usable with any dissimilarity. (Think of the median household income vs the mean once a billionaire moves in.)
Definitions (lecture)
Medoid (minimax form): for each Xi compute Zi=maxjρ(Xi,Xj); the medoid is the point achieving Z′=miniZi. Cost O(n2).
Approximation: the member closest to the mean μ of the set: X0=argminXi∈Sρ(Xi,μ). Cost O(n).
(The lecture also describes the medoid as the member with minimal average distance to all others — the standard textbook definition; the three definitions often, but not always, coincide.)
The rest of the algorithm is k-means with medoids in place of means.
Key insights
Robust to outliers; the centre is always a data point.
Same limitations as k-means (k fixed, seeds).
Worked examples
Example 1 — Very Easy · Mean vs medoid
Problem: Medoid (closest-to-mean) of {1,2,3,100}.
Asked: Medoid and mean.
Concept: Approximation.
Approach: Mean, then nearest member.
Solution: Mean =26.5. Distances: 25.5,24.5,23.5,73.5 ⇒ nearest is 3.
Final answer: Mean 26.5, medoid 3.
Key lesson
The mean is pulled by 100; the medoid is not.
Example 2 — Easy · Three definitions
Problem: For {1,2,3,100} compute the minimax and average-distance medoids.
Asked: Two medoids.
Concept: Definitions.
Approach: Table.
Solution: Max distances: 1→99, 2→98, 3→97, 100→99 ⇒ minimax medoid 3. Average distances: 1:25.5; 2:25; 3:25; 100:73.5 ⇒ tie between 2 and 3.
Definitions can disagree on ties; state which you use.
Example 3 — Moderate · Centres of an outlier cluster
Problem: Cluster {10,11,12,200}: mean, approximate medoid, and the distance of a new point 11.5 to each.
Asked: Compare centres.
Concept: Outlier robustness.
Approach: Compute.
Solution: Mean =58.25. Distances of members to 58.25: 48.25,47.25,46.25,141.75 ⇒ approximate medoid 12. Distance of 11.5: to the mean 46.75; to the medoid 0.5.
Final answer: Mean 58.25 vs medoid 12.
Key lesson
The mean is far from every real member.
Example 4 — Hard · Cost of exact vs approximate
Problem: For n=1000 compare the number of distance evaluations for the exact minimax medoid vs the mean-based approximation (per cluster).
Asked: Counts.
Concept: Complexity.
Approach: Pairs vs points.
Solution: Exact: all ordered pairs, n2=106 (or (2n)≈5×105 distinct). Approximate: compute the mean (O(nm)) then n=1000 distances.
Final answer:∼106 vs ∼103 distances.
Key lesson
Hence the approximation in practice, at the price of exactness.
Example 5 — Very Hard · k-medoids with an outlier
Problem:S={1,2,3,10,11,12,200}, k=3, ρ=∣⋅∣. Start with medoids {1,10,200} and run to convergence; report cost.
Asked: Final medoids and clusters.
Concept: k-medoids iteration.
Approach: Assign; recompute medoids (minimising total distance).
Solution: Assign: {1,2,3}→1, {10,11,12}→10, {200}→200. New medoids: for {1,2,3} total distance to 2 is 2 (vs 3 for 1) ⇒ 2; for {10,11,12} ⇒ 11; {200}→200. Re-assign: unchanged. Cost =2+2+0=4.
Final answer: Medoids 2,11,200; clusters {1,2,3},{10,11,12},{200}; cost 4.
Key lesson
The outlier 200 gets its own cluster rather than distorting a centroid.
Common mistakes
Using the mean and calling it a medoid.
Believing the medoid must minimise squared distance (that is the mean).
C39. Agglomerative Hierarchical Clustering: Single, Complete, Average Linkage
Intuition
Start with every point alone; repeatedly merge the two closest clusters; record the merges in a tree (dendrogram). “Closest” for sets of points needs a definition — that choice is the linkage.
Every point is a singleton cluster. 2. Compute distances between all pairs of clusters. 3. Merge the closest pair. 4. Repeat 2–3 until one cluster (or until the desired number of clusters). Cutting the dendrogram at a height gives a flat clustering.
Linkages (lecture)
For clusters C1={X1i}i≤p, C2={X2j}j≤q:
dsingle=mini,jρ(X1i,X2j),dcomplete=maxi,jρ(X1i,X2j),davg=pq1∑i=1p∑j=1qρ(X1i,X2j).
Update rule after merging i,j into (ij), for another cluster k (Lance–Williams): single dk,(ij)=min(dki,dkj); complete max(dki,dkj); average ni+njnidki+njdkj.
Behaviour
Single: can follow chains of close points ⇒ long, straggly clusters; the chaining effect: two clusters joined by a thin bridge of noise points get merged.
Complete: compact, roughly spherical clusters; sensitive to outliers.
Average: in between.
Naive complexity O(n3) time, O(n2) memory. Choosing where to stop is the main practical difficulty.
Python helper for the checks in this section
def heights(pts, method): # merge heights of the dendrogram return np.round(linkage(np.array(pts, float)[:, None], method)[:, 2], 3)
Worked examples
Example 1 — Very Easy · The three distances
Problem:C1={1,2}, C2={5,9} (1-D). Compute the three linkage distances.
Asked: Three numbers.
Concept: Linkage definitions.
Approach: All cross distances: ∣1−5∣=4,∣1−9∣=8,∣2−5∣=3,∣2−9∣=7.
Solution: Single =min=3; complete =max=8; average =44+8+3+7=5.5.
Final answer:3,8,5.5.
Key lesson
Single ≤ average ≤ complete, always.
Example 2 — Easy · Dendrogram heights
Problem: Points 0,1,4,6,10. Give the merge sequence and heights for single, complete, average.
Asked: Three dendrograms.
Concept: Algorithm.
Approach: Merge the closest pair each time.
Solution: All three first merge {0,1} (height 1), then {4,6} (height 2). Next: single: 3; complete: 6; average: 44+6+3+5=4.5. Then 10 joins {0,1,4,6}: single =4; complete =10; average =410+9+6+4=7.25.
Final answer: Heights — single: 1,2,3,4; complete: 1,2,6,10; average: 1,2,4.5,7.25.
Python check
for m in ("single", "complete", "average"): print(m, heights([0, 1, 4, 6, 10], m))# single [1 2 3 4] complete [1 2 6 10] average [1 2 4.5 7.25]
Key lesson
Same merge order here, different heights.
Example 3 — Moderate · Doubling gaps
Problem: Points 1,2,4,8,16. Merge heights for the three linkages.
Asked: Heights.
Concept: Height behaviour.
Approach: Sequential merges (all produce {1,2}, then 4, then 8, then 16).
Final answer: Single 1,2,4,8; complete 1,3,7,15; average 1,2.5,5.67,12.25.
Python check
for m in ("single", "complete", "average"): print(m, heights([1, 2, 4, 8, 16], m))
Key lesson
Complete-link heights are the cluster diameters.
Example 4 — Hard · Three linkages, three answers
Problem: Points 7,9,16,24,30,35. Find the 3-cluster partition from each linkage.
Asked: Three partitions.
Concept: Linkages can disagree.
Approach: Run three merges each.
Solution: Pairwise gaps: 2,7,8,6,5. Single:(7,9) at 2; (30,35) at 5; 24 joins {30,35} at 6 ⇒ {7,9},{16},{24,30,35}. Complete:(7,9) at 2; (30,35) at 5; next smallest: d(16,24)=8 (vs d(16,{7,9})=9, d(24,{30,35})=11) ⇒ {7,9},{16,24},{30,35}. Average:d(16,{7,9})=8 vs d(24,{30,35})=8.5 ⇒ {7,9,16},{24},{30,35}.
Final answer: Three different partitions.
Python check
for m in ("single", "complete", "average"): print(m, fcluster(linkage(np.array([7, 9, 16, 24, 30, 35.])[:, None], m), 3, "maxclust"))# single [2 2 3 1 1 1] complete [2 2 3 3 1 1] average [1 1 1 3 2 2]
Key lesson
The linkage is the assumption about what a cluster looks like.
Example 5 — Very Hard · Chaining across a bridge
Problem: Two blobs {0,1,2} and {10,11,12} connected by a sparse bridge {4,6,8}. Compare single and complete linkage; what does each give for 3 clusters?
Asked: Chaining demonstration.
Concept: Chaining effect.
Approach: Merge heights.
Solution:Single: four merges at height 1 build {0,1,2} and {10,11,12}; then every bridge gap is 2, so all remaining merges happen at height 2 — the dendrogram cannot tell the bridge from the blobs, and a 3-cluster cut depends on tie-breaking (it may absorb the bridge into a blob). Complete: merge heights 1,1,2,2,2,4,8,12; the 3-cluster cut gives {0,1,2},{4,6,8},{10,11,12} — the true structure.
Final answer: Single linkage chains through the bridge; complete linkage recovers three clusters.
Divisive: start with everything in one cluster and split — the mirror image of agglomerative.
DBSCAN: clusters are dense regions separated by sparse regions; points in sparse regions are noise. It finds arbitrarily shaped clusters and does not need k.
noise border core core core border core core core
· · ● ● ● · · ● ● ● · ← each ● has ≥ r neighbours within ε
└── cluster 1 ──┘ └─ cluster 2 ─┘
Divisive clustering (lecture)
Start with the whole data set as one cluster. At each step choose one existing cluster (generally the one with the least overall similarity) and split it into two. Stop when only singletons remain or a halting criterion is met. Limitation: choosing the halting point for unknown data.
Solution:∣H∣: 0:2,0.5:3,1:3,1.5:3,2:2; 3.2:2; 4:3{3.2,4,4.8}; 4.8:2; and symmetric for B. Cores: 0.5,1,1.5; 4; 6.5,7,7.5. H0.5,H1,H1.5 overlap pairwise ⇒ one cluster {0,…,2}; H4 stands alone ⇒ {3.2,4,4.8}; B likewise. No noise.
The bridge is separated from the blobs because the gaps (1.2 and 1.2) exceed ϵ.
Example 4 — Hard · Parameter sensitivity
Problem: Same points. (a) ϵ=0.6,r=3; (b) ϵ=1.3,r=3. Outputs?
Asked: Parameter sensitivity.
Concept: Choosing ϵ.
Approach: Recount.
Solution: (a) Bridge points have no neighbour within 0.6 (∣H∣=1 each) ⇒ not core, in no core neighbourhood ⇒ noise; clusters A and B remain. (b) ϵ=1.3: ∣H2∣={1,1.5,2,3.2} and ∣H3.2∣={2,3.2,4} both ≥3 and intersect ⇒ A merges with the bridge; similarly bridge with B ⇒ everything becomes one cluster.
ϵ controls whether sparse bridges are noise, separate clusters or merged.
Example 5 — Very Hard · Why DBSCAN resists chaining
Problem: Explain, using this data, why DBSCAN avoids the chaining that plagues single linkage, and when it would still chain.
Asked: Argument.
Concept: Density vs distance.
Approach: Compare merge conditions.
Solution: Single linkage merges A and the bridge once the gap1.2 is the smallest remaining distance, regardless of how thin the bridge is. DBSCAN merges two neighbourhoods only if both are dense (≥r points) and overlap. With ϵ=0.9 the gap 1.2 exceeds ϵ, so nothing connects; even if a single point lay in the gap, its ∣H∣ would be small (1–2), failing ∣H∣≥r. It chains only when the bridge itself is dense (as with ϵ=1.3).
Final answer: DBSCAN requires density, not just proximity; a dense bridge defeats it.
If class labels exist, ask how well each class is recovered by some cluster: use the recall / precision of its best-matching cluster, then weight by class size.
Formal definition
R = categories (I of them), S = clusters (J), N points; ri = size of category i, sj = size of cluster j, sij = overlap.
Recallij=risij,Precisionij=sjsij,Fij=Recallij+Precisionij2RecallijPrecisionij(Fij=0 if sij=0),Fi=maxjFij,F=∑i=1INriFi.
Larger is better; F∈[0,1].
Key insights
Same formula as C11 with “category” = positive class and “cluster” = predicted group.
Max over clusters: each category is matched to its best cluster (a cluster may be matched by several categories).
Weakness: a single big cluster gets a high F (Example 5).
Worked data used in Examples 2–4 (and C42)
N=100 customers, three known segments R1,R2,R3 and three discovered clusters S1,S2,S3 (rows = categories, columns = clusters):
R1R2R3sjS1358245S2525030S3022325ri403525100
Worked examples
Example 1 — Very Easy · Recall and precision of one cell
Problem: Category with ri=40 members; cluster with sj=45; overlap sij=35. Recall, precision?
Problem: Two categories of 50 points each. Compute F for (a) perfect clustering, (b) one cluster containing everything, (c) N=100 singleton clusters. Comment.
Asked: Three F values.
Concept: Degenerate clusterings.
Approach: Per-category best match.
Solution: (a) R=P=1 ⇒ F=1. (b) sj=100, sij=50: R=1, P=0.5, Fi=0.667 ⇒ F=0.667. (c) Best cluster is a singleton: R=501, P=1, Fi=512=0.0392 ⇒ F=0.0392.
The trivial one-cluster solution scores surprisingly high (0.667); F rewards recall too generously — compare with the number of clusters and use NMI (C42) as a complement.
Common mistakes
Averaging Fij over all clusters instead of taking the max.
Weighting by cluster size instead of category size.
C42. Cluster Evaluation II: Normalised Mutual Information (NMI)
Intuition
Knowing the cluster of a point should tell you something about its category. Mutual information measures how many bits the cluster reveals about the category; dividing by the entropies puts it on a [0,1] scale.
Formal definition (Strehl & Ghosh)
MI(R,S)=∑i=1I∑j=1JNsijlogrisjNsij,E(R)=−∑iNrilogNri,E(S)=−∑jNsjlogNsj,NMI(R,S)=E(R)E(S)MI(R,S).
Conventions: 0log0=0; every category and cluster non-empty. The log base cancels in the ratio.
Properties
MI≥0; MI=0 iff R and S are independent (sij=risj/N).
NMI(S,S)=1; NMI∈[0,1].
Invariant to relabelling clusters.
Derivation: MI=0 under independence
If sij=risj/N then risjNsij=1, log1=0 for every term. ∎
Worked examples
Example 1 — Very Easy · A perfect clustering
Problem: Perfect clustering of two balanced categories (N=100, s11=s22=50, off-diagonals 0). NMI?
Different criteria give different scales; NMI is stricter than F here.
Example 5 — Very Hard · Singleton clusters
Problem: Two categories of 50. Show that placing every point in its own cluster (J=N=100) gives NMI=E(R)/logN and evaluate it; then comment.
Asked: Formula and value.
Concept: Bias toward many clusters.
Approach: If each cluster is a singleton, sj=1 and the cluster determines the category.
Solution:sij=1 for the unique category of the point. MI=∑iNrilogriN=E(R). E(S)=logN. NMI=E(R)logNE(R)=logNE(R). Here (bits) E(R)=1, log2100=6.644 ⇒ NMI=0.1505=0.388.
Final answer:NMI=0.388 for the meaningless singleton clustering.
Python check
print(np.sqrt(1 / np.log2(100))) # 0.388
Key lesson
NMI is not zero for over-clustering; read it together with the number of clusters (F, by contrast, punishes singletons heavily: 0.039).
Common mistakes
Forgetting 0log0=0.
Using logNsij instead of logrisjNsij.
Exam traps
The denominator is E(R)E(S) (geometric mean).
NMI(S,S)=1.
Connections: Entropy and information gain (C4), F-measure (C41).