Math & Machine Learning Foundations
Unsupervised Learning: k-means, Gaussian Mixtures and EM, PCA, t-SNE and UMAP
Intermediate 35 min For: Researchers
Key takeaways
- ▸Unsupervised learning has inputs X but no labels y. Its goal is to find structure: clustering groups similar samples, dimensionality reduction summarises high-dimensional data with a few coordinates, and density estimation models the probability distribution of the data.
- ▸k-means alternates between assigning each point to its nearest centre and moving each centre to the mean of its points. Neither step increases the within-cluster sum of squares (inertia), but only a local optimum is guaranteed. k-means++ picks initial centres with probability proportional to squared distance, and Arthur and Vassilvitskii (2007) proved its expected result is within a Θ(log k) factor of optimal.
- ▸A Gaussian mixture model gives each point a probability of belonging to each cluster (soft assignment) and is fitted by maximum likelihood with EM: the E-step computes posterior responsibilities under the current parameters, the M-step re-estimates means, covariances and mixing weights weighted by those responsibilities, and the log-likelihood never decreases (Dempster et al., 1977).
- ▸PCA finds the orthogonal directions of greatest variance and can be computed directly from the SVD of the centred data; it is linear, invertible and interpretable. t-SNE and UMAP are non-linear methods that preserve local neighbourhoods and suit visualisation, but cluster sizes and between-cluster distances on their plots cannot be read literally.
- ▸Without labels, cluster quality must be judged from several kinds of evidence: internal indices such as silhouette and BIC, ARI when some labels exist, and manual inspection of each cluster. Different indices can suggest different values of k.
Summary: Supervised learning maps inputs to outputs from labelled examples. Unsupervised learning has only inputs and asks different questions: what natural groups exist in the data, can it be described with fewer dimensions, and what distribution does it follow? This lesson moves from k-means to density-based clustering, Gaussian mixtures and EM, PCA, t-SNE and UMAP, and finally cluster evaluation. Every number quoted comes from the runnable example at the end.
This lesson belongs to the Unsupervised Learning unit. The prerequisites are Overfitting, Generalisation and Data Splits and Linear Algebra; the EM section uses maximum likelihood from Probability, Statistics and Information Theory. Continue with Neural Networks and Backpropagation and Tokens and Embeddings. Related algorithm cards: k-means, DBSCAN, EM, PCA, t-SNE, UMAP and autoencoders.
What unsupervised learning is for
| Task | Output | Typical methods | Example in work with large models |
|---|---|---|---|
| Clustering | A cluster id per sample (or a probability per cluster) | k-means, DBSCAN, Gaussian mixtures | Grouping user questions by topic; finding duplicate or anomalous training samples |
| Dimensionality reduction | Low-dimensional coordinates per sample | PCA, t-SNE, UMAP, autoencoders | Plotting 768-dimensional or larger embeddings in 2-D; compressing features |
| Density estimation | A probability distribution p(x) | Gaussian mixtures, kernel density estimation | Anomaly detection: very improbable samples may be outliers |
There is no ground truth to compare against, so the last section of this lesson is devoted to evaluating results.
k-means and k-means++
k-means splits n points into k groups so that the sum of squared distances from each point to its cluster centre is as small as possible. This quantity is called the inertia, or within-cluster sum of squares:
Objective J = Σᵢ ‖xᵢ − μ_c(i)‖² c(i) is the cluster of point i, μ_c the centre of cluster c
Steps 1. Assign: give each point to its nearest centre
2. Update: move each centre to the mean of its points
repeat 1–2 until assignments stop changing
This iteration is usually called Lloyd's algorithm (Lloyd, formally published in 1982). Neither step increases J, so the algorithm always converges, but only to a local optimum: Arthur and Vassilvitskii (2007) note at the start of their paper that solving the objective exactly is NP-hard, even with just two clusters.
Initialisation therefore matters. k-means++ picks the first centre uniformly from the data, then samples each new centre with probability proportional to its squared distance to the nearest centre already chosen, so points far from existing centres are more likely to be picked. The authors prove that the expected objective is within a Θ(log k) factor of optimal. On the handwritten-digits data (1,797 samples, 64 dimensions), running 20 random seeds with a single initialisation each gives a mean inertia of 1,189,680 and a worst case of 1,240,658 for random initialisation, against 1,178,526 and 1,218,629 for k-means++.
scikit-learn's KMeans uses k-means++ by default. Since version 1.4 n_init defaults to 'auto', which runs k-means++ once and random initialisation 10 times, keeping the result with the lowest inertia.
k-means implicitly assumes clusters that are roughly convex and similar in size, and features on comparable scales. Features are usually standardised first; text embeddings are often L2-normalised so that Euclidean distance is monotonically related to cosine similarity.
DBSCAN: density-based clustering
DBSCAN, proposed by Ester et al. (1996), does not need the number of clusters in advance. Instead it defines density with two parameters, a radius eps and a minimum count min_samples:
- Core point: has at least min_samples points within eps;
- Border point: not a core point, but within eps of a core point;
- Noise point: neither, labelled −1.
Core points that are density-reachable from one another, together with their border points, form a cluster, so clusters can take any shape. The example compares methods on two interleaving half-moons (500 points): k-means with k=2 reaches an adjusted Rand index (ARI, see the last section) of only 0.257, because it can only split the plane with a straight boundary, while DBSCAN (eps=0.2, min_samples=5) reaches 1.000, finding exactly 2 clusters with no noise points. DBSCAN is sensitive to eps and struggles when clusters have very different densities; HDBSCAN extends it to a hierarchical version that handles varying densities, and scikit-learn has provided HDBSCAN since version 1.3.
Gaussian mixture models and EM
k-means gives each point one definite cluster (hard assignment). A Gaussian mixture model (GMM) assumes the data were generated by K Gaussian distributions mixed with weights π₁…π_K:
p(x) = Σₖ πₖ · N(x | μₖ, Σₖ) Σₖ πₖ = 1
The posterior probability that point i came from component k is called its responsibility rᵢₖ; this is soft assignment. The parameters θ = {πₖ, μₖ, Σₖ} are estimated by maximum likelihood, but which component produced each point is an unobserved latent variable, which makes direct maximisation hard. The EM algorithm, formalised by Dempster, Laird and Rubin (1977), alternates two steps:
E-step rᵢₖ = πₖ · N(xᵢ | μₖ, Σₖ) / Σⱼ πⱼ · N(xᵢ | μⱼ, Σⱼ) responsibilities under current parameters
M-step Nₖ = Σᵢ rᵢₖ
πₖ = Nₖ / n
μₖ = Σᵢ rᵢₖ · xᵢ / Nₖ
Σₖ = Σᵢ rᵢₖ · (xᵢ − μₖ)(xᵢ − μₖ)ᵀ / Nₖ parameters weighted by responsibilities
The paper proves that no iteration decreases the log-likelihood of the observed data, though, as with k-means, only convergence to a local optimum is guaranteed. The example implements one-dimensional two-component EM in NumPy on data drawn from N(−2, 0.8²) and N(3, 1.2²) in a 3:7 ratio. After 50 iterations the log-likelihood rises from −3604.4 to −2034.5 without ever decreasing, and the estimates are π = (0.303, 0.697), μ = (−2.02, 2.955) and σ = (0.815, 1.117).
k-means can be viewed as a special case of a GMM: when all components share a spherical covariance that shrinks towards zero, responsibilities become 0 or 1, the E-step becomes "assign to the nearest centre" and the M-step becomes "take the mean".
The number of GMM components can be chosen with BIC (Bayesian information criterion), which adds a penalty growing with the number of parameters to the negative log-likelihood; lower is better. The example first reduces the digits to 20 dimensions with PCA and then fits full-covariance GMMs. Across 6, 8, 10, 12, 14 and 16 components, BIC is lowest at 10 (213,941), and that GMM reaches an ARI of 0.842 against the true digit labels, higher than the 0.666 of k-means on the raw 64 dimensions.
Principal component analysis (PCA)
PCA looks for orthogonal directions such that the data have maximum variance along the first, maximum remaining variance along the second subject to being orthogonal to the first, and so on. The idea goes back to Pearson's (1901) lines and planes of closest fit and Hotelling's (1933) principal components.
1. Centre: X̃ = X − mean
2. SVD: X̃ = U · S · Vᵀ
3. Principal directions = first k columns of V; variance of component j = sⱼ² / (n − 1)
4. Reduced coordinates = X̃ · V_k; explained-variance ratio = sⱼ² / Σ s²
There are two equivalent views of PCA: maximising the variance of the projection, or minimising the squared error of reconstructing the data from the projection. The latter is an application of the Eckart–Young theorem from the Linear Algebra lesson. In the example, the first 2 principal components of the digits explain only 28.5% of the variance and 21 components are needed to reach 90%, so a 2-D PCA plot discards a great deal of information.
PCA is used for initial reduction before visualisation (t-SNE and UMAP are often run on a few dozen PCA components), for denoising and compression, and for removing linear correlation between features. It captures only linear structure and is sensitive to feature scales, so features are usually standardised first.
t-SNE and UMAP: non-linear visualisation
t-SNE (van der Maaten and Hinton, 2008) turns pairwise similarities in the high-dimensional space into probabilities and then finds 2-D or 3-D coordinates that minimise the KL divergence between the low- and high-dimensional similarity distributions. It uses a heavy-tailed Student-t distribution in the low-dimensional space to ease the "crowding problem" that arises when many high-dimensional points are squeezed into few dimensions. Its main parameter, perplexity, roughly corresponds to the effective number of neighbours each point considers; the original paper gives typical values between 5 and 50.
UMAP (McInnes et al., 2018) builds a neighbourhood graph from manifold assumptions and fuzzy topology and then optimises a low-dimensional layout. The authors state in the abstract that it is competitive with t-SNE for visualisation quality, arguably preserves more of the global structure, and runs faster; unlike t-SNE, UMAP can transform new samples. Its main parameters are n_neighbors (larger values emphasise global structure) and min_dist (how tightly points may be packed in the embedding).
Both preserve local neighbourhoods well. The example measures trustworthiness (k=5; whether neighbours in the embedding are also neighbours in the original space, maximum 1) for 2-D embeddings of the digits: PCA 0.830, t-SNE 0.995 and UMAP 0.990.
Read such plots with care. The following points all come from synthetic-data experiments in the Distill article "How to Use t-SNE Effectively" (Wattenberg et al., 2016):
- Hyperparameters matter: the same data can take very different shapes at different perplexities, so compare several settings.
- Cluster sizes mean nothing: t-SNE expands dense clusters and contracts sparse ones.
- Distances between clusters might not mean anything: two far-apart clusters are not necessarily more different than two close ones.
- Random noise can look structured: small clumps do not prove the data contain such groups.
Kobak and Berens (2019) summarise ways to improve the global structure of t-SNE for single-cell data, including PCA initialisation; scikit-learn's TSNE has defaulted to init="pca" since version 1.2. Use visualisations to form hypotheses, and confirm clustering conclusions in the original or PCA space.
Evaluating clusters
| Index | Needs true labels? | Meaning | Source |
|---|---|---|---|
| Inertia (within-cluster sum of squares) | No | Smaller is more compact, but it always falls as k grows, so only the "elbow" is informative | k-means objective |
| Silhouette score | No | Per point s = (b − a) / max(a, b), where a is the mean distance to points in the same cluster and b the mean distance to the nearest other cluster; ranges from −1 to 1, higher is better | Rousseeuw (1987) |
| BIC | No (needs a probabilistic model) | Log-likelihood minus a penalty on the number of parameters, used to compare GMM sizes; lower is better | scikit-learn Gaussian mixture guide |
| Adjusted Rand index (ARI) | Yes | Agreement between two partitions corrected for chance; about 0 for random labelling and 1 for perfect agreement | Hubert and Arabie (1985) |
In the example, silhouette scores on the digits for k = 5, 8, 10, 12 and 15 are 0.138, 0.178, 0.183, 0.185 and 0.174: the maximum is at k=12 rather than at the true number of classes, 10, and all values are modest. Internal indices reflect only geometric compactness and separation, which need not match the categories people care about. In practice ARI is available only when some labels exist, and the final judgement usually also requires sampling each cluster and naming it.
Runnable example
The code below was run on scikit-learn 1.9, NumPy 2.5 and umap-learn 0.6, and its output matches the numbers above (t-SNE and UMAP results may vary slightly across versions and thread counts).
import numpy as np
from sklearn.datasets import load_digits, make_moons
from sklearn.cluster import KMeans, DBSCAN
from sklearn.mixture import GaussianMixture
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.metrics import adjusted_rand_score as ari, silhouette_score
X, y = load_digits(return_X_y=True) # 1,797 8×8 handwritten digits, 64 dimensions
# 1) Random vs k-means++ initialisation: 20 seeds, one initialisation each
for init in ("random", "k-means++"):
inert = [KMeans(10, init=init, n_init=1, random_state=s).fit(X).inertia_ for s in range(20)]
print(f"{init:10s} inertia mean {np.mean(inert):.0f} worst {np.max(inert):.0f}")
km = KMeans(10, n_init=10, random_state=0).fit(X)
print(f"k-means ARI = {ari(y, km.labels_):.3f}")
# 2) Silhouette scores
for k in (5, 8, 10, 12, 15):
lab = KMeans(k, n_init=10, random_state=0).fit_predict(X)
print(f"k={k:2d} silhouette {silhouette_score(X, lab):.3f}")
# 3) PCA explained variance
cum = np.cumsum(PCA().fit(X).explained_variance_ratio_)
print(f"first 2 components {cum[1]:.3f}; {np.searchsorted(cum, 0.90) + 1} needed for 90%")
# 4) Gaussian mixtures + BIC (after reducing to 20 dimensions)
Z = PCA(20, random_state=0).fit_transform(X)
for n in (6, 8, 10, 12, 14, 16):
print(n, round(GaussianMixture(n, covariance_type="full", random_state=0).fit(Z).bic(Z)))
g = GaussianMixture(10, covariance_type="full", random_state=0).fit(Z)
print(f"GMM(10) ARI = {ari(y, g.predict(Z)):.3f}")
# 5) Non-convex clusters: k-means vs DBSCAN
M, ym = make_moons(500, noise=0.05, random_state=0)
print("k-means ARI", round(ari(ym, KMeans(2, n_init=10, random_state=0).fit_predict(M)), 3))
print("DBSCAN ARI", round(ari(ym, DBSCAN(eps=0.2, min_samples=5).fit_predict(M)), 3))
# 6) Neighbourhood preservation of 2-D embeddings
P2 = PCA(2, random_state=0).fit_transform(X)
T2 = TSNE(2, perplexity=30, random_state=0).fit_transform(X)
print(f"trustworthiness PCA {trustworthiness(X, P2, n_neighbors=5):.3f} t-SNE {trustworthiness(X, T2, n_neighbors=5):.3f}")
# UMAP: import umap; umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0).fit_transform(X)
# 7) EM by hand: 1-D two-component Gaussian mixture
rng = np.random.default_rng(0)
x = np.concatenate([rng.normal(-2, 0.8, 300), rng.normal(3, 1.2, 700)])
pi, mu, var = np.array([0.5, 0.5]), np.array([-1.0, 1.0]), np.array([1.0, 1.0])
ll = []
for _ in range(50):
p = pi * np.exp(-(x[:, None] - mu) ** 2 / (2 * var)) / np.sqrt(2 * np.pi * var)
ll.append(np.log(p.sum(1)).sum())
r = p / p.sum(1, keepdims=True) # E-step: responsibilities
nk = r.sum(0); pi = nk / len(x) # M-step: weighted updates
mu = (r * x[:, None]).sum(0) / nk
var = (r * (x[:, None] - mu) ** 2).sum(0) / nk
print(f"log-likelihood {ll[0]:.1f} → {ll[-1]:.1f}, non-decreasing {bool(np.all(np.diff(ll) >= -1e-9))}")
print("π", pi.round(3), "μ", mu.round(3), "σ", np.sqrt(var).round(3))
Key outputs: random initialisation inertia mean 1,189,680 and worst 1,240,658, k-means++ mean 1,178,526 and worst 1,218,629; k-means ARI 0.666; silhouette 0.138 / 0.178 / 0.183 / 0.185 / 0.174; the first 2 components explain 28.5% of the variance and 21 are needed for 90%; BIC is lowest at 10 components (213,941) and the GMM ARI is 0.842; on the half-moons k-means ARI is 0.257 and DBSCAN ARI 1.000; trustworthiness is 0.830 for PCA, 0.995 for t-SNE and 0.990 for UMAP; the EM log-likelihood goes from −3604.4 to −2034.5.
Hands-on practice
- Unit project: take 1,000 sentences, embed them with any open sentence-embedding model and L2-normalise the vectors; cluster them with k-means, plot them in 2-D with UMAP, read 10 sentences from each cluster and name it, then check whether the names still make sense for other values of k.
- In the scikit-learn example gallery, find the clustering comparison example, compare k-means, DBSCAN and Gaussian mixtures on the same data, and vary DBSCAN's eps to see how the number of clusters changes.
- Run the PCA and Gaussian mixture notebooks in the Mathematics for Machine Learning companion repository and derive the EM M-step yourself using the formulas above.
- In the interactive Distill t-SNE article, set perplexity to 2, 30 and 100 and record how the plot of the same data changes.
Suggested order
Start with the method overview and the "Clustering performance evaluation" section of the scikit-learn clustering guide to get the big picture. For the mathematics, read chapters 10 (PCA) and 11 (Gaussian mixtures and EM) of Mathematics for Machine Learning. For visualisation, read the Distill t-SNE article and then the parameter and clustering sections of the UMAP documentation. Then move on to Neural Networks and Backpropagation, where autoencoders extend this lesson's dimensionality reduction to non-linear mappings.
FAQ
How do I choose k for k-means?
Common practice is to compute the silhouette score or the inertia curve (the 'elbow') over a range of k, compare BIC when using Gaussian mixtures, and then weigh the result against the intended use and manual spot checks. In this lesson's handwritten-digits example the silhouette score at k=12 is slightly higher than at k=10 (0.185 vs 0.183), while the Gaussian mixture BIC is lowest at 10 components. Indices do not always agree, and k ultimately depends on the purpose.
Which data suit k-means, DBSCAN and Gaussian mixtures?
k-means assumes roughly spherical clusters of similar size and is fast, which makes it a good baseline. DBSCAN (Ester et al., 1996) links samples by density, finds clusters of arbitrary shape and labels sparse points as noise, but is sensitive to eps and struggles when densities differ widely. Gaussian mixtures allow elliptical clusters and give soft assignment probabilities, at the cost of more parameters and more sensitivity to initialisation. The scikit-learn clustering guide has an overview table comparing the methods by geometry, scalability and parameters.
If two clusters are far apart on a t-SNE plot, are they very different?
Not necessarily. The interactive Distill article by Wattenberg et al. (2016) uses synthetic data to show that cluster sizes on a t-SNE plot mean nothing, that distances between clusters may mean nothing, that random noise can look structured, and that results change markedly with perplexity. Before interpreting a plot, try several perplexities and random seeds and cross-check with PCA or distances in the original space.
How is PCA related to autoencoders?
PCA is linear dimensionality reduction: encoding projects onto the top k principal components and decoding projects back, giving the smallest squared reconstruction error among all k-dimensional linear projections. An autoencoder uses neural networks for the encoder and decoder and can learn non-linear low-dimensional representations; Hinton and Salakhutdinov (2006) showed in Science that deep autoencoders can reduce dimensionality much better than PCA.
Are these classical methods still relevant in the era of large models?
Yes. Text and image embeddings are themselves high-dimensional data, and a common workflow is embed, reduce, cluster, then name the clusters by hand. BERTopic (Grootendorst, 2022), for example, creates document embeddings with a pre-trained model, reduces them with UMAP, clusters them with HDBSCAN and extracts topic words for each cluster with a class-based TF-IDF. The same methods are used to inspect training-data distributions, find duplicates and analyse the types of questions users ask.