Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 13: Unsupervised Learning

Open in Colab

If intelligence was a cake, unsupervised learning would be the cake, supervised learning would be the icing on the cake, and reinforcement learning would be the cherry on the cake.

Yann LeCun, keynote at NIPS 2016

13.1 Learning Without Labels

Chapters 8 to 12 learnt from labelled examples. Labels are expensive: a radiologist’s hour per scan, a linguist per sentence. Most data has none: customer records, sensor logs, photos, web text. Unsupervised learning finds structure in {x1,…,xn}\{\mathbf{x}_1, \dots, \mathbf{x}_n\} alone.

TaskQuestionMethods (this chapter)Example
Clusteringwhich examples belong together?k-means, hierarchical, DBSCAN, Gaussian mixturescustomer segments, groups of news stories
Dimensionality reductionwhat are the few directions that matter?PCA, t-SNE, autoencodersvisualising 64-D digits in 2-D, compression
Anomaly detectionwhich examples do not fit?DBSCAN noise, reconstruction errorfraud, machine faults
Generative modellinghow could we produce new examples?mixtures, variational autoencoderssynthetic data, image generation

There is no “right answer” to compare with, so evaluation is harder: we judge clusters by internal measures, by their usefulness for a later task, and by asking experts whether they make sense.

13.2 Similarity and Scaling

Most methods rest on a distance, usually Euclidean: d(x,z)=∑j(xj−zj)2d(\mathbf{x}, \mathbf{z}) = \sqrt{\sum_j (x_j - z_j)^2}. As with k-NN (Chapter 8), scale the features first: if income is in riyals and age in years, income decides everything. Standardise each feature (mean 0, standard deviation 1), or choose a distance that suits the data (cosine for text, for example).

13.3 k-Means

k-means splits the data into kk clusters, each represented by its centroid μj\boldsymbol{\mu}_j (the mean of its points). It looks for the clusters with the smallest within-cluster sum of squares (WCSS, also called inertia):

J=∑j=1k ∑x∈Cj∥x−μj∥2J = \sum_{j=1}^{k}\ \sum_{\mathbf{x} \in C_j} \|\mathbf{x} - \boldsymbol{\mu}_j\|^2

Lloyd’s algorithm alternates two steps until nothing changes:

  1. Assign each point to its nearest centroid.

  2. Update each centroid to the mean of its points.

Each step can only lower JJ, so the algorithm always stops, but possibly in a local minimum that depends on the starting centroids.

Worked example

Six points on a line, x={1,2,4,7,8,10}x = \{1, 2, 4, 7, 8, 10\}, k=2k = 2, with a poor start: μ1=1\mu_1 = 1, μ2=2\mu_2 = 2.

IterationAssignment (cluster 1 / cluster 2)New centroids
1{1}\{1\} / {2,4,7,8,10}\{2, 4, 7, 8, 10\} (2 is closer to μ2=2\mu_2 = 2)1,  31/5=6.2\ 31/5 = 6.2
2{1,2}\{1, 2\} / {4,7,8,10}\{4, 7, 8, 10\} (4 is closer to 6.2 than to 1)1.5,  29/4=7.25\ 29/4 = 7.25
3{1,2,4}\{1, 2, 4\} / {7,8,10}\{7, 8, 10\} (∣4−1.5∣=2.5<∣4−7.25∣=3.25\lvert 4 - 1.5\rvert = 2.5 < \lvert 4 - 7.25\rvert = 3.25)2.33,  8.33\ 8.33
4no change: converged

Final WCSS: (1−2.33)2+(2−2.33)2+(4−2.33)2+(7−8.33)2+(8−8.33)2+(10−8.33)2=9.33(1-2.33)^2 + (2-2.33)^2 + (4-2.33)^2 + (7-8.33)^2 + (8-8.33)^2 + (10-8.33)^2 = 9.33.

Source
<Figure size 1400x330 with 4 Axes>

Better starts: k-means++

Because the result depends on the start, libraries run k-means several times (n_init) and keep the best JJ. They also choose the starting centroids with k-means++: the first at random, each next one far from those already chosen (with probability proportional to its squared distance). This gives better results and faster convergence.

Choosing kk

  • Elbow method: plot JJ against kk. JJ always decreases (with k=nk = n it is 0), but it drops sharply until the natural number of clusters and slowly after: look for the bend.

  • Silhouette: for a point, let aa be its mean distance to the other points of its cluster and bb its mean distance to the points of the nearest other cluster. Then

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

ss near 1: well placed; near 0: on a border; negative: probably in the wrong cluster. The mean silhouette over all points scores a whole clustering; choose the kk that maximises it.

Example. In the final clustering above, the point 4 has a=(3+2)/2=2.5a = (3 + 2)/2 = 2.5 (to 1 and 2) and b=(3+4+6)/3=4.33b = (3 + 4 + 6)/3 = 4.33 (to 7, 8, 10), so s=(4.33−2.5)/4.33=0.42s = (4.33 - 2.5)/4.33 = 0.42: correctly placed, but the closest to the border.

Source
<Figure size 1400x330 with 3 Axes>

Limits of k-means

k-means assumes clusters that are round, of similar size and spread, and it assigns every point, outliers included. It fails on elongated or curved clusters (see the moons in Section 13.5), and the mean is pulled by outliers. Its strengths: simple, fast (O(nkd)O(nkd) per iteration), and often good enough.

13.4 Hierarchical Clustering

Agglomerative clustering builds a whole hierarchy, from bottom to top:

  1. Start with every point as its own cluster.

  2. Repeatedly merge the two closest clusters, until one remains.

The result is drawn as a dendrogram: a tree whose merge heights are the distances at which clusters joined. Cutting it at a chosen height gives a clustering, for any number of clusters, without rerunning anything.

How far apart are two clusters? That is the linkage:

LinkageDistance between clusters AA and BBTends to give
Singlethe closest pair min⁡d(a,b)\min d(a, b)long chains; finds curved shapes, sensitive to noise
Completethe farthest pair max⁡d(a,b)\max d(a, b)compact clusters of similar diameter
Averagethe mean over all pairsa compromise
Wardthe increase in WCSS caused by merginground clusters, like k-means

Worked example

Points {1,2,6,7,15}\{1, 2, 6, 7, 15\} on a line. First {1,2}\{1, 2\} merge (distance 1) and {6,7}\{6, 7\} (distance 1). Then:

MergeSingleCompleteAverage
{1,2}\{1, 2\} with {6,7}\{6, 7\}6−2=46 - 2 = 47−1=67 - 1 = 6(5+6+4+5)/4=5(5 + 6 + 4 + 5)/4 = 5
{1,2,6,7}\{1, 2, 6, 7\} with {15}\{15\}15−7=815 - 7 = 815−1=1415 - 1 = 14(14+13+9+8)/4=11(14 + 13 + 9 + 8)/4 = 11

The merge order is the same here, but the heights differ, and on real data so do the trees.

Source
<Figure size 1300x320 with 3 Axes>

Hierarchical clustering needs all pairwise distances: O(n2)O(n^2) memory, and more time. It suits a few thousand points, and data where the hierarchy itself is meaningful (families of species, of documents, of products).

13.5 DBSCAN: Clusters of Any Shape

DBSCAN (Density-Based Spatial Clustering of Applications with Noise, 1996) defines clusters as dense regions separated by sparse ones. Two parameters: a radius ε\varepsilon and a count minPts.

  • A core point has at least minPts points (itself included) within distance ε\varepsilon.

  • A border point is within ε\varepsilon of a core point, but is not core itself.

  • Everything else is noise.

A cluster is a set of core points that can reach each other through chains of neighbours, plus their border points.

k-meansDBSCAN
Number of clustersmust be given (kk)found automatically
Shapesroundany shape
Outliersforced into a clusterlabelled noise
Difficultychoosing kkchoosing ε\varepsilon (clusters of very different densities are hard)
Source
<Figure size 1400x340 with 3 Axes>

Single linkage can follow curved shapes too, but a single outlier or a thin bridge of points can chain two clusters together.

13.6 Gaussian Mixture Models

k-means makes hard decisions: each point belongs to one cluster. A Gaussian mixture model (GMM) assumes the data was generated by kk Gaussian “bumps”, each with its own mean μj\boldsymbol{\mu}_j, covariance Σj\Sigma_j (so clusters can be elongated and tilted) and weight πj\pi_j:

p(x)=∑j=1kπj N(x∣μj,Σj)p(\mathbf{x}) = \sum_{j=1}^{k} \pi_j\, \mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu}_j, \Sigma_j)

It is fitted with the Expectation–Maximisation (EM) algorithm, a soft version of k-means:

  • E-step: for each point, compute the responsibility of each cluster, the probability that it generated the point: rij=πjN(xi∣μj,Σj)/∑lπlN(xi∣μl,Σl)r_{ij} = \pi_j \mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_j, \Sigma_j) \big/ \sum_l \pi_l \mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_l, \Sigma_l).

  • M-step: re-estimate each πj\pi_j, μj\boldsymbol{\mu}_j and Σj\Sigma_j from the points, weighted by their responsibilities.

A GMM gives probabilities (“70% segment A, 30% segment B”), a density p(x)p(\mathbf{x}) (very low density = an anomaly), and can generate new points. k-means is the limit of a GMM with equal, round, shrinking covariances.

13.7 Evaluating a Clustering

SituationMeasure
No labels at allinertia (for choosing kk only: it always improves with kk), silhouette, the Davies–Bouldin index
Labels exist for checkingadjusted Rand index (ARI): 1 = identical partitions, about 0 = random; it does not care how clusters are numbered
Alwaysusefulness: do the segments behave differently? Do experts recognise them?

A clustering method always returns clusters, even from random noise. Check that the structure is real: compare with the same method run on shuffled data, and see whether the clusters are stable when the data is resampled.

13.8 Principal Component Analysis

High-dimensional data usually lies close to a much lower-dimensional subspace: the 64 pixels of a digit are far from independent. Principal Component Analysis (PCA) finds the orthogonal directions along which the data varies most:

  1. Centre the data: subtract the mean of each feature (and usually standardise).

  2. Compute the covariance matrix S=1n−1X⊤XS = \frac{1}{n-1}X^\top X (d×dd \times d).

  3. Find its eigenvectors (the principal components) and eigenvalues (the variance along each).

  4. Keep the kk eigenvectors with the largest eigenvalues, as columns of WkW_k, and project: Z=XWkZ = XW_k.

The fraction of the total variance kept is ∑i≤kλi/∑iλi\sum_{i \le k}\lambda_i \big/ \sum_i \lambda_i. In practice PCA is computed with the singular value decomposition of XX, which is faster and more stable.

Worked example

Two features with covariance matrix S=(21.21.21)S = \begin{pmatrix} 2 & 1.2 \\ 1.2 & 1 \end{pmatrix}. The eigenvalues solve det⁡(S−λI)=0\det(S - \lambda I) = 0:

(2−λ)(1−λ)−1.44=0  ⟺  λ2−3λ+0.56=0  ⟺  λ=3±9−2.242=3±2.62(2 - \lambda)(1 - \lambda) - 1.44 = 0 \iff \lambda^2 - 3\lambda + 0.56 = 0 \iff \lambda = \frac{3 \pm \sqrt{9 - 2.24}}{2} = \frac{3 \pm 2.6}{2}

so λ1=2.8\lambda_1 = 2.8 and λ2=0.2\lambda_2 = 0.2. For λ1\lambda_1: (2−2.8)v1+1.2v2=0(2 - 2.8)v_1 + 1.2 v_2 = 0 gives v2=23v1v_2 = \tfrac{2}{3}v_1, normalised w1=(0.832, 0.555)\mathbf{w}_1 = (0.832,\ 0.555).

The first component alone keeps 2.8/(2.8+0.2)=93%2.8 / (2.8 + 0.2) = 93\% of the variance: the two features say almost the same thing, and one number per example is enough.

Source
<Figure size 1300x400 with 2 Axes>

Uses of PCA: visualisation (2 or 3 components), compression, removing noise (drop the small components), and a faster, less overfitting input for other models. Limits: it is linear (it cannot unroll a curved surface), and the components are combinations of all features, which can be hard to interpret.

13.9 t-SNE and UMAP: Maps for the Eye

t-SNE (van der Maaten and Hinton, 2008) places points in 2-D so that points that are neighbours in the original space stay neighbours. It measures neighbourhoods with probabilities, and moves the 2-D points to make the two sets of probabilities match. UMAP (2018) has a similar goal and is faster on large data.

Source
<Figure size 650x500 with 1 Axes>

13.10 Autoencoders

An autoencoder is a neural network trained to reproduce its input, through a narrow bottleneck:

The loss is the reconstruction error ∥x−x^∥2\|\mathbf{x} - \hat{\mathbf{x}}\|^2; no labels are needed. To pass through the bottleneck, the network must learn a compact code that keeps what matters.

  • A linear autoencoder with squared error learns the same subspace as PCA. With nonlinear layers it can learn curved low-dimensional structure.

  • Denoising autoencoders are given a corrupted input and must reconstruct the clean one, which forces more robust features.

  • Anomaly detection: trained on normal data only, an autoencoder reconstructs normal examples well and unusual ones badly. A high reconstruction error flags an anomaly: a faulty machine, a fraudulent transaction, a damaged part on a production line.

  • Variational autoencoders (VAEs) make the code a probability distribution, so that decoding random codes generates new examples. Generative models such as GANs and diffusion models (behind today’s image generators) belong to the same family of ideas.

13.11 Self-Supervised Learning

The largest models of today are trained mostly without human labels, by inventing a supervised task from the data itself:

DataPretext taskModel
Texthide words and predict themBERT
Textpredict the next wordGPT and the large language models of Chapter 21
Imagesrecognise two crops of the same photo among others (contrastive learning)SimCLR, CLIP (with captions)
Imageshide patches and reconstruct themmasked autoencoders

The labels are free, so the training sets can be enormous, and the features learnt transfer to many tasks (Chapter 18’s transfer learning). This is the “cake” of the epigraph.

13.12 Choosing a Method

GoalStart withThen try
Segments of similar size and shapek-means (scaled features, several kk, silhouette)Gaussian mixture for soft or elongated clusters
Clusters of any shape, with noiseDBSCANHDBSCAN (varying densities)
A hierarchy, or a small datasetagglomerative (Ward or average)
A 2-D picture of the dataPCAt-SNE or UMAP
Compression, faster modelsPCA (keep 90–95% of the variance)autoencoder
AnomaliesDBSCAN noise, a Gaussian mixture’s low densityautoencoder reconstruction error

13.13 Summary

  • Unsupervised learning finds structure without labels: clusters, low-dimensional structure, anomalies.

  • k-means alternates assignment and update to reduce the within-cluster sum of squares; choose kk with the elbow or the silhouette s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b); it assumes round clusters.

  • Hierarchical clustering builds a dendrogram; the linkage (single, complete, average, Ward) shapes the result.

  • DBSCAN finds dense regions of any shape and labels noise; Gaussian mixtures give soft, elliptical clusters, fitted with EM.

  • PCA projects onto the eigenvectors of the covariance matrix with the largest eigenvalues; t-SNE and UMAP draw neighbourhood maps for the eye only.

  • Autoencoders learn codes by reconstruction and detect anomalies; self-supervised pretraining powers modern large models.

Exercises

  1. Run k-means on {1,2,4,7,8,10}\{1, 2, 4, 7, 8, 10\} with k=2k = 2 starting from μ1=4\mu_1 = 4, μ2=10\mu_2 = 10. Do you reach the same clusters?

  2. Compute the silhouette of the point 7 in the final clustering of Section 13.3.

  3. Build the single-linkage dendrogram of {0,1,3,7,8,12}\{0, 1, 3, 7, 8, 12\}. Where would you cut it, and how many clusters do you get?

  4. With ε=1.5\varepsilon = 1.5 and minPts = 3, label every point of {1,2,3,6,10,11,12,13}\{1, 2, 3, 6, 10, 11, 12, 13\} as core, border or noise.

  5. Find the principal components and explained variance of S=(3001)S = \begin{pmatrix} 3 & 0 \\ 0 & 1 \end{pmatrix}. Interpret.

  6. A t-SNE plot shows two clusters far apart and one small. What can you conclude, and what can you not?

  7. How would you use an autoencoder to detect faulty engines from vibration data, when you only have recordings of healthy engines?

Further Reading

  • G. James, D. Witten, T. Hastie, R. Tibshirani, An Introduction to Statistical Learning, 2nd ed., 2021, Chapter 12 (free online).

  • C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, Chapters 9 (mixtures, EM) and 12 (PCA).

  • M. Wattenberg, F. Viégas, I. Johnson, “How to Use t-SNE Effectively”, Distill, 2016.

  • The scikit-learn user guide, “Clustering” and “Decomposing signals in components”.

  • C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 9.