Clustering and PCA
Two core unsupervised tools: k-means clustering (Lloyd's algorithm, k-means++ initialisation, choosing K) and principal component analysis for dimensionality reduction — with an interactive k-means playground.
Without labels, we can still learn a lot from the shape of data. [[clustering|Clustering]] groups similar examples (customer segments, document topics, image colour palettes). Dimensionality reduction compresses many features into a few (for plots, speed, or denoising). This lesson covers the most widely used method of each: [[k-means]] and [[pca|PCA]][5][6].
k-means (Lloyd's algorithm)
- Initialise: choose K starting centroids.
- Assign: put each point in the cluster of its nearest centroid (Euclidean distance).
- Update: move each centroid to the mean of the points assigned to it.
- Repeat 2–3 until assignments stop changing (or a maximum number of iterations).
- Inertia (WCSS)
- within-cluster sum of squares: total squared distance of points to their own centroid (
inertia_in scikit-learn) - Σₖ
- sum over all K clusters k
- Σ_{x ∈ Cₖ}
- sum over every point x that belongs to cluster k
- ∈
- “is an element of”, “belongs to”
- Cₖ
- the set of points currently assigned to cluster k
- ‖x − μₖ‖²
- squared Euclidean distance from point x to its centroid
- μₖ
- mu-k — the centroid (mean point) of cluster k
▸Worked example
Both steps can only lower (or keep) the inertia, so the algorithm always converges — but to a local minimum that depends on the starting centroids[1]. Finding the global optimum is NP-hard in general, so in practice we run k-means several times from different starts (n_init) and keep the best.
Smarter starts: k-means++
Random initialisation can place two centroids in the same blob and none in another. k-means++ (Arthur & Vassilvitskii, 2007) picks the first centroid at random, then each next centroid with probability proportional to D(x)², the squared distance to the nearest centroid already chosen — so new centroids tend to land far from existing ones. This simple change gives a provable O(log K) approximation guarantee in expectation and usually faster, better results[2]. It is scikit-learn's default.
- Blobs, K = the true number of blobs: press Step repeatedly. Watch the centroid trails and the inertia readout — it never goes up.
- Set K too low: distinct blobs get merged. Set K too high: real blobs are chopped into pieces — yet inertia is *lower*. Inertia always falls as K grows, so it cannot choose K by itself.
- Look at the elbow chart: the ‘knee’ where the curve stops dropping steeply is a reasonable K.
- Re-initialise with random several times: sometimes two centroids share one blob and the result is clearly worse. Switch to k-means++: much more consistent.
- Moons dataset: k-means cuts straight across the two crescents. It assumes roughly round, similar-sized clusters, because each cluster is ‘everything closest to one centre’.
- Uniform dataset: k-means still returns K neat clusters — even though there is no real structure.
- What it is
- The number of clusters k-means must create. It is not learned — you choose it.
- ↑ If you increase it
- Inertia always decreases; clusters become smaller and more specific, eventually splitting natural groups (at K = n every point is its own cluster, inertia 0).
- ↓ If you decrease it
- Coarser groups; distinct populations get merged and the centroid sits between them, describing no one well.
- Typical values
- Choose with the elbow method, the silhouette score, and — most importantly — what is useful for the business (e.g. 4–8 marketing segments).
- What it is
- How many times k-means is run with different initial centroids; the run with the lowest inertia is kept.
- ↑ If you increase it
- More likely to find a good (lower-inertia) solution and more reproducible results; runtime grows linearly.
- ↓ If you decrease it
- Faster, but more exposed to an unlucky start (especially with random initialisation).
- Typical values
- scikit-learn ≥ 1.4 uses
n_init="auto": 1 run with k-means++, 10 with random init. 10 is a safe explicit choice.
Choosing K
Elbow method: plot inertia vs K and look for the bend. Silhouette score: for each point, a = mean distance to its own cluster, b = mean distance to the nearest other cluster; s ranges from −1 (probably in the wrong cluster) to 1 (well separated). Pick the K with the highest average s. Neither is decisive — combine them with domain sense[5].
- s(i)
- silhouette score of point i, from −1 to 1. The overall score is the average over all points
- a(i)
- mean distance from i to the other points in its own cluster (cohesion; smaller is better)
- b(i)
- mean distance from i to the points of the nearest other cluster (separation; larger is better)
- max
- the larger of the two values; dividing by it keeps s between −1 and 1
▸Worked example
| Method | Cluster shapes | Need K? | Notes |
|---|---|---|---|
| k-means | round, similar size | yes | fast, scales to millions of points |
| DBSCAN | any shape (density-based) | no (eps, min_samples instead) | marks outliers as noise; struggles with varying density |
| Agglomerative (hierarchical) | depends on linkage | cut the tree at any level | dendrogram shows nested groups; O(n²) memory |
| Gaussian mixture | ellipses | yes | soft (probabilistic) assignments |
Principal Component Analysis (PCA)
[[pca|PCA]] (Pearson, 1901) finds new axes — principal components — along which the data vary the most. The first component is the direction of maximum variance; the second is the direction of maximum remaining variance perpendicular to the first, and so on. Keeping only the first few components gives the best linear compression of the data in the least-squares sense[3][4].
- Center the data (subtract each feature's mean) and usually standardise it — otherwise features with big units dominate.
- Compute the covariance matrix of the features.
- Its eigenvectors are the principal components; each eigenvalue is the variance along that component. (In practice, libraries use the SVD of the data matrix.)
- Project each example onto the top k components to get k new features.
- Σ
- here: the covariance Matrix (d×d for d features) — not the sum sign
- (1/(n−1))
- average over n examples (n − 1 gives the unbiased sample estimate)
- XᵀX
- X transposed times X: sums of products of every feature pair
- X
- data matrix, n rows × d features, centred = each column's mean subtracted
- vⱼ
- the j-th eigenvector = the j-th principal component (a unit-length direction)
- λⱼ
- lambda-j — the eigenvalue: the variance of the data along vⱼ
- explained variance ratio of PC j
- fraction of all variance captured by principal component j (
explained_variance_ratio_) - Σᵢ
- this one IS a sum: over all components i
- λᵢ
- the i-th eigenvalue; their total = total variance of the data
- z
- the new k-dimensional representation of x (the PCA scores)
- Vₖᵀ
- the top k eigenvectors as rows (k×d): k dot products at once
- x
- an original example (d features)
- μ
- mean vector of the training data (subtracted to centre)
▸Worked example
- What it is
- How many principal components to keep. In scikit-learn it can be an integer, or a fraction like 0.95 meaning ‘keep enough components to explain 95% of the variance’.
- ↑ If you increase it
- Keeps more information (higher explained variance, lower reconstruction error), but less compression and less denoising; at all components PCA is just a rotation.
- ↓ If you decrease it
- Stronger compression and faster downstream models, but subtle yet important variation may be thrown away. 2–3 components are used for plotting.
- Typical values
- 2 or 3 for visualisation; 0.90–0.99 of variance for preprocessing. Inspect the cumulative explained-variance curve.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, _ = load_digits(return_X_y=True) # 1797 images of 8×8 = 64 pixel features
# (all pixels share the same units; with mixed units, StandardScaler first)
pca = PCA(n_components=0.90) # keep 90% of the variance
Z = pca.fit_transform(X)
print(Z.shape[1], "components kept") # ~21 instead of 64
print(pca.explained_variance_ratio_[:3].round(3))
for k in range(2, 13):
km = KMeans(n_clusters=k, init="k-means++", n_init=10, random_state=0).fit(Z)
print(k, "inertia", round(km.inertia_), "silhouette", round(silhouette_score(Z, km.labels_), 3))▸Go deeper: t-SNE, UMAP and the link to Gaussian mixtures
- t-SNE (van der Maaten & Hinton, 2008) and UMAP are non-linear methods that preserve local neighbourhoods and make beautiful 2D maps of embeddings. Distances between far-apart clusters and cluster sizes in these plots are not meaningful, and they are for visualisation, not preprocessing.
- k-means is a limiting case of fitting a Gaussian mixture model with the EM algorithm, when all clusters share the same tiny spherical variance and assignments become hard.
- PCA via SVD: if X = UΣVᵀ (X centred), the columns of V are the principal directions and the squared singular values divided by (n − 1) are the variances. Jolliffe & Cadima give a modern review[4].
Quiz
References
- [1]Least squares quantization in PCMPaperLloyd1982doi.org
- [2]k-means++: The Advantages of Careful SeedingPaperArthur & Vassilvitskii2007dl.acm.org
- [3]On Lines and Planes of Closest Fit to Systems of Points in SpacePaperPearson1901doi.org
- [4]Principal component analysis: a review and recent developmentsPaperJolliffe & Cadima2016doi.org
- [5]scikit-learn User Guide — ClusteringDocsscikit-learn developersscikit-learn.org
- [6]scikit-learn User Guide — Decomposing signals in components (PCA)Docsscikit-learn developersscikit-learn.org