Chapter 13 — Lab: Unsupervised Learning
Lab Overview¶
You will implement the core of each unsupervised method of the chapter and check it against scikit-learn or SciPy.
| Exercise | Topic | Points |
|---|---|---|
| 1 | The two steps of k-means | 20 |
| 2 | The silhouette | 15 |
| 3 | Agglomerative clustering and linkage | 20 |
| 4 | DBSCAN: core, border and noise points | 15 |
| 5 | PCA | 15 |
| 6 | An autoencoder that beats PCA | 15 |
| Challenge | One step of EM for a Gaussian mixture | +10 |
Complete the code where you see # TODO, then run the check cell under it.
import numpy as np
import torch
from torch import nn
from scipy.cluster.hierarchy import linkage as scipy_linkage
from sklearn.datasets import make_blobs, load_digits
from sklearn.cluster import KMeans, DBSCAN
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_samples, adjusted_rand_score
from sklearn.model_selection import train_test_split
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
X_blobs, _ = make_blobs(300, centers=3, cluster_std=0.8, random_state=1)
print('Setup complete.')Exercise 1: The Two Steps of k-Means (20 points)¶
Complete assign(X, C) (the index of the nearest centroid for each row of X) and update(X, labels, k) (the mean of each cluster’s points; you may assume no cluster is empty). kmeans then alternates them.
def assign(X, C):
raise NotImplementedError # TODO
def update(X, labels, k):
raise NotImplementedError # TODO
def kmeans(X, C, max_iter=100):
for _ in range(max_iter):
labels = assign(X, C)
new_C = update(X, labels, len(C))
if np.allclose(new_C, C):
break
C = new_C
return labels, C_x = np.array([[1], [2], [4], [7], [8], [10.]])
check('the chapter example converges to 2.33 and 8.33', lambda: np.allclose(kmeans(_x, np.array([[1.], [2.]]))[1].ravel(), [7 / 3, 25 / 3]))
def _km_ok():
labels, C = kmeans(X_blobs, X_blobs[[0, 1, 2]].copy())
return adjusted_rand_score(labels, KMeans(3, n_init=10, random_state=0).fit_predict(X_blobs)) > 0.99
check('the same clusters as scikit-learn on 3 blobs', _km_ok)Exercise 2: The Silhouette (15 points)¶
Complete silhouette(X, labels), returning one value per point: , where is the mean distance to the other points of its own cluster and the smallest mean distance to the points of another cluster. (Assume every cluster has at least 2 points.)
def silhouette(X, labels):
raise NotImplementedError # TODOcheck('the point 4 in the chapter example: 0.423', lambda: np.isclose(silhouette(_x, np.array([0, 0, 0, 1, 1, 1]))[2], 0.4231, atol=1e-3))
_lab = KMeans(3, n_init=10, random_state=0).fit_predict(X_blobs)
check('matches silhouette_samples', lambda: np.allclose(silhouette(X_blobs, _lab), silhouette_samples(X_blobs, _lab)))Exercise 3: Agglomerative Clustering (20 points)¶
Complete merge_heights(X, linkage): start with one cluster per point and repeatedly merge the two closest clusters, until one remains. Return the list of merge distances, in order. linkage is 'single' (closest pair), 'complete' (farthest pair) or 'average' (mean over all pairs). A plain implementation with lists of point indices is fine.
def merge_heights(X, linkage='single'):
raise NotImplementedError # TODO_pts = np.array([[1], [2], [6], [7], [15.]])
check('the chapter example, single linkage: 1, 1, 4, 8', lambda: np.allclose(merge_heights(_pts, 'single'), [1, 1, 4, 8]))
check('the chapter example, complete and average', lambda: np.allclose(merge_heights(_pts, 'complete'), [1, 1, 6, 14]) and np.allclose(merge_heights(_pts, 'average'), [1, 1, 5, 11]))
_R = np.random.default_rng(0).normal(size=(12, 2))
check('matches SciPy on random points (all three linkages)', lambda: all(np.allclose(merge_heights(_R, m), scipy_linkage(_R, m)[:, 2]) for m in ['single', 'complete', 'average']))Exercise 4: DBSCAN Point Types (15 points)¶
Complete point_types(X, eps, min_pts), returning an array of strings 'core', 'border' or 'noise'. A point is core if at least min_pts points (itself included) lie within distance eps; border if it is not core but lies within eps of a core point; noise otherwise.
def point_types(X, eps, min_pts):
raise NotImplementedError # TODO_line = np.array([[1], [2], [3], [6], [10], [11], [12], [13.]])
check('the chapter exercise: eps 1.5, minPts 3', lambda: list(point_types(_line, 1.5, 3)) == ['border', 'core', 'border', 'noise', 'border', 'core', 'core', 'border'])
def _db_ok():
db = DBSCAN(eps=0.5, min_samples=5).fit(X_blobs)
core = np.zeros(len(X_blobs), bool); core[db.core_sample_indices_] = True
types = point_types(X_blobs, 0.5, 5)
return np.array_equal(types == 'core', core) and np.array_equal(types == 'noise', db.labels_ == -1)
check('core and noise points match scikit-learn', _db_ok)Exercise 5: PCA (15 points)¶
Complete pca(X, k), returning the projected data Z (shape (n, k)) and the explained variance ratio of each of the components. Centre the data, compute the covariance matrix, use np.linalg.eigh, and sort the eigenvalues in decreasing order.
def pca(X, k):
raise NotImplementedError # TODO_D = load_digits().data
check('explained variance matches scikit-learn', lambda: np.allclose(pca(_D, 5)[1], PCA(5).fit(_D).explained_variance_ratio_))
check('projections match (up to sign)', lambda: np.allclose(np.abs(pca(_D, 3)[0]), np.abs(PCA(3).fit_transform(_D)), atol=1e-6))Question. How many components keep 80% of the digits’ variance? Compute it.
# TODOExercise 6: An Autoencoder (15 points)¶
Complete make_autoencoder(k): an nn.Sequential from 64 inputs down to a code of k numbers and back to 64 outputs in (end with a Sigmoid), with at least one hidden ReLU layer on each side. The training loop is given. Target: with , a lower test reconstruction error than PCA with 8 components.
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):
raise NotImplementedError # TODO
def train_autoencoder(model, X, epochs=200, 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()
opt.zero_grad(); loss.backward(); opt.step()
return modeldef _ae_ok():
torch.manual_seed(0)
model = train_autoencoder(make_autoencoder(8), T_tr)
with torch.no_grad():
ae_err = ((model(T_te) - T_te) ** 2).mean().item()
code_ok = min(m.out_features for m in model if isinstance(m, nn.Linear)) <= 8
p = PCA(8).fit(D_tr)
pca_err = ((p.inverse_transform(p.transform(D_te)) - D_te) ** 2).mean()
print(f' test reconstruction error: autoencoder {ae_err:.4f}, PCA {pca_err:.4f}')
return code_ok and ae_err < pca_err
check('an 8-number code that beats PCA', _ae_ok)Challenge: One EM Step (+10 points)¶
For a 1-D mixture of two Gaussians with weights pi, means mu and standard deviations sigma (arrays of length 2), complete em_step(x, pi, mu, sigma):
E-step: responsibilities ;
M-step: with : , , (using the new ).
Return the new pi, mu, sigma.
def normal_pdf(x, mu, sigma):
return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * np.sqrt(2 * np.pi))
def em_step(x, pi, mu, sigma):
raise NotImplementedError # TODO_rng = np.random.default_rng(0)
_xs = np.concatenate([_rng.normal(-2, 0.5, 300), _rng.normal(3, 1.0, 700)])
def _em_ok():
pi, mu, sigma = np.array([0.5, 0.5]), np.array([-1.0, 1.0]), np.array([1.0, 1.0])
for _ in range(100):
pi, mu, sigma = em_step(_xs, pi, mu, sigma)
print(f' weights {pi.round(3)}, means {mu.round(3)}, standard deviations {sigma.round(3)}')
return np.allclose(pi, [0.3, 0.7], atol=0.02) and np.allclose(mu, [-2, 3], atol=0.1) and np.allclose(sigma, [0.5, 1.0], atol=0.1)
check('100 EM steps recover the two Gaussians', _em_ok)Lab Report¶
Submit this notebook with every check cell showing ✅ and your answer to the question in Exercise 5.