Skip to content
BIASED

Clustering

Finding groups in data without labels — why the answer depends on what a cluster is, k-means and Lloyd's algorithm as coordinate descent, k-means++ seeding, the elbow and the silhouette, where k-means fails, DBSCAN, hierarchical clustering and its linkages, spectral clustering in brief, and evaluating a clustering with and without labels.

What a cluster is

Every model so far, from nearest neighbours to the deep networks of the topic Training deep networks, learned from pairs (x,y)(x, y): an object and the answer it should get. The answers are the expensive part of a dataset. Someone has to mark each email as spam, check each loan, label each image. Often there are no labels at all: a log of customer sessions, a million unannotated photos, the vectors a network's hidden layer produces.

The data still have structure. The first question to ask of them is whether they fall into groups. That is clustering: split the points into groups so that points in a group are similar and points in different groups are not.

The sentence leaves two choices open: what "similar" means and what shape a group may have. Three common answers:

  • Compact groups. A cluster is a ball around a centre; points are close to their centre. This is k-means.
  • Dense regions. A cluster is a crowded region of any shape, separated by sparse space; isolated points belong to no cluster. This is DBSCAN.
  • Connected structure. A cluster is a set of points linked by chains of near neighbours. This is single linkage and spectral clustering.

On well-separated round blobs all three agree. Elsewhere they disagree, and none of them is wrong: they answer different questions. Kleinberg (2002) proved there is no way around this choice. No clustering rule built on pairwise distances can have three natural properties at once: ignore the unit of distance, be able to output any partition, and keep its answer when clusters are made tighter and further apart.

The distance itself is part of the answer. Every method in this topic sees the data only through distances, so the units of the features matter. As in the topic Nearest neighbours, a feature on a large scale dominates every distance. On four well-separated blobs, k-means recovers the blobs exactly; after one feature is multiplied by 10, it recovers them only partly. Scaling and encoding from the topic Data, features and leakage are part of the clustering.

Notation for the whole topic: points x1,…,xn∈Rdx_1, \dots, x_n \in \mathbb R^d, the number of clusters KK (capital, so it is not confused with kk neighbours), the cluster ci∈{1,…,K}c_i \in \{1, \dots, K\} of point ii, the set CkC_k of points in cluster kk and its size nkn_k.

The k-means objective

k-means turns "compact" into a number. For an assignment cc and centres μ1,…,μK∈Rd\mu_1, \dots, \mu_K \in \mathbb R^d, the within-cluster sum of squares is

J(c,μ)=∑i=1n∥xi−μci∥2=∑k=1K∑i∈Ck∥xi−μk∥2.J(c, \mu) = \sum_{i=1}^n \lVert x_i - \mu_{c_i} \rVert^2 = \sum_{k=1}^K \sum_{i \in C_k} \lVert x_i - \mu_k \rVert^2 .

k-means looks for the cc and μ\mu that minimize it. scikit-learn calls JJ the inertia.

The best centre of a cluster is its mean. The topic Conditional expectation showed that the mean is the best constant under squared error. Here it applies to each cluster. With the cluster mean xˉk=1nk∑i∈Ckxi\bar x_k = \frac{1}{n_k}\sum_{i \in C_k} x_i, any other centre μ\mu pays extra:

∑i∈Ck∥xi−μ∥2=∑i∈Ck∥xi−xˉk∥2+nk∥xˉk−μ∥2.\sum_{i \in C_k} \lVert x_i - \mu \rVert^2 = \sum_{i \in C_k} \lVert x_i - \bar x_k \rVert^2 + n_k \lVert \bar x_k - \mu \rVert^2 .

The cross term vanishes because the deviations from the mean sum to zero.

Small within means large between. Take μ=xˉ\mu = \bar x, the mean of all the data, in the same identity and sum over clusters. You get the sample version of the law of total variance from the same topic:

∑i=1n∥xi−xˉ∥2⏟total=∑k=1K∑i∈Ck∥xi−xˉk∥2⏟within+∑k=1Knk∥xˉk−xˉ∥2⏟between.\underbrace{\sum_{i=1}^n \lVert x_i - \bar x \rVert^2}_{\text{total}} = \underbrace{\sum_{k=1}^K \sum_{i \in C_k} \lVert x_i - \bar x_k \rVert^2}_{\text{within}} + \underbrace{\sum_{k=1}^K n_k \lVert \bar x_k - \bar x \rVert^2}_{\text{between}} .

The total is fixed by the data. So minimizing the scatter inside clusters is the same as pushing the cluster means apart.

Finding the exact minimum of JJ is NP-hard, even for two clusters when the dimension can grow. In practice one uses a local search.

Lloyd's algorithm is coordinate descent

JJ depends on two blocks of variables: the discrete assignment cc and the continuous centres μ\mu. Each block is easy to optimize when the other is fixed. Lloyd's algorithm alternates the two exact minimizations:

  1. Assignment step. With μ\mu fixed, each point takes its nearest centre: ci←arg⁡min⁡k∥xi−μk∥2c_i \leftarrow \arg\min_k \lVert x_i - \mu_k \rVert^2. On a tie, a point keeps its cluster.
  2. Update step. With cc fixed, each centre becomes its cluster mean: μk←xˉk\mu_k \leftarrow \bar x_k.

Each step minimizes JJ over one block, so neither can increase it:

J(ct+1,μt+1)≤J(ct+1,μt)≤J(ct,μt).J(c^{t+1}, \mu^{t+1}) \le J(c^{t+1}, \mu^{t}) \le J(c^{t}, \mu^{t}) .

This is coordinate descent with two coordinates. It also stops. There are finitely many assignments, and a change of assignment strictly lowers JJ, so no assignment repeats. The algorithm ends where neither step helps. That point is a local minimum, not necessarily the global one. An iteration costs O(nKd)O(nKd) for the distances, and few iterations are usually needed.

Five points on a line, 0,2,3,8,100, 2, 3, 8, 10, with K=2K = 2 and starting centres 00 and 33. Each row shows the centres, the clusters they produce and JJ for that pair:

iteration centres clusters JJ
0 0, 30,\ 3 {0}\{0\}, {2,3,8,10}\{2, 3, 8, 10\} 7575
1 0, 5.750,\ 5.75 {0,2}\{0, 2\}, {3,8,10}\{3, 8, 10\} 34.6934.69
2 1, 71,\ 7 {0,2,3}\{0, 2, 3\}, {8,10}\{8, 10\} 1616
3 1.67, 91.67,\ 9 {0,2,3}\{0, 2, 3\}, {8,10}\{8, 10\} 6.676.67

At iteration 3 the clusters stop changing, and the algorithm stops with J=6.67J = 6.67.

The assignment step cuts space into Voronoi cells. Points nearer to μk\mu_k than to μj\mu_j lie on one side of the perpendicular bisector of the two centres. A cell is an intersection of such half-spaces, so it is convex. Every k-means clustering is therefore a split into convex pieces with flat boundaries, whatever shape the data have. This one fact explains most of its failures.

Seeding: k-means++

Lloyd's algorithm ends in whichever local minimum lies downhill from its start. A bad start puts two centres into one blob and none into another. On four blobs of 600 points, a single start from four random data points reached the best J=1127.4J = 1127.4 in only 56% of 200 runs. The failed runs merged two blobs and split another, and the average JJ was 4064.44064.4.

k-means++ spreads the starting centres out. The first centre is a uniformly random data point. Each next centre is a data point drawn with probability proportional to D(x)2D(x)^2, the squared distance from xx to the nearest centre chosen so far. Points far from every current centre probably sit in a cluster with no centre yet, and they are the likely picks.

For the points 0,2,3,8,100, 2, 3, 8, 10 with the first centre at 00, the squared distances are 0,4,9,64,1000, 4, 9, 64, 100, with sum 177177. The second centre is 1010 with probability 100/177=0.565100/177 = 0.565 and 88 with probability 64/177=0.36264/177 = 0.362. It lands in the far group with probability 0.930.93; a uniform draw would give 0.40.4.

Arthur and Vassilvitskii (2007) bounded the result of the seeding alone, before any Lloyd step:

E[J]≤8(ln⁡K+2) Jopt.\mathbb E[J] \le 8(\ln K + 2)\, J_{\text{opt}} .

For K=4K = 4 the factor is about 27. The bound is loose, but a uniform start has no such guarantee, and in practice the seeding does far better. On the same four blobs, all 200 single k-means++ starts reached J=1127.4J = 1127.4. The usual practice adds restarts: run from several seeds and keep the lowest JJ. scikit-learn does both by default.

How many clusters

JJ cannot choose KK on its own. The best JJ never grows with KK, because one more centre can always sit on an existing one. At K=nK = n, one cluster per point, it reaches zero. Two heuristics read KK off the data instead.

The elbow. Plot the best JJ against KK and look for where extra clusters stop paying. On the four blobs, J=18363, 5241, 1127, 1020, 921J = 18363,\ 5241,\ 1127,\ 1020,\ 921 for K=2,…,6K = 2, \dots, 6. The drop from 3 to 4 is large, the drops after 4 are small: the elbow is at K=4K = 4. On real data the curve often bends smoothly, and the elbow is a matter of taste.

The silhouette scores each point by how much closer it is to its own cluster than to the next one. Let a(i)a(i) be the mean distance from xix_i to the other points of its cluster, and b(i)b(i) the smallest mean distance from xix_i to the points of another cluster. Then

s(i)=b(i)−a(i)max⁡(a(i),b(i))∈[−1,1],s(i) = \frac{b(i) - a(i)}{\max\big(a(i), b(i)\big)} \in [-1, 1] ,

with s(i)=0s(i) = 0 for a point alone in its cluster. Near 1 means deep inside its cluster, near 0 on a border, negative probably in the wrong cluster.

Take the points 0,1,2,6,70, 1, 2, 6, 7 with clusters {0,1,2}\{0, 1, 2\} and {6,7}\{6, 7\}. For the point 22, a=(2+1)/2=1.5a = (2 + 1)/2 = 1.5 and b=(4+5)/2=4.5b = (4 + 5)/2 = 4.5, so s=(4.5−1.5)/4.5=0.67s = (4.5 - 1.5)/4.5 = 0.67.

The average silhouette scores a whole clustering and can be compared across KK. On the four blobs it is 0.588, 0.762, 0.811, 0.680, 0.5770.588,\ 0.762,\ 0.811,\ 0.680,\ 0.577 for K=2,…,6K = 2, \dots, 6, highest at K=4K = 4. It needs all pairwise distances, O(n2)O(n^2). Like JJ, it favours convex, well-separated clusters: it inherits the k-means idea of a cluster.

Where k-means fails and DBSCAN

The convex cells and the squared distances make k-means prefer round clusters of similar spread and size. Four ways it goes wrong:

  • Non-convex clusters. Two interleaving half-moons cannot be split by a straight line, so k-means cuts each moon in half.
  • Unequal spreads. The boundary lies halfway between the centres, whatever the spreads. Take a tight cluster and a wide one four units apart. The outer points of the wide cluster that lie nearer to the tight centre go to the tight cluster.
  • Unequal sizes and elongated clusters. Splitting a large cluster can lower JJ more than respecting a small one.
  • Outliers. A mean moves toward far points. Medians (k-medians) or centres restricted to data points (k-medoids) are more robust and cost more.

DBSCAN defines clusters by density. It takes a radius ε\varepsilon and a count minPts\text{minPts}. Let Nε(x)N_\varepsilon(x) be the data points within distance ε\varepsilon of xx, xx included.

  • A point is a core point if ∣Nε(x)∣≥minPts\lvert N_\varepsilon(x)\rvert \ge \text{minPts}.
  • Core points within ε\varepsilon of each other share a cluster, and so does every chain of such steps. Non-core points within ε\varepsilon of a core point join its cluster as border points.
  • Everything else is noise and belongs to no cluster.

Take the points 0,0.5,1,1.5,5,9,9.4,9.80, 0.5, 1, 1.5, 5, 9, 9.4, 9.8 with ε=0.6\varepsilon = 0.6 and minPts=3\text{minPts} = 3. The neighbourhood of 0.50.5 is {0,0.5,1}\{0, 0.5, 1\} and that of 11 is {0.5,1,1.5}\{0.5, 1, 1.5\}, so both are core points. The points 00 and 1.51.5 have only two points within 0.60.6; they are border points of the same cluster. Likewise 9.49.4 is a core point with border points 99 and 9.89.8. The point 55 is noise. Two clusters and one outlier, and nobody gave KK.

A chain of ε\varepsilon-steps can follow a curve, so DBSCAN finds clusters of any shape. On 400 points of two moons it recovers both moons exactly with ε=0.2\varepsilon = 0.2. The method is sensitive to ε\varepsilon: 0.10.1 gives four clusters and 10 noise points, 0.30.3 merges everything into one. The original paper reads ε\varepsilon off the sorted distances to the minPts\text{minPts}-th nearest neighbour, at the knee between cluster points and noise. One ε\varepsilon is also one density threshold for all clusters; HDBSCAN scans all radii and keeps the clusters that persist.

Hierarchies and graphs

Often there is no single right KK: documents form topics, and topics split into subtopics. Agglomerative clustering builds the whole hierarchy. It starts with nn one-point clusters and repeatedly merges the two closest clusters until one is left. The merges form a tree, the dendrogram; cutting it at some height gives a flat clustering.

"Closest clusters" needs a distance between sets, the linkage:

linkage distance between clusters AA and BB behaviour
single min⁡a∈A,b∈B∥a−b∥\min_{a \in A, b \in B} \lVert a - b \rVert follows chains; one bridge of noise merges two clusters
complete max⁡a∈A,b∈B∥a−b∥\max_{a \in A, b \in B} \lVert a - b \rVert compact clusters of similar diameter
average mean of ∥a−b∥\lVert a - b \rVert over all pairs between the two
Ward increase of JJ caused by the merge the k-means objective, greedily

By the identity of the k-means objective, merging AA and BB raises JJ by nAnBnA+nB∥xˉA−xˉB∥2\frac{n_A n_B}{n_A + n_B} \lVert \bar x_A - \bar x_B \rVert^2, and Ward's linkage merges the pair with the smallest increase. Single linkage equals cutting the longest edges of a minimum spanning tree. That is why it follows the moons exactly, while complete, average and Ward linkage cut them like k-means. The price is the matrix of pairwise distances, O(n2)O(n^2) memory.

Spectral clustering looks at the whole graph of near neighbours. Give each pair of points a weight wij≥0w_{ij} \ge 0, for example 11 if one is among the 10 nearest neighbours of the other. With degrees di=∑jwijd_i = \sum_j w_{ij} and D=diag⁡(d1,…,dn)D = \operatorname{diag}(d_1, \dots, d_n), the graph Laplacian is L=D−WL = D - W (here LL is a matrix, not a loss). For any vector ff with one value per point,

f⊤Lf=12∑i,j=1nwij(fi−fj)2.f^\top L f = \frac12 \sum_{i,j=1}^n w_{ij} (f_i - f_j)^2 .

So LL is symmetric and positive semidefinite, and f⊤Lf=0f^\top L f = 0 only if ff is constant along every edge. By the spectral theorem of the topic Symmetric matrices and quadratic forms, the multiplicity of the eigenvalue 0 equals the number of connected components of the graph. Their indicator vectors span its eigenspace.

The algorithm uses this. Take the eigenvectors of the KK smallest eigenvalues, give each point their KK values as new coordinates, and run k-means there. Weak links between components make those eigenvalues small instead of zero, and the idea still works. On the moons, the 10-nearest-neighbour graph has two components, and k-means on two eigenvectors recovers the moons exactly.

Evaluating a clustering and what comes next

Without labels, a clustering can only be judged against the definition it was built from. JJ compares solutions with the same KK. The silhouette compares across KK, but it carries the k-means idea of a cluster: on the moons it scores the true split 0.330.33 and the k-means split, which cuts both moons, 0.490.49. Another check is stability: cluster several bootstrap samples and see whether the answers agree. Unstable structure is suspect, but a stable answer can be forced by the method. With K=2K = 2, k-means cuts a single elongated blob into nearly the same two halves on every resample.

With labels withheld from the clustering, one can compare. Accuracy does not work, because cluster numbers are arbitrary: {1,1,2,2}\{1, 1, 2, 2\} is the same clustering as {2,2,1,1}\{2, 2, 1, 1\}. Pair counting avoids the matching. Over all (n2)\binom n2 pairs, count the pairs on which the two partitions agree: both put the pair together, or both apart. The share of agreements is the Rand index. Random partitions agree on many pairs by chance, mostly "apart", so its values crowd near 1.

The adjusted Rand index (ARI) subtracts the agreement expected by chance. Let nijn_{ij} be the number of points in true class ii and cluster jj, and aia_i, bjb_j the row and column sums. Then

ARI=∑ij(nij2)−E12[∑i(ai2)+∑j(bj2)]−E,E=∑i(ai2)∑j(bj2)(n2).\text{ARI} = \frac{\sum_{ij} \binom{n_{ij}}{2} - E}{\frac12\big[\sum_i \binom{a_i}{2} + \sum_j \binom{b_j}{2}\big] - E}, \qquad E = \frac{\sum_i \binom{a_i}{2} \sum_j \binom{b_j}{2}}{\binom n2} .

EE is the expected number of pairs together in both partitions if the cluster labels were shuffled with sizes kept, a hypergeometric model from the topic Discrete distributions. The ARI is 1 for identical partitions, about 0 for unrelated ones, and it can be negative. On this scale, the results told in words earlier read as follows. k-means scores 1.0 on the four blobs and 0.736 after one feature is multiplied by 10. On the moons, k-means scores 0.274 and Ward linkage 0.239, while single linkage, DBSCAN with ε=0.2\varepsilon = 0.2 and spectral clustering all score 1.0.

Six points with classes AAABBBAAABBB and clusters 112222112222. The table nijn_{ij} has rows (2,1)(2, 1) and (0,3)(0, 3), so ∑(nij2)=1+3=4\sum \binom{n_{ij}}{2} = 1 + 3 = 4. The classes give 3+3=63 + 3 = 6, the clusters 1+6=71 + 6 = 7, and (62)=15\binom62 = 15. Then E=6⋅7/15=2.8E = 6 \cdot 7/15 = 2.8 and ARI=(4−2.8)/(6.5−2.8)=0.32\text{ARI} = (4 - 2.8)/(6.5 - 2.8) = 0.32. The Rand index of the same pair is 10/15=0.6710/15 = 0.67, which flatters the clustering. And labels are one structure among many: digits can be grouped by digit or by writer, so a low ARI may mean a different grouping, not a bad one.

k-means comes back later as a tool. In the Generative Models course it turns vectors into discrete codes, as in the VQ-VAE codebook. Within this course, every method here gives hard answers. A point belongs to one cluster, nothing says how sure that is, and k-means treats all clusters as round and equally wide. On a tight cluster next to a wide one it scores ARI 0.561. The next topic, Mixtures and the EM algorithm, makes clustering probabilistic. Each cluster becomes a Gaussian with its own mean and covariance, each point gets a probability for each cluster, and Lloyd's algorithm turns out to be a limiting case of EM.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.