Unsupervised Learning
Labels are expensive, and much of the world's data has none: customer purchase logs, sensor streams, documents, images. Unsupervised learning finds structure in data without labels. There is no teacher marking answers, so the question changes from "predict " to "what does this data look like?"
Three main tasks
| Task | Question | Typical methods | Uses |
|---|---|---|---|
| Clustering | Which examples belong together? | k-means, hierarchical clustering, DBSCAN, Gaussian mixtures | customer segments, grouping documents, image compression |
| Dimensionality reduction | Can fewer numbers describe each example? | PCA, SVD, t-SNE, UMAP, autoencoders | visualisation, compression, faster models, removing noise |
| Anomaly detection | Which examples do not look like the rest? | isolation forest, distance or density scores, one-class models | fraud, machine faults, data quality checks |
Related tasks are density estimation (how likely is this example?) and association rules (which products are bought together?).
k-means, step by step
k-means splits the data into groups. It keeps centroids (centre points) and repeats two steps until nothing changes:
- Assign: every point joins the cluster of its nearest centroid.
- Update: every centroid moves to the mean of the points in its cluster.
Each round lowers the inertia, the sum of squared distances from points to their centroids:
where is the centroid of the cluster that point belongs to. Step through it below. The three centroids start badly, on three points of the same group in the lower left, and the algorithm still finds the three groups in two iterations.
The inertia falls from 28392 after the first assignment to 819.4 at the end. No label was used: the groups come only from distances.
k-means from scratch and with scikit-learn
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=4) # labels thrown away
def kmeans(X, k, iters=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), size=k, replace=False)]
for it in range(iters):
dist = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(axis=2)
labels = dist.argmin(axis=1) # assign step
new = np.array([X[labels == j].mean(axis=0) for j in range(k)]) # update step
if np.allclose(new, centroids):
break
centroids = new
inertia = ((X - centroids[labels]) ** 2).sum()
return labels, centroids, inertia, it
labels, centroids, inertia, it = kmeans(X, 3)
print("from scratch: stopped after", it, "iterations, inertia", round(inertia, 1))
print("cluster sizes:", np.bincount(labels))
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print("scikit-learn: inertia", round(km.inertia_, 1), " sizes", np.bincount(km.labels_))from scratch: stopped after 3 iterations, inertia 542.1
cluster sizes: [ 96 100 104]
scikit-learn: inertia 542.1 sizes [100 96 104]
Both find the same three clusters with the same inertia, 542.1. The cluster numbers differ (scikit-learn's cluster 0 has 100 points, ours has 96): cluster ids are arbitrary names, not meaningful labels. scikit-learn runs k-means 10 times from different starts (n_init=10) and keeps the best, because a bad start can end in a poor solution.
Dimensionality reduction and anomalies
Two more unsupervised tools in a few lines. PCA (principal component analysis) finds the directions along which the data varies most; keeping the first few gives a compressed description. An isolation forest scores how easy each point is to isolate with random cuts: outliers are isolated quickly.
import numpy as np
from sklearn.datasets import load_digits, make_blobs
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
# Dimensionality reduction: 64 pixel columns squeezed into a few directions.
X = load_digits().data
pca = PCA(n_components=10).fit(X)
cum = np.cumsum(pca.explained_variance_ratio_)
print("variance kept by 2, 5, 10 components:", cum[[1, 4, 9]].round(3))
# Anomaly detection: which points do not look like the rest?
normal, _ = make_blobs(n_samples=200, centers=[[0, 0]], cluster_std=1.0, random_state=0)
odd = np.array([[6, 6], [-7, 5], [8, -6]])
data = np.vstack([normal, odd])
flags = IsolationForest(contamination=0.01, random_state=0).fit_predict(data) # -1 = anomaly
print("flagged rows:", np.where(flags == -1)[0])variance kept by 2, 5, 10 components: [0.285 0.545 0.738]
flagged rows: [200 201 202]
Ten directions keep 73.8 % of the variation in the 64 pixel values of the digit images, and two keep 28.5 %, enough for a rough 2-D map of the data. The isolation forest flags exactly rows 200, 201 and 202, the three points we added far from the cloud. We told it to expect about 1 % anomalies (contamination=0.01); choosing that share is a judgement call, since without labels nothing tells the algorithm what counts as abnormal.
How do you evaluate without labels?
This is the hard part of unsupervised learning. Options:
- Internal scores: inertia, the silhouette score (how much closer points are to their own cluster than to the next one). They measure compactness, not usefulness.
- Usefulness downstream: do the segments lead to better marketing? Do PCA features make a supervised model better or faster?
- Human inspection: look at examples from each cluster or the top-scored anomalies. Do they make sense to a domain expert?
- A few labels: if some labels exist, check how well clusters or anomaly scores agree with them.
The Classical ML Algorithms course covers the methods in depth; the Machine Learning course has hands-on lessons on k-means, hierarchical clustering, DBSCAN and PCA.
Pitfalls
- Unscaled features. Distances are dominated by the feature with the largest numbers (income in dollars beats age in years). Scale features first.
- Choosing blindly. k-means always returns clusters, even when the data has none. Try several and look at inertia, silhouette and the clusters themselves.
- Reading meaning into cluster numbers. Cluster 2 is not "better" than cluster 1, and the numbering can change between runs.
- Wrong shape assumptions. k-means assumes round, similar-sized clusters. For long or nested shapes, use DBSCAN or hierarchical clustering.
Practice
- What happens with for the same 13 points, starting from points 0 and 1?
Answer
Two of the three natural groups must share a centroid. From this start, the lower-left group gets one centroid at and the other two groups share a centroid at , between them and far from both. The algorithm converges after two iterations with inertia 4911.9, six times the 819.4 of . Comparing inertia across several values of is one way to choose .
- Why does the from-scratch k-means need a fixed
seedto give the same result every run?
Answer
The starting centroids are random points from the data. Different starts can converge to different clusterings (and different cluster numbers), so the seed makes the run reproducible.
Test yourself
What does unsupervised learning work with?
- Inputs with labels
- Inputs without labels
- Rewards from an environment
- Only images
What are the two alternating steps of k-means?
- Split and merge
- Assign points to the nearest centroid; move centroids to the mean of their points
- Compute gradients; update weights
- Label and train
scikit-learn's KMeans numbered the clusters differently from the from-scratch version but had the same inertia. What does this show?
- One of them is wrong
- Cluster numbers are arbitrary names; the grouping is the same
- scikit-learn uses labels
- Inertia is meaningless
Why should features usually be scaled before k-means?
- k-means only accepts values between 0 and 1
- Otherwise the feature with the largest numeric range dominates the distances
- Scaling adds labels
- It makes k-means supervised