Chapter 13: Unsupervised Learning
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 alone.
| Task | Question | Methods (this chapter) | Example |
|---|---|---|---|
| Clustering | which examples belong together? | k-means, hierarchical, DBSCAN, Gaussian mixtures | customer segments, groups of news stories |
| Dimensionality reduction | what are the few directions that matter? | PCA, t-SNE, autoencoders | visualising 64-D digits in 2-D, compression |
| Anomaly detection | which examples do not fit? | DBSCAN noise, reconstruction error | fraud, machine faults |
| Generative modelling | how could we produce new examples? | mixtures, variational autoencoders | synthetic 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: . 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 clusters, each represented by its centroid (the mean of its points). It looks for the clusters with the smallest within-cluster sum of squares (WCSS, also called inertia):
Lloyd’s algorithm alternates two steps until nothing changes:
Assign each point to its nearest centroid.
Update each centroid to the mean of its points.
Each step can only lower , so the algorithm always stops, but possibly in a local minimum that depends on the starting centroids.
Worked example¶
Six points on a line, , , with a poor start: , .
| Iteration | Assignment (cluster 1 / cluster 2) | New centroids |
|---|---|---|
| 1 | / (2 is closer to ) | 1, |
| 2 | / (4 is closer to 6.2 than to 1) | 1.5, |
| 3 | / () | 2.33, |
| 4 | no change: converged |
Final WCSS: .
Source
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, make_moons, load_digits
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.metrics import silhouette_score
X, _ = make_blobs(300, centers=3, cluster_std=1.0, random_state=7)
rng = np.random.default_rng(1)
C = X[rng.choice(len(X), 3, replace=False)] + 2.0
fig, axes = plt.subplots(1, 4, figsize=(14, 3.3))
for it, ax in enumerate(axes):
labels = np.argmin(((X[:, None] - C[None]) ** 2).sum(-1), axis=1)
ax.scatter(X[:, 0], X[:, 1], c=labels, cmap='Set2', s=12)
ax.scatter(C[:, 0], C[:, 1], c='k', marker='X', s=160)
J = sum(((X[labels == j] - C[j]) ** 2).sum() for j in range(3))
ax.set_title(f'iteration {it + 1}: J = {J:.0f}'); ax.set_xticks([]); ax.set_yticks([])
C = np.array([X[labels == j].mean(0) for j in range(3)])
plt.suptitle('k-means: assign to the nearest centroid (X), move each centroid to the mean of its points', y=1.03); plt.tight_layout(); plt.show()
Better starts: k-means++¶
Because the result depends on the start, libraries run k-means several times (n_init) and keep the best . 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 ¶
Elbow method: plot against . always decreases (with 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 be its mean distance to the other points of its cluster and its mean distance to the points of the nearest other cluster. Then
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 that maximises it.
Example. In the final clustering above, the point 4 has (to 1 and 2) and (to 7, 8, 10), so : correctly placed, but the closest to the border.
Source
X4, _ = make_blobs(500, centers=4, cluster_std=0.9, random_state=3)
ks = range(2, 9)
inertia = [KMeans(k, n_init=10, random_state=0).fit(X4).inertia_ for k in ks]
sil = [silhouette_score(X4, KMeans(k, n_init=10, random_state=0).fit_predict(X4)) for k in ks]
fig, axes = plt.subplots(1, 3, figsize=(14, 3.3))
axes[0].scatter(X4[:, 0], X4[:, 1], s=8, c='gray'); axes[0].set_title('data (4 groups)')
axes[1].plot(ks, inertia, 'o-'); axes[1].axvline(4, ls='--', c='C3'); axes[1].set_title('Elbow: the bend is at k = 4'); axes[1].set_xlabel('k'); axes[1].set_ylabel('J (inertia)')
axes[2].plot(ks, sil, 'o-', c='C2'); axes[2].axvline(4, ls='--', c='C3'); axes[2].set_title('Mean silhouette: highest at k = 4'); axes[2].set_xlabel('k')
plt.tight_layout(); plt.show()
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 ( per iteration), and often good enough.
13.4 Hierarchical Clustering¶
Agglomerative clustering builds a whole hierarchy, from bottom to top:
Start with every point as its own cluster.
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:
| Linkage | Distance between clusters and | Tends to give |
|---|---|---|
| Single | the closest pair | long chains; finds curved shapes, sensitive to noise |
| Complete | the farthest pair | compact clusters of similar diameter |
| Average | the mean over all pairs | a compromise |
| Ward | the increase in WCSS caused by merging | round clusters, like k-means |
Worked example¶
Points on a line. First merge (distance 1) and (distance 1). Then:
| Merge | Single | Complete | Average |
|---|---|---|---|
| with | |||
| with |
The merge order is the same here, but the heights differ, and on real data so do the trees.
Source
from scipy.cluster.hierarchy import linkage, dendrogram
pts = np.array([1, 2, 6, 7, 15.0])[:, None]
fig, axes = plt.subplots(1, 3, figsize=(13, 3.2))
for ax, method in zip(axes, ['single', 'complete', 'average']):
dendrogram(linkage(pts, method), labels=['1', '2', '6', '7', '15'], ax=ax, color_threshold=0, above_threshold_color='C0')
ax.set_title(f'{method} linkage'); ax.set_xlabel('point')
for ax in axes: ax.set_ylim(0, 15)
axes[0].set_ylabel('merge distance'); plt.suptitle('Dendrograms of the worked example', y=1.02); plt.tight_layout(); plt.show()
Hierarchical clustering needs all pairwise distances: 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 and a count minPts.
A core point has at least
minPtspoints (itself included) within distance .A border point is within 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-means | DBSCAN | |
|---|---|---|
| Number of clusters | must be given () | found automatically |
| Shapes | round | any shape |
| Outliers | forced into a cluster | labelled noise |
| Difficulty | choosing | choosing (clusters of very different densities are hard) |
Source
Xm, _ = make_moons(400, noise=0.06, random_state=0)
Xm = np.vstack([Xm, np.random.default_rng(0).uniform([-1.3, -0.8], [2.3, 1.3], (15, 2))]) # a few outliers
models = [('k-means, k = 2', KMeans(2, n_init=10, random_state=0)),
('single linkage, 2 clusters: one outlier is a "cluster"', AgglomerativeClustering(2, linkage='single')),
('DBSCAN, eps = 0.2, minPts = 5', DBSCAN(eps=0.2, min_samples=5))]
fig, axes = plt.subplots(1, 3, figsize=(14, 3.4))
for ax, (name, model) in zip(axes, models):
lab = model.fit_predict(Xm)
ax.scatter(Xm[lab >= 0, 0], Xm[lab >= 0, 1], c=lab[lab >= 0], cmap='Set2', s=10)
if (lab < 0).any(): ax.scatter(Xm[lab < 0, 0], Xm[lab < 0, 1], c='k', marker='x', s=25, label='noise'); ax.legend(loc='lower left')
ax.set_title(name); ax.set_xticks([]); ax.set_yticks([])
plt.suptitle('Two interleaved moons with outliers: k-means cuts straight across; DBSCAN follows the shapes and flags the outliers', y=1.03); plt.tight_layout(); plt.show()
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 Gaussian “bumps”, each with its own mean , covariance (so clusters can be elongated and tilted) and weight :
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: .
M-step: re-estimate each , and from the points, weighted by their responsibilities.
A GMM gives probabilities (“70% segment A, 30% segment B”), a density (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¶
| Situation | Measure |
|---|---|
| No labels at all | inertia (for choosing only: it always improves with ), silhouette, the Davies–Bouldin index |
| Labels exist for checking | adjusted Rand index (ARI): 1 = identical partitions, about 0 = random; it does not care how clusters are numbered |
| Always | usefulness: 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:
Centre the data: subtract the mean of each feature (and usually standardise).
Compute the covariance matrix ().
Find its eigenvectors (the principal components) and eigenvalues (the variance along each).
Keep the eigenvectors with the largest eigenvalues, as columns of , and project: .
The fraction of the total variance kept is . In practice PCA is computed with the singular value decomposition of , which is faster and more stable.
Worked example¶
Two features with covariance matrix . The eigenvalues solve :
so and . For : gives , normalised .
The first component alone keeps of the variance: the two features say almost the same thing, and one number per example is enough.
Source
from sklearn.decomposition import PCA
digits = load_digits()
pca = PCA().fit(digits.data)
Z = pca.transform(digits.data)[:, :2]
fig, axes = plt.subplots(1, 2, figsize=(13, 4))
sc = axes[0].scatter(Z[:, 0], Z[:, 1], c=digits.target, cmap='tab10', s=6)
axes[0].legend(*sc.legend_elements(), title='digit', fontsize=7, loc='upper right', ncol=2)
axes[0].set_title('64-D digits projected on the first 2 components'); axes[0].set_xlabel('PC 1'); axes[0].set_ylabel('PC 2')
cum = np.cumsum(pca.explained_variance_ratio_)
axes[1].plot(np.arange(1, 65), cum, 'o-', ms=3); axes[1].axhline(0.9, ls='--', c='gray')
k90 = int(np.argmax(cum >= 0.9)) + 1
axes[1].axvline(k90, ls='--', c='C3'); axes[1].set_title(f'{k90} of 64 components keep 90% of the variance')
axes[1].set_xlabel('number of components'); axes[1].set_ylabel('cumulative explained variance')
plt.tight_layout(); plt.show()
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
from sklearn.manifold import TSNE
T2 = TSNE(2, perplexity=30, random_state=0, init='pca').fit_transform(digits.data)
plt.figure(figsize=(6.5, 5))
sc = plt.scatter(T2[:, 0], T2[:, 1], c=digits.target, cmap='tab10', s=6)
plt.legend(*sc.legend_elements(), title='digit', fontsize=7, loc='best', ncol=2)
plt.title('t-SNE of the 64-D digits: the ten digits separate (labels used only for colour)'); plt.xticks([]); plt.yticks([]); plt.show()
13.10 Autoencoders¶
An autoencoder is a neural network trained to reproduce its input, through a narrow bottleneck:
The loss is the reconstruction error ; 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:
| Data | Pretext task | Model |
|---|---|---|
| Text | hide words and predict them | BERT |
| Text | predict the next word | GPT and the large language models of Chapter 21 |
| Images | recognise two crops of the same photo among others (contrastive learning) | SimCLR, CLIP (with captions) |
| Images | hide patches and reconstruct them | masked 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¶
| Goal | Start with | Then try |
|---|---|---|
| Segments of similar size and shape | k-means (scaled features, several , silhouette) | Gaussian mixture for soft or elongated clusters |
| Clusters of any shape, with noise | DBSCAN | HDBSCAN (varying densities) |
| A hierarchy, or a small dataset | agglomerative (Ward or average) | |
| A 2-D picture of the data | PCA | t-SNE or UMAP |
| Compression, faster models | PCA (keep 90–95% of the variance) | autoencoder |
| Anomalies | DBSCAN noise, a Gaussian mixture’s low density | autoencoder 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 with the elbow or the silhouette ; 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¶
Run k-means on with starting from , . Do you reach the same clusters?
Compute the silhouette of the point 7 in the final clustering of Section 13.3.
Build the single-linkage dendrogram of . Where would you cut it, and how many clusters do you get?
With and
minPts= 3, label every point of as core, border or noise.Find the principal components and explained variance of . Interpret.
A t-SNE plot shows two clusters far apart and one small. What can you conclude, and what can you not?
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.