Chapter 13: Unsupervised Learning — Implementation
This notebook implements the chapter’s main methods from scratch, checks them against scikit-learn, and applies them to real data:
k-means with k-means++ starts, from scratch
Choosing : the elbow and the silhouette
Case study: grouping wines without their labels, and why scaling decides everything
Hierarchical clustering, DBSCAN and Gaussian mixtures where k-means fails
PCA from scratch, and compressing digits
An autoencoder: better compression than PCA, and anomaly detection
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, make_moons, load_wine, load_digits
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.mixture import GaussianMixture
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score, silhouette_samples, adjusted_rand_score
np.set_printoptions(precision=3, suppress=True)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.
def kmeans_pp_init(X, k, rng):
centroids = [X[rng.integers(len(X))]]
for _ in range(1, k):
d2 = np.min(((X[:, None] - np.array(centroids)[None]) ** 2).sum(-1), axis=1)
centroids.append(X[rng.choice(len(X), p=d2 / d2.sum())])
return np.array(centroids)
def kmeans(X, k, n_init=10, max_iter=100, seed=0):
rng = np.random.default_rng(seed)
best = None
for _ in range(n_init): # several starts; keep the lowest J
C = kmeans_pp_init(X, k, rng)
for _ in range(max_iter):
labels = np.argmin(((X[:, None] - C[None]) ** 2).sum(-1), axis=1) # assign
new_C = np.array([X[labels == j].mean(0) if np.any(labels == j) else C[j] for j in range(k)]) # update
if np.allclose(new_C, C):
break
C = new_C
J = sum(((X[labels == j] - C[j]) ** 2).sum() for j in range(k))
if best is None or J < best[2]:
best = (labels, C, J)
return best
# the chapter's worked example
labels, C, J = kmeans(np.array([[1], [2], [4], [7], [8], [10.]]), 2)
print('worked example: centroids', C.ravel(), ' J =', round(J, 3))
X, y_true = make_blobs(500, centers=4, cluster_std=0.9, random_state=3)
labels, C, J = kmeans(X, 4)
sk = KMeans(4, n_init=10, random_state=0).fit(X)
print(f'blobs: our J = {J:.1f} scikit-learn J = {sk.inertia_:.1f} same partition (ARI): {adjusted_rand_score(labels, sk.labels_):.3f}')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 ¶
The silhouette of each point compares (its mean distance to its own cluster) and (its mean distance to the nearest other cluster): .
def silhouette(X, labels):
D = np.sqrt(((X[:, None] - X[None]) ** 2).sum(-1)) # all pairwise distances
s = np.zeros(len(X))
for i in range(len(X)):
own = labels == labels[i]
if own.sum() == 1:
continue # a singleton gets s = 0
a = D[i, own].sum() / (own.sum() - 1) # exclude the point itself
b = min(D[i, labels == c].mean() for c in set(labels) if c != labels[i])
s[i] = (b - a) / max(a, b)
return s
x1 = np.array([[1], [2], [4], [7], [8], [10.]]); lab1 = np.array([0, 0, 0, 1, 1, 1])
print('worked example, point 4:', round(silhouette(x1, lab1)[2], 3))
print('matches scikit-learn on the blobs:', np.allclose(silhouette(X, labels), silhouette_samples(X, labels)))
ks = range(2, 9)
results = [kmeans(X, k) for k in ks]
fig, axes = plt.subplots(1, 2, figsize=(11, 3.3))
axes[0].plot(ks, [r[2] for r in results], 'o-'); axes[0].set_title('Elbow'); axes[0].set_xlabel('k'); axes[0].set_ylabel('J')
axes[1].plot(ks, [silhouette(X, r[0]).mean() for r in results], 'o-', c='C2'); axes[1].set_title('Mean silhouette'); axes[1].set_xlabel('k')
plt.tight_layout(); plt.show()worked example, point 4: 0.423
matches scikit-learn on the blobs: True

Both point to , 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).
wine = load_wine()
W, cultivar = wine.data, wine.target
print('feature ranges (max − min):')
for name, r in sorted(zip(wine.feature_names, np.ptp(W, axis=0)), key=lambda t: -t[1])[:4]:
print(f' {name:30} {r:8.1f}')
print(' ...')
for name, data in [('raw features', W), ('standardised', StandardScaler().fit_transform(W))]:
lab = KMeans(3, n_init=10, random_state=0).fit_predict(data)
print(f'{name:14} ARI with the cultivars = {adjusted_rand_score(cultivar, lab):.3f} mean silhouette = {silhouette_score(data, lab):.3f}')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.
Ws = StandardScaler().fit_transform(W)
print('silhouette by k on the standardised wines:', {k: round(silhouette_score(Ws, KMeans(k, n_init=10, random_state=0).fit_predict(Ws)), 3) for k in range(2, 7)})
print('hierarchical clustering, ARI by linkage:', {link: round(adjusted_rand_score(cultivar, AgglomerativeClustering(3, linkage=link).fit_predict(Ws)), 3) for link in ['ward', 'complete', 'average', 'single']})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 , 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:
Z = PCA(2).fit_transform(Ws)
lab = KMeans(3, n_init=10, random_state=0).fit_predict(Ws)
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].scatter(Z[:, 0], Z[:, 1], c=lab, cmap='Set2', s=18); axes[0].set_title('k-means clusters (no labels used)')
axes[1].scatter(Z[:, 0], Z[:, 1], c=cultivar, cmap='Set1', s=18); axes[1].set_title('the true cultivars')
for ax in axes: ax.set_xlabel('PC 1'); ax.set_ylabel('PC 2')
plt.tight_layout(); plt.show()
Xm, ym = make_moons(400, noise=0.06, random_state=0)
for name, model in [('k-means', KMeans(2, n_init=10, random_state=0)), ('DBSCAN', DBSCAN(eps=0.2, min_samples=5))]:
lab = model.fit_predict(Xm)
print(f'{name:8} ARI = {adjusted_rand_score(ym, lab):.3f} clusters found: {len(set(lab) - {-1})} noise points: {(lab == -1).sum()}')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.
Xa, ya = make_blobs(600, centers=3, random_state=170)
Xa = Xa @ np.array([[0.6, -0.64], [-0.41, 0.85]]) # stretch and tilt
km_lab = KMeans(3, n_init=10, random_state=0).fit_predict(Xa)
gmm = GaussianMixture(3, random_state=0).fit(Xa)
gm_lab = gmm.predict(Xa)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for ax, lab, name in [(axes[0], km_lab, 'k-means'), (axes[1], gm_lab, 'Gaussian mixture')]:
ax.scatter(Xa[:, 0], Xa[:, 1], c=lab, cmap='Set2', s=10)
ax.set_title(f'{name}: ARI = {adjusted_rand_score(ya, lab):.2f}'); ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout(); plt.show()
proba = gmm.predict_proba(Xa)
unsure = proba.max(axis=1).argmin()
print(f'most uncertain point {Xa[unsure].round(2)}: probabilities per cluster {proba[unsure].round(3)}')
print(f'points with no cluster above 95%: {(proba.max(axis=1) < 0.95).sum()} of {len(Xa)}')
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¶
def pca_fit(X, k):
mean = X.mean(axis=0)
Xc = X - mean
S = Xc.T @ Xc / (len(X) - 1) # covariance matrix
eigvals, eigvecs = np.linalg.eigh(S) # ascending order for symmetric matrices
order = np.argsort(eigvals)[::-1]
eigvals, eigvecs = eigvals[order], eigvecs[:, order]
return mean, eigvecs[:, :k], eigvals / eigvals.sum()
# the chapter's worked example: the eigen-decomposition of S
vals, vecs = np.linalg.eigh(np.array([[2, 1.2], [1.2, 1.0]]))
print('worked example: eigenvalues', vals[::-1], ' first component', np.abs(vecs[:, -1]))
digits = load_digits()
D = digits.data
mean, Wk, ratio = pca_fit(D, 2)
ours = (D - mean) @ Wk
ref = PCA(2).fit_transform(D)
print('matches scikit-learn (up to the sign of each component):', np.allclose(np.abs(ours), np.abs(ref)))
print('variance kept by 2 / 10 / 21 components:', ratio[:2].sum().round(3), ratio[:10].sum().round(3), ratio[:21].sum().round(3))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 numbers and reconstructing it, :
ks_show = [2, 5, 10, 21, 64]
fig, axes = plt.subplots(3, len(ks_show) + 1, figsize=(9, 4.6))
for row, idx in enumerate([0, 3, 7]):
axes[row, 0].imshow(D[idx].reshape(8, 8), cmap='gray_r'); axes[row, 0].set_title('original' if row == 0 else '')
for col, k in enumerate(ks_show, start=1):
mean, Wk, _ = pca_fit(D, k)
rec = mean + (D[idx] - mean) @ Wk @ Wk.T
axes[row, col].imshow(rec.reshape(8, 8), cmap='gray_r')
if row == 0: axes[row, col].set_title(f'k = {k}')
for ax in axes.ravel(): ax.axis('off')
plt.suptitle('PCA reconstructions: 10 to 21 numbers are enough to read the digit'); plt.tight_layout(); plt.show()
6. An Autoencoder¶
A network 64 → 64 → → 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 .
import torch
from torch import nn
from sklearn.model_selection import train_test_split
Dn = D / 16.0
D_tr, D_te = train_test_split(Dn, test_size=0.25, random_state=0)
T_tr, T_te = torch.tensor(D_tr, dtype=torch.float32), torch.tensor(D_te, dtype=torch.float32)
def make_autoencoder(k):
encoder = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, k))
decoder = nn.Sequential(nn.Linear(k, 64), nn.ReLU(), nn.Linear(64, 64), nn.Sigmoid())
return nn.Sequential(encoder, decoder)
def train_autoencoder(model, X, epochs=300, lr=1e-3):
torch.manual_seed(0)
opt = torch.optim.Adam(model.parameters(), lr=lr)
for _ in range(epochs):
perm = torch.randperm(len(X))
for i in range(0, len(X), 64):
batch = X[perm[i:i + 64]]
loss = ((model(batch) - batch) ** 2).mean() # reconstruction error: no labels
opt.zero_grad(); loss.backward(); opt.step()
return model
autoencoders = {}
for k in [2, 8]:
torch.manual_seed(0)
autoencoders[k] = train_autoencoder(make_autoencoder(k), T_tr)
with torch.no_grad():
ae_err = ((autoencoders[k](T_te) - T_te) ** 2).mean().item()
p = PCA(k).fit(D_tr)
pca_err = ((p.inverse_transform(p.transform(D_te)) - D_te) ** 2).mean()
print(f'k = {k}: test reconstruction error PCA {pca_err:.4f} autoencoder {ae_err:.4f}')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.
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(0)
scrambled = np.array([rng.permutation(x) for x in D_te[:100]])
ae = autoencoders[8]
with torch.no_grad():
err_normal = ((ae(T_te) - T_te) ** 2).mean(1).numpy()
S_t = torch.tensor(scrambled, dtype=torch.float32)
err_anom = ((ae(S_t) - S_t) ** 2).mean(1).numpy()
threshold = np.percentile(err_normal, 99)
print(f'threshold (99th percentile of normal errors) = {threshold:.4f}')
print(f'scrambled images flagged: {(err_anom > threshold).mean():.0%} normal digits flagged: {(err_normal > threshold).mean():.0%}')
print(f'AUROC = {roc_auc_score(np.r_[np.zeros(len(err_normal)), np.ones(len(err_anom))], np.r_[err_normal, err_anom]):.3f}')
plt.hist(err_normal, bins=40, alpha=0.7, label='normal test digits'); plt.hist(err_anom, bins=40, alpha=0.7, label='scrambled images')
plt.axvline(threshold, ls='--', c='k', label='threshold'); plt.xlabel('reconstruction error'); plt.legend(); plt.title('Anomalies are badly reconstructed'); plt.show()threshold (99th percentile of normal errors) = 0.0429
scrambled images flagged: 100% normal digits flagged: 1%
AUROC = 1.000

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