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 — Implementation

Open in Colab

This notebook implements the chapter’s main methods from scratch, checks them against scikit-learn, and applies them to real data:

  1. k-means with k-means++ starts, from scratch

  2. Choosing kk: the elbow and the silhouette

  3. Case study: grouping wines without their labels, and why scaling decides everything

  4. Hierarchical clustering, DBSCAN and Gaussian mixtures where k-means fails

  5. PCA from scratch, and compressing digits

  6. An autoencoder: better compression than PCA, and anomaly detection

1. k-Means from Scratch

kmeans_pp_init picks the first centroid at random and each next one with probability proportional to its squared distance from the nearest centroid already chosen. kmeans then alternates the two steps of Lloyd’s algorithm.

worked example: centroids [8.333 2.333]  J = 9.333
blobs: our J = 816.9   scikit-learn J = 816.9   same partition (ARI): 1.000

2. Choosing kk

The silhouette of each point compares aa (its mean distance to its own cluster) and bb (its mean distance to the nearest other cluster): s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b).

worked example, point 4: 0.423
matches scikit-learn on the blobs: True
<Figure size 1100x330 with 2 Axes>

Both point to k=4k = 4, the number of groups we generated.

3. Case Study: Grouping Wines

The wine dataset holds 13 chemical measurements of 178 Italian wines from three grape cultivars. We hide the cultivar, cluster the wines, and only afterwards check whether the clusters match the cultivars (adjusted Rand index, ARI).

feature ranges (max − min):
  proline                          1402.0
  magnesium                          92.0
  alcalinity_of_ash                  19.4
  color_intensity                    11.7
  ...
raw features    ARI with the cultivars = 0.371   mean silhouette = 0.571
standardised    ARI with the cultivars = 0.897   mean silhouette = 0.285

Scaling decides everything. Proline ranges over about 1400 units while most features range over a few, so on raw data k-means effectively clusters by proline alone (ARI 0.37). Standardised, the clusters nearly recover the three cultivars (ARI 0.90), without ever seeing them.

Notice the trap: the raw clustering has the higher silhouette. A silhouette measures how well separated the clusters are in the space you gave it; it cannot tell you that the space was badly scaled, and silhouettes computed in different spaces cannot be compared.

silhouette by k on the standardised wines: {2: 0.268, 3: 0.285, 4: 0.246, 5: 0.203, 6: 0.196}
hierarchical clustering, ARI by linkage: {'ward': 0.79, 'complete': 0.577, 'average': -0.005, 'single': -0.007}

The silhouette picks k=3k = 3, the true number of cultivars. Among the linkages, Ward (which, like k-means, prefers compact clusters) does well; single and average linkage chain 174 of the 178 wines into one giant cluster, leaving 1 and 3 stray wines as the other two “clusters” (ARI near 0).

To look at the clusters, project the 13 standardised features on two principal components:

<Figure size 1100x400 with 2 Axes>

4. Where k-Means Fails

Curved clusters: DBSCAN

k-means  ARI = 0.274   clusters found: 2   noise points: 0
DBSCAN   ARI = 1.000   clusters found: 2   noise points: 0

Elongated clusters: Gaussian mixtures

We stretch and tilt three blobs. k-means, which measures plain distance to a centre, cuts them wrongly; a Gaussian mixture learns a covariance for each cluster and recovers them exactly.

<Figure size 1100x380 with 2 Axes>
most uncertain point [-2.04  0.83]: probabilities per cluster [0.831 0.    0.169]
points with no cluster above 95%: 1 of 600

5. PCA from Scratch

worked example: eigenvalues [2.8 0.2]  first component [0.832 0.555]
matches scikit-learn (up to the sign of each component): True
variance kept by 2 / 10 / 21 components: 0.285 0.738 0.903

Compressing a digit to kk numbers and reconstructing it, x^=xˉ+WkWk⊤(x−xˉ)\hat{\mathbf{x}} = \bar{\mathbf{x}} + W_k W_k^\top(\mathbf{x} - \bar{\mathbf{x}}):

<Figure size 900x460 with 18 Axes>

6. An Autoencoder

A network 64 → 64 → kk → 64 → 64 trained to reproduce the digits (pixels scaled to 0–1). We compare its reconstruction error on unseen digits with PCA using the same kk.

k = 2: test reconstruction error   PCA 0.0540   autoencoder 0.0383
k = 8: test reconstruction error   PCA 0.0249   autoencoder 0.0139

With the same code size, the nonlinear autoencoder reconstructs unseen digits clearly better than PCA (which is the best linear method).

Anomaly detection

Trained only on normal digits, the autoencoder should fail on images unlike anything it has seen. As “anomalies” we scramble the pixels of 100 test digits (same pixel values, no digit shape) and compare reconstruction errors.

threshold (99th percentile of normal errors) = 0.0429
scrambled images flagged: 100%   normal digits flagged: 1%
AUROC = 1.000
<Figure size 640x480 with 1 Axes>

Real anomalies are rarely this obvious; in practice the threshold is chosen from the cost of false alarms against missed anomalies, as with the classification thresholds of Chapter 8.

Summary

SectionResult
1our k-means with k-means++ matches scikit-learn
2elbow and silhouette both find the 4 generated groups
3on wines, standardising lifts agreement with the cultivars from ARI 0.37 to 0.90, while the silhouette wrongly prefers the unscaled clustering
4DBSCAN follows curved clusters; a Gaussian mixture recovers tilted, elongated ones
5PCA from scratch matches scikit-learn; about 21 of 64 components keep 90% of the digits’ variance
6an autoencoder compresses better than PCA and flags scrambled images by their reconstruction error