Skip to content
BIASED

Dimensionality reduction

Describing an object by a few coordinates instead of dozens of features — PCA as largest variance and smallest reconstruction error via the SVD, explained variance and choosing the number of components, units and whitening, probabilistic and kernel PCA, how to read t-SNE and UMAP maps, and autoencoders as the nonlinear version.

Summarize features, not objects

The topic Mixtures and the EM algorithm explained every object by one hidden discrete variable: the component it came from. Clusters summarize objects, the rows of XX. This topic summarizes the columns instead: it replaces the dd features by a few new ones.

Take the digits of scikit-learn: 17971797 images of 8×88 \times 8 pixels, so each object is a vector x∈R64x \in \mathbb R^{64}. The images do not fill R64\mathbb R^{64}. They vary along far fewer directions: which digit it is, its slant, its width, the thickness of the stroke. The points lie near a thin region of low dimension. Describing each object by its position in that region helps in four ways:

  • looking: a scatter plot has two axes, and 64 features do not fit on it;
  • compression: kk numbers per object instead of dd, and everything downstream gets faster;
  • denoising: if the signal lives in a few directions and the noise in all of them, dropping the weak directions removes mostly noise;
  • distances: the topic Nearest neighbours showed that distances concentrate in high dimension; in a well-chosen low-dimensional space they say more.

The linear tool is already known from Mathematics for ML. The topic Symmetric matrices and quadratic forms found the direction of largest variance as the top eigenvector of the covariance. The topic The singular value decomposition got all such directions from the data matrix itself. Together this is principal component analysis, PCA. Here we use it as a learning method: why it is also the best reconstruction, how many components to keep, what units and whitening do, which probability model stands behind it, its kernel version, and the nonlinear maps used for looking.

Notation. The data are centred, ∑ixi=0\sum_i x_i = 0, and X∈Rn×dX \in \mathbb R^{n \times d} has rows xi⊤x_i^\top. The covariance is S=1nX⊤XS = \frac1n X^\top X, with eigenvalues λ1≥⋯≥λd≥0\lambda_1 \ge \dots \ge \lambda_d \ge 0 and orthonormal eigenvectors v1,…,vdv_1, \dots, v_d; in this topic λ\lambda is an eigenvalue, not a regularization strength. The letter k<dk < d is the number of components kept. W∈Rd×kW \in \mathbb R^{d \times k} has orthonormal columns, W⊤W=IkW^\top W = I_k, and zi=W⊤xi∈Rkz_i = W^\top x_i \in \mathbb R^k are the new coordinates of object ii.

Largest variance is smallest error

Keep kk numbers per object, zi=W⊤xiz_i = W^\top x_i, and rebuild the object from them as x^i=Wzi=WW⊤xi\hat x_i = W z_i = W W^\top x_i. Which WW rebuilds best? The map WW⊤W W^\top is an orthogonal projection, so the residual xi−x^ix_i - \hat x_i is perpendicular to x^i\hat x_i. By Pythagoras,

∥xi−WW⊤xi∥2=∥xi∥2−∥W⊤xi∥2.\lVert x_i - W W^\top x_i \rVert^2 = \lVert x_i \rVert^2 - \lVert W^\top x_i \rVert^2 .

Average over the objects:

1n∑i=1n∥xi−x^i∥2=tr⁡S−tr⁡(W⊤SW).\frac1n \sum_{i=1}^n \lVert x_i - \hat x_i \rVert^2 = \operatorname{tr} S - \operatorname{tr}(W^\top S W) .

The first term is the total variance, fixed by the data. The second is the variance kept by the projection. So the smallest reconstruction error and the largest kept variance are one problem with one answer: W=(v1,…,vk)W = (v_1, \dots, v_k). The error left is the sum of the discarded eigenvalues, ∑j>kλj\sum_{j > k} \lambda_j. These are the two historical origins of PCA: Pearson (1901) looked for the plane of closest fit, Hotelling (1933) for the components of largest variance.

A worked example. For the covariance S=(21.21.21)S = \begin{pmatrix} 2 & 1.2 \\ 1.2 & 1 \end{pmatrix} the eigenvalues are 2.82.8 and 0.20.2, and v1=(0.832,0.555)v_1 = (0.832, 0.555). The point x=(1,1)x = (1, 1) gets the coordinate z=v1⊤x=1.387z = v_1^\top x = 1.387 and the reconstruction x^=z v1=(1.154,0.769)\hat x = z\, v_1 = (1.154, 0.769). Its residual (−0.154,0.231)(-0.154, 0.231) has squared length 0.0770.077, and indeed ∥x∥2=2=1.3872+0.077\lVert x \rVert^2 = 2 = 1.387^2 + 0.077.

In practice nobody forms SS. As the topic The singular value decomposition showed, the SVD X=UΣV⊤X = U \Sigma V^\top of the centred data gives everything at once: the components are the right singular vectors vjv_j, the eigenvalues are λj=σj2/n\lambda_j = \sigma_j^2 / n, and the coordinates are XV=UΣXV = U\Sigma. The reconstruction XVkVk⊤X V_k V_k^\top is the truncated SVD XkX_k, so by Eckart–Young no rank-kk linear summary of the data does better. For large data a randomized SVD computes only the kk leading components.

One thing is new for learning. The mean is part of the fitted model. It is computed on the training set and subtracted from every new object before projecting, and added back after reconstructing.

How many components

The share of variance kept by the first kk components is the explained variance ratio:

λ1+⋯+λkλ1+⋯+λd.\frac{\lambda_1 + \dots + \lambda_k}{\lambda_1 + \dots + \lambda_d} .

One minus it is the relative reconstruction error. On the digits the first two components explain 14.9%14.9\% and 13.6%13.6\% of the variance. Five components explain half, 2121 explain 90%90\%, and 2929 explain 95%95\%. With 2121 components the mean squared reconstruction error per image is 116.3116.3, the sum of the 4343 discarded eigenvalues, out of a total variance of 1201.51201.5.

There is no single rule for kk. Four common ones:

  • a share of variance, such as 90%90\% or 95%95\%: simple, but the threshold is arbitrary;
  • the elbow of the scree plot, the eigenvalues in decreasing order: keep the components before the curve flattens into a floor of small, similar eigenvalues, which is what isotropic noise produces;
  • the downstream task: choose kk by the validation score of the model that uses the components, as in the topic Validation and overfitting;
  • the likelihood of probabilistic PCA, two blocks below.

The rules can disagree. Let ten features have covariance eigenvalues 4.34.3, 2.82.8, 1.31.3 and seven times 0.30.3: three directions of signal on top of noise of variance 0.30.3 in every direction. The scree plot drops after the third value and then stays flat. But those three explain only 8.4/10.5=80%8.4 / 10.5 = 80\% of the variance, so a 90%90\% rule keeps seven components, four of them pure noise.

In scikit-learn a fractional n_components applies the share rule. PCA centres the data itself.

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
 
X, y = load_digits(return_X_y=True)
pca = PCA(n_components=0.9).fit(X)
print(X.shape, pca.n_components_)
 
model = make_pipeline(PCA(n_components=21), LogisticRegression(max_iter=5000))
print(cross_val_score(model, X, y, cv=5).mean().round(3))
(1797, 64) 21
0.894

PCA uses no labels, but it is still a model fitted to data: the mean and the components are its parameters. Inside the pipeline, cross_val_score refits them on the training part of every fold.

Units and whitening

PCA depends on the units of the features. The same mass in grams has a thousand times the standard deviation it has in kilograms, and a million times the variance. Measured in grams, it takes over the first component. When features have unrelated units, standardize each one first, as in the topic Data, features and leakage; PCA then works with the correlation matrix instead of the covariance. When they share a unit, as pixels do, the raw covariance is usually right.

Whitening goes one step further and rescales every component to unit variance:

zi=Λk−1/2W⊤xi,Λk=diag⁡(λ1,…,λk).z_i = \Lambda_k^{-1/2} W^\top x_i, \qquad \Lambda_k = \operatorname{diag}(\lambda_1, \dots, \lambda_k) .

The new coordinates are uncorrelated and have unit variance, 1n∑izizi⊤=Ik\frac1n \sum_i z_i z_i^\top = I_k. This is the sample version of the whitening of a Gaussian vector from the topic The multivariate Gaussian. It helps methods that expect comparable, uncorrelated inputs: distance-based methods, independent component analysis, and gradient descent. For least squares on whitened inputs the matrix 1nZ⊤Z\frac1n Z^\top Z is IkI_k, so its condition number from the topic Gradient descent is 11.

The risk is the division by λj\sqrt{\lambda_j}. A direction with a tiny eigenvalue is often pure noise, and whitening stretches it to the same scale as the signal. So whitening goes together with truncation to kk components, or with a small constant added to every λj\lambda_j under the root. In scikit-learn, PCA(k, whiten=True) whitens only the kk components it keeps.

Probabilistic PCA

PCA as described so far is a projection, not a model. It gives no probability to an object. Probabilistic PCA (Tipping and Bishop, 1999) is the continuous relative of the Gaussian mixture from the previous topic. The hidden variable is now a vector z∼N(0,Ik)z \sim \mathcal N(0, I_k) instead of a component index. It is mapped linearly into the feature space and blurred by isotropic noise:

x=Wz+μ+ε,ε∼N(0,σ2Id).x = W z + \mu + \varepsilon, \qquad \varepsilon \sim \mathcal N(0, \sigma^2 I_d) .

By the rule for affine maps of a Gaussian vector from the topic The multivariate Gaussian, x∼N(μ, WW⊤+σ2Id)x \sim \mathcal N(\mu,\ W W^\top + \sigma^2 I_d): a Gaussian whose covariance is "rank kk plus noise". Here W∈Rd×kW \in \mathbb R^{d \times k} holds loadings and need not have orthonormal columns.

Its maximum likelihood solution is PCA again. The estimate of μ\mu is the sample mean, and

σ2=1d−k∑j>kλj,W=Vk(Λk−σ2Ik)1/2R,\sigma^2 = \frac{1}{d - k} \sum_{j > k} \lambda_j, \qquad W = V_k (\Lambda_k - \sigma^2 I_k)^{1/2} R ,

for any rotation RR (Bishop, 2006, Section 12.2.1). The columns of WW span the principal subspace, and the noise variance is the average of the discarded eigenvalues. In the ten-feature example of the previous blocks, k=3k = 3 gives σ2=0.3\sigma^2 = 0.3, the true noise. The columns of WW (with R=IR = I) have lengths 22, 1.581.58 and 11, the standard deviations of the three signals. On the digits with k=10k = 10 the noise variance is 5.835.83.

A density buys three things.

  • A likelihood for choosing kk. Draw 10001000 training and 10001000 held-out objects from the ten-feature example. The mean held-out log-likelihood per object is −11.977-11.977 at k=2k = 2, −11.315-11.315 at k=3k = 3 and −11.329-11.329 at k=4k = 4, and it stays below the peak for every larger kk: the maximum is at the true k=3k = 3. In scikit-learn this is PCA(k).fit(X_train).score(X_test).
  • EM. The model can be fitted by the EM algorithm of the previous topic, with the posterior of zz in the E-step. EM never forms the d×dd \times d covariance and handles missing values.
  • A score for unusual objects: an object the model finds improbable stands out. The next topic starts from this.

The course Bayesian Methods in Machine Learning puts a prior on WW in the topic EM and Bayesian PCA, and the prior then chooses kk by itself.

Kernel PCA

PCA finds linear structure only. Take two concentric rings in the plane. No direction separates them: every projection onto a line mixes the rings.

Kernel PCA (Schölkopf, Smola and Müller, 1998) runs PCA in a feature space φ(x)\varphi(x) reached through a kernel K(x,x′)=⟨φ(x),φ(x′)⟩K(x, x') = \langle \varphi(x), \varphi(x') \rangle, as the topic Kernels promised. The principal directions in feature space are combinations of the mapped objects, ∑iαiφ(xi)\sum_i \alpha_i \varphi(x_i). The eigenvalue problem then moves to the n×nn \times n Gram matrix Kij=K(xi,xj)K_{ij} = K(x_i, x_j), centred in feature space:

K~=K−1nK−K1n+1nK1n,K~α=nλα.\tilde K = K - \mathbf 1_n K - K \mathbf 1_n + \mathbf 1_n K \mathbf 1_n, \qquad \tilde K \alpha = n \lambda \alpha .

Here 1n\mathbf 1_n is the n×nn \times n matrix with all entries 1/n1/n, and α\alpha is scaled so that nλ α⊤α=1n \lambda\, \alpha^\top \alpha = 1, which gives the direction unit length. The coordinate of an object xx on a component is ∑iαiK~(xi,x)\sum_i \alpha_i \tilde K(x_i, x): kernels only, no φ\varphi.

With K(x,x′)=⟨x,x′⟩2K(x, x') = \langle x, x' \rangle^2 the feature space is φ(x)=(x12, 2 x1x2, x22)\varphi(x) = (x_1^2,\ \sqrt2\, x_1 x_2,\ x_2^2). The squared radius x12+x22x_1^2 + x_2^2, which tells the rings apart, is a linear function there. Take 400400 points on two noisy rings. A logistic regression on two ordinary principal components reaches a training accuracy of 0.5020.502, chance. On three kernel components it reaches 1.01.0. Both are fitted and scored on the same points, so they show what each representation can express linearly, not a test score. Only the third kernel component separates the rings on its own (1.01.0 against 0.530.53 and 0.5350.535): kernel PCA ranks directions by variance in feature space, not by usefulness.

The price is the one from the topic Kernels. The Gram matrix has n2n^2 entries and its eigenproblem costs about n3n^3 operations. A new object needs kernels with all nn training objects. And a component has no simple reading in the original features.

t-SNE and UMAP: maps for looking

For looking at data, keeping large distances is often the wrong goal. The two leading components of the digits keep 28.5%28.5\% of the variance, and the ten classes overlap heavily in that plane. t-SNE (van der Maaten and Hinton, 2008) asks instead that objects close in the data stay close in the plane. It works in three steps.

  1. Turn distances in the data into neighbour probabilities. For each xix_i, pj∣i∝exp⁡(−∥xi−xj∥2/2σi2)p_{j \mid i} \propto \exp\big(-\lVert x_i - x_j \rVert^2 / 2\sigma_i^2\big) over j≠ij \ne i. Each bandwidth σi\sigma_i is set so that the distribution has a chosen perplexity 2H(p⋅∣i)2^{H(p_{\cdot \mid i})}, with HH the entropy in bits: roughly the number of neighbours that count, typically 55 to 5050. Symmetrize: pij=(pj∣i+pi∣j)/2np_{ij} = (p_{j \mid i} + p_{i \mid j}) / 2n.
  2. Define similar probabilities for points yiy_i in the plane, with a heavy-tailed Student-tt kernel: qij∝(1+∥yi−yj∥2)−1q_{ij} \propto (1 + \lVert y_i - y_j \rVert^2)^{-1}, normalized over all pairs.
  3. Move the yiy_i by gradient descent to minimize DKL(P ∥ Q)=∑i≠jpijlog⁡(pij/qij)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{i \ne j} p_{ij} \log (p_{ij} / q_{ij}), the divergence from the topic Entropy, cross-entropy and KL of Generative Models.

The order of PP and QQ in the divergence decides which mistakes are expensive. The heavy tail fights the crowding problem: in 64 dimensions an object can have many neighbours at the same distance, in the plane it cannot. The tt kernel lets moderately distant objects move far away instead of piling up in the middle. On the digits, 58.4%58.4\% of the 1010 nearest neighbours of each image in R64\mathbb R^{64} stay among its 1010 nearest neighbours in a t-SNE map (perplexity 3030). In the two-component PCA plane only 11.8%11.8\% do.

UMAP (McInnes, Healy and Melville, 2018) follows the same plan with other choices: a weighted graph of kk nearest neighbours in the data, a similar graph in the plane, and a cross-entropy between their edge weights minimized by SGD. It is much faster, scales to millions of objects and can place new ones.

How to read such maps (Wattenberg, Viégas and Johnson, 2016):

  • the perplexity, or for UMAP the number of neighbours, changes the picture, so look at several values and seeds;
  • the area of a cluster says nothing about its spread in the data: t-SNE expands dense clusters and shrinks sparse ones;
  • distances between clusters may mean nothing;
  • random noise can look clustered, especially at low perplexity;
  • a ring or a line in one map may be an artefact of that run.

The axes carry no meaning, and plain t-SNE has no map for new objects. A map is for looking, not for measuring, and its coordinates are poor features for a model.

Autoencoders, and then anomalies

PCA is the best linear encoder–decoder pair: encode z=W⊤xz = W^\top x, decode x^=Wz\hat x = W z, minimize the squared reconstruction error. Now train a linear network with a bottleneck of kk units on the same loss by gradient descent. It reaches the same subspace: the minimum spans the principal subspace, and there are no other local minima, only saddle points (Baldi and Hornik, 1989).

Replace both linear maps by networks, an encoder z=f(x)z = f(x) and a decoder x^=g(z)\hat x = g(z), trained by backpropagation (the topic Backpropagation). This is an autoencoder. It can follow a curved surface instead of a flat subspace. The topic Autoencoders of Generative Models builds them for images. Its probabilistic version, with the encoder as an approximate posterior, is the variational autoencoder (the topic Latent variables and the ELBO): probabilistic PCA made nonlinear.

PCA probabilistic PCA kernel PCA t-SNE, UMAP autoencoder
map linear linear, with a density linear in feature space positions optimized encoder network
keeps variance variance, likelihood variance in feature space neighbourhoods what reconstruction needs
new objects project project kernels with training set UMAP only encode
use compression, features the same, density nonlinear features looking representations

Probabilistic PCA and the Gaussian mixture are densities. They say not only where the data are but how probable each object is. An object the model finds very improbable, or one far from the subspace where the data live, with a large reconstruction error, does not fit. The next topic, Anomaly detection, turns this into methods: density scores, distances to neighbours, random trees that isolate odd objects quickly, the one-class SVM, and how to evaluate a detector when anomalies are rare.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.