Part 07 / Stage 2
Unsupervised learning
Goal: Find structure in data without labels: clusters, components, and anomalies. Time: ~2 hours · Needs: Parts 5–6
What you will learn
- Clustering with k-means
- Choosing k with the silhouette score
- Dimensionality reduction with PCA
- Visualising high-dimensional data, and the limits
- Anomaly detection with Isolation Forest
Topics in this part
Practice
Run from the repo root with PYTHONPATH=tools.
Exercise 1: Scaling matters
Create 300 rows with two features: normal(0, 1) and normal(0, 1000). Run k-means with k=2 on the raw data, then on standardized data, and print how many points land in each cluster both times. Explain in a comment what the raw version clustered on.
Show the solution to Exercise 1
# Exercise 1: Scaling matters
import numpy as np
from collections import Counter
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
X = np.c_[rng.normal(0, 1, 300), rng.normal(0, 1000, 300)]
raw = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
Xs = (X - X.mean(axis=0)) / X.std(axis=0)
scaled = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(Xs)
print("raw split: ", dict(Counter(raw.tolist())))
print("scaled split:", dict(Counter(scaled.tolist())))
# Raw: the second feature's huge range decides everything — the clusters are
# simply "feature 2 above/below its middle"; feature 1 is ignored entirely.
split_by_sign = ((X[:, 1] > np.median(X[:, 1])).astype(int) == raw).mean()
print("raw clusters match a feature-2 median split:",
round(max(split_by_sign, 1 - split_by_sign), 3))
Exercise 2: Silhouette on digits
Run k-means with k in [8, 10, 12] on the (scaled) digits data and print the silhouette for each. Does k=10 — the true number of digit classes — win?
Show the solution to Exercise 2
# Exercise 2: Silhouette on digits
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(load_digits().data)
for k in [8, 10, 12]:
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
print(f"k={k:2d} silhouette={silhouette_score(X, labels):.3f}")
# Real data rarely peaks cleanly at the "true" k: handwritten digits overlap
# (4s look like 9s), so the curve is flat — the lesson of section 2 in practice.
Exercise 3: PCA compression check
Project digits onto 21 components with PCA(n_components=21), reconstruct with inverse_transform, and print the mean squared reconstruction error. Compare with 5 components.
Show the solution to Exercise 3
# Exercise 3: PCA compression check
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X = load_digits().data
for n in [5, 21]:
pca = PCA(n_components=n).fit(X)
X_back = pca.inverse_transform(pca.transform(X))
mse = ((X - X_back) ** 2).mean()
print(f"{n:2d} components: reconstruction MSE = {mse:.3f}")
# 21 components reconstruct far better than 5 — matching the lesson's
# "90% of variance needs 21 components".
Exercise 4: Anomaly review
Generate 500 normal rows (normal(70, 10, (500, 2))) plus three planted outliers. Run IsolationForest(contamination=0.01) and print which row indices were flagged. Were all plants caught, and how many normals were swept up?
Show the solution to Exercise 4
# Exercise 4: Anomaly review
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.default_rng(0)
normal = rng.normal(70, 10, (500, 2))
plants = np.array([[200.0, 5.0], [10.0, 300.0], [250.0, 250.0]])
X = np.vstack([normal, plants])
iso = IsolationForest(contamination=0.01, random_state=0).fit(X)
flagged = np.where(iso.predict(X) == -1)[0]
print("flagged indices:", flagged.tolist())
print("all plants (500, 501, 502) caught:", all(i in flagged for i in [500, 501, 502]))
print("normal rows swept up:", int(sum(i < 500 for i in flagged)))
Mini-project: Customer segments
Cluster the churn customers on scaled numeric features (k from a silhouette sweep), print each segment's size, average tenure, charges, support calls and churn rate — and give each a plain-language name in a comment.
A complete version is in solutions/mini_customer_segments.py.
Stretch: compare k-means with DBSCAN and explain where they disagree.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| k-means on unscaled data | Big-range features decide everything | Standardize first |
| Trusting one silhouette number | Real peaks are shallow | Sweep k, then sanity-check cluster meaning |
| Reading t-SNE distances literally | Only neighbourhoods are meaningful | Verify hypotheses with statistics |
| PCA on unscaled mixed units | Variance = units, not information | Standardize before PCA too |
| Treating every anomaly flag as real | contamination forces a quota of flags |
Review flags; tune the rate |
Quick recap
- k-means assigns each point to its nearest centre; it needs scaled features and roughly round clusters.
- The silhouette score grades k, and it peaked at the true 4 on the generated blobs (0.811).
- PCA ranks directions by variance; the digits data needs only 21 of its 64 dimensions to keep 90%.
- 2D plots are hypothesis generators, not proofs — especially t-SNE.
- Isolation Forest isolates outliers fast; contamination sets the flag rate.
Checklist
- I can describe one k-means iteration.
- I swept k and read the silhouette curve.
- I can explain "21 components keep 90%" in plain words.
- I know what t-SNE plots do and do not show.
- I ran an Isolation Forest and reviewed its flags.
Read more: Clustering · Decomposition / PCA