AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
∿Classical Machine Learning
  1. Linear regression
  2. Gradient descent
  3. Classification: logistic regression, kNN, SVM
  4. Decision trees and ensembles
  5. Clustering and PCA
  6. Overfitting and the bias-variance trade-off
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Classical Machine Learning

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.

Intermediate~28 min·6 references
Key terms
Clusteringk-meansPrincipal component analysis (PCA)Unsupervised learningFeature scaling (normalisation / standardisation)Hyperparameter

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].

≈
Seating guests at K tables
Put K table signs randomly in a hall. Every guest walks to the nearest sign. Then move each sign to the middle of the guests standing at it. Guests look again and some switch to a now-closer sign. Repeat until nobody moves. That is k-means.

k-means (Lloyd's algorithm)

  1. Initialise: choose K starting centroids.
  2. Assign: put each point in the cluster of its nearest centroid (Euclidean distance).
  3. Update: move each centroid to the mean of the points assigned to it.
  4. Repeat 2–3 until assignments stop changing (or a maximum number of iterations).
Inertia (WCSS) = Σₖ Σ_{x ∈ Cₖ} ‖x − μₖ‖²
Within-cluster sum of squares: total squared distance from each point to its centroid μₖ. k-means minimises this.
In words: “for every cluster, for every point in it, take the squared distance to the cluster's centre, and add everything up”. Small inertia means points sit tightly around their centroids. k-means alternates assign/update steps that can only lower this number.
Symbols(hover a symbol in the formula)
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
Cluster 1: (1, 1), (1, 3) → μ₁ = (1, 2) squared distances: 0² + 1² = 1, 0² + 1² = 1 → 2 Cluster 2: (5, 5), (7, 5), (6, 8) → μ₂ = (6, 6) squared distances: 1 + 1 = 2, 1 + 1 = 2, 0 + 4 = 4 → 8 Inertia = 2 + 8 = 10 Note: inertia always drops as K grows (K = number of points gives 0), so do not pick K by its minimum.

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.

Loading interactive…
Choose a dataset and K, then step through assign → update, run to convergence, or re-initialise with random or k-means++ starts.
  • 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.
knobK (n_clusters)
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).
knobn_init
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) = (b(i) − a(i)) / max(a(i), b(i))
In words: “how much closer is point i to its own cluster than to the next-best cluster, as a fraction of the larger distance”. Near 1: much closer to its own cluster (good). Near 0: on the border. Negative: it is actually closer to another cluster — probably misassigned.
Symbols(hover a symbol in the formula)
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
Point well inside its cluster: a = 1, b = 4 s = (4 − 1) / max(1, 4) = 3/4 = 0.75 Point on the border: a = 2, b = 2 → s = 0 / 2 = 0 Point in the wrong cluster: a = 3, b = 2 s = (2 − 3) / max(3, 2) = −1/3 ≈ −0.33
MethodCluster shapesNeed K?Notes
k-meansround, similar sizeyesfast, scales to millions of points
DBSCANany shape (density-based)no (eps, min_samples instead)marks outliers as noise; struggles with varying density
Agglomerative (hierarchical)depends on linkagecut the tree at any leveldendrogram shows nested groups; O(n²) memory
Gaussian mixtureellipsesyessoft (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].

≈
Finding the best camera angle
Photographing a 3D object turns it into 2D. A bad angle (looking straight down a pencil) hides almost everything; a good angle shows its full length. PCA picks the ‘camera angle’ whose 2D shadow keeps as much of the spread of the data as possible.
  1. Center the data (subtract each feature's mean) and usually standardise it — otherwise features with big units dominate.
  2. Compute the covariance matrix of the features.
  3. Its eigenvectors are the principal components; each eigenvalue is the variance along that component. (In practice, libraries use the SVD of the data matrix.)
  4. Project each example onto the top k components to get k new features.
Σ = (1/(n−1)) · XᵀX (X centred) Σ·vⱼ = λⱼ·vⱼ explained variance ratio of PC j = λⱼ / Σᵢ λᵢ z = Vₖᵀ (x − μ)
In words: Four steps of PCA. (1) The covariance matrix Σ records how every pair of features varies together. (2) Its eigenvectors vⱼ are directions that Σ only stretches, not rotates; the stretch factor λⱼ is the variance along that direction. (3) Each component's share of the total variance tells you how much information it keeps. (4) A point is compressed by centring it and taking dot products with the top k directions.
Symbols(hover a symbol in the formula)
Σ
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
Centred data, n = 4: (2, 2), (−2, −2), (1, −1), (−1, 1) XᵀX = [[10, 6], [6, 10]] → Σ = XᵀX / 3 ≈ [[3.33, 2], [2, 3.33]] Eigenvectors: v₁ = [0.707, 0.707] with λ₁ = 3.33 + 2 ≈ 5.33 v₂ = [0.707, −0.707] with λ₂ = 3.33 − 2 ≈ 1.33 Check: Σ·v₁ = [3.33·0.707 + 2·0.707, …] ≈ 5.33 · v₁ ✓ Explained variance ratio PC1 = 5.33 / (5.33 + 1.33) = 0.8 → 80% Project x = (2, 2) onto PC1 (μ = 0): z = 0.707·2 + 0.707·2 ≈ 2.83
knobn_components
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.
python
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))
Compress with PCA, then cluster and compare inertia (elbow) with silhouette for each K.
!
Pitfalls
Scale first: both k-means and PCA use distances/variances, so a feature in rupiah outweighs one in years. k-means always finds K clusters, even in random noise — validate them. Non-spherical clusters (moons, rings) need DBSCAN, spectral clustering or GMMs. PCA is linear and maximises variance, which is not always what matters for your task. Components are blends of all features and can be hard to interpret. Fit PCA on training data only (inside a Pipeline) to avoid leakage.
▸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

1.
In the update step of k-means, each centroid moves to…
2.
Why can't you pick K simply by choosing the K with the lowest inertia?
3.
What does k-means++ change compared to plain k-means?
4.
You run PCA on unscaled data with income (in rupiah) and age (in years). What will the first component mostly be?
5.
k-means on the two-moons dataset gives a poor split. Why?
Score: 0/5

References

  1. [1]
    Least squares quantization in PCM
    PaperLloyd1982doi.org
  2. [2]
    k-means++: The Advantages of Careful Seeding
    PaperArthur & Vassilvitskii2007dl.acm.org
  3. [3]
    On Lines and Planes of Closest Fit to Systems of Points in Space
    PaperPearson1901doi.org
  4. [4]
    Principal component analysis: a review and recent developments
    PaperJolliffe & Cadima2016doi.org
  5. [5]
    scikit-learn User Guide — Clustering
    Docsscikit-learn developersscikit-learn.org
  6. [6]
    scikit-learn User Guide — Decomposing signals in components (PCA)
    Docsscikit-learn developersscikit-learn.org
← Previous
Decision trees and ensembles
Next →
Overfitting and the bias-variance trade-off