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 : 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 , the number of clusters (capital, so it is not confused with neighbours), the cluster of point , the set of points in cluster and its size .
The k-means objective
k-means turns "compact" into a number. For an assignment and centres , the within-cluster sum of squares is
k-means looks for the and that minimize it. scikit-learn calls 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 , any other centre pays extra:
The cross term vanishes because the deviations from the mean sum to zero.
Small within means large between. Take , 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:
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 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
depends on two blocks of variables: the discrete assignment and the continuous centres . Each block is easy to optimize when the other is fixed. Lloyd's algorithm alternates the two exact minimizations:
- Assignment step. With fixed, each point takes its nearest centre: . On a tie, a point keeps its cluster.
- Update step. With fixed, each centre becomes its cluster mean: .
Each step minimizes over one block, so neither can increase it:
This is coordinate descent with two coordinates. It also stops. There are finitely many assignments, and a change of assignment strictly lowers , 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 for the distances, and few iterations are usually needed.
Five points on a line, , with and starting centres and . Each row shows the centres, the clusters they produce and for that pair:
| iteration | centres | clusters | |
|---|---|---|---|
| 0 | , | ||
| 1 | , | ||
| 2 | , | ||
| 3 | , |
At iteration 3 the clusters stop changing, and the algorithm stops with .
The assignment step cuts space into Voronoi cells. Points nearer to than to 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 in only 56% of 200 runs. The failed runs merged two blobs and split another, and the average was .
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 , the squared distance from 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 with the first centre at , the squared distances are , with sum . The second centre is with probability and with probability . It lands in the far group with probability ; a uniform draw would give .
Arthur and Vassilvitskii (2007) bounded the result of the seeding alone, before any Lloyd step:
For 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 . The usual practice adds restarts: run from several seeds and keep the lowest . scikit-learn does both by default.
How many clusters
cannot choose on its own. The best never grows with , because one more centre can always sit on an existing one. At , one cluster per point, it reaches zero. Two heuristics read off the data instead.
The elbow. Plot the best against and look for where extra clusters stop paying. On the four blobs, for . The drop from 3 to 4 is large, the drops after 4 are small: the elbow is at . 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 be the mean distance from to the other points of its cluster, and the smallest mean distance from to the points of another cluster. Then
with 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 with clusters and . For the point , and , so .
The average silhouette scores a whole clustering and can be compared across . On the four blobs it is for , highest at . It needs all pairwise distances, . Like , 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 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 and a count . Let be the data points within distance of , included.
- A point is a core point if .
- Core points within of each other share a cluster, and so does every chain of such steps. Non-core points within of a core point join its cluster as border points.
- Everything else is noise and belongs to no cluster.
Take the points with and . The neighbourhood of is and that of is , so both are core points. The points and have only two points within ; they are border points of the same cluster. Likewise is a core point with border points and . The point is noise. Two clusters and one outlier, and nobody gave .
A chain of -steps can follow a curve, so DBSCAN finds clusters of any shape. On 400 points of two moons it recovers both moons exactly with . The method is sensitive to : gives four clusters and 10 noise points, merges everything into one. The original paper reads off the sorted distances to the -th nearest neighbour, at the knee between cluster points and noise. One 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 : documents form topics, and topics split into subtopics. Agglomerative clustering builds the whole hierarchy. It starts with 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 and | behaviour |
|---|---|---|
| single | follows chains; one bridge of noise merges two clusters | |
| complete | compact clusters of similar diameter | |
| average | mean of over all pairs | between the two |
| Ward | increase of caused by the merge | the k-means objective, greedily |
By the identity of the k-means objective, merging and raises by , 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, memory.
Spectral clustering looks at the whole graph of near neighbours. Give each pair of points a weight , for example if one is among the 10 nearest neighbours of the other. With degrees and , the graph Laplacian is (here is a matrix, not a loss). For any vector with one value per point,
So is symmetric and positive semidefinite, and only if 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 smallest eigenvalues, give each point their 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. compares solutions with the same . The silhouette compares across , but it carries the k-means idea of a cluster: on the moons it scores the true split and the k-means split, which cuts both moons, . 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-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: is the same clustering as . Pair counting avoids the matching. Over all 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 be the number of points in true class and cluster , and , the row and column sums. Then
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 and spectral clustering all score 1.0.
Six points with classes and clusters . The table has rows and , so . The classes give , the clusters , and . Then and . The Rand index of the same pair is , 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.
Answers are saved on the server and tied to this browser until you sign in.