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 . This topic summarizes the columns instead: it replaces the features by a few new ones.
Take the digits of scikit-learn: images of pixels, so each object is a vector . The images do not fill . 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: numbers per object instead of , 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, , and has rows . The covariance is , with eigenvalues and orthonormal eigenvectors ; in this topic is an eigenvalue, not a regularization strength. The letter is the number of components kept. has orthonormal columns, , and are the new coordinates of object .
Largest variance is smallest error
Keep numbers per object, , and rebuild the object from them as . Which rebuilds best? The map is an orthogonal projection, so the residual is perpendicular to . By Pythagoras,
Average over the objects:
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: . The error left is the sum of the discarded eigenvalues, . 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 the eigenvalues are and , and . The point gets the coordinate and the reconstruction . Its residual has squared length , and indeed .
In practice nobody forms . As the topic The singular value decomposition showed, the SVD of the centred data gives everything at once: the components are the right singular vectors , the eigenvalues are , and the coordinates are . The reconstruction is the truncated SVD , so by Eckart–Young no rank- linear summary of the data does better. For large data a randomized SVD computes only the 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 components is the explained variance ratio:
One minus it is the relative reconstruction error. On the digits the first two components explain and of the variance. Five components explain half, explain , and explain . With components the mean squared reconstruction error per image is , the sum of the discarded eigenvalues, out of a total variance of .
There is no single rule for . Four common ones:
- a share of variance, such as or : 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 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 , , and seven times : three directions of signal on top of noise of variance in every direction. The scree plot drops after the third value and then stays flat. But those three explain only of the variance, so a 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.894PCA 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:
The new coordinates are uncorrelated and have unit variance, . 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 is , so its condition number from the topic Gradient descent is .
The risk is the division by . 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 components, or with a small constant added to every under the root. In scikit-learn, PCA(k, whiten=True) whitens only the 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 instead of a component index. It is mapped linearly into the feature space and blurred by isotropic noise:
By the rule for affine maps of a Gaussian vector from the topic The multivariate Gaussian, : a Gaussian whose covariance is "rank plus noise". Here holds loadings and need not have orthonormal columns.
Its maximum likelihood solution is PCA again. The estimate of is the sample mean, and
for any rotation (Bishop, 2006, Section 12.2.1). The columns of span the principal subspace, and the noise variance is the average of the discarded eigenvalues. In the ten-feature example of the previous blocks, gives , the true noise. The columns of (with ) have lengths , and , the standard deviations of the three signals. On the digits with the noise variance is .
A density buys three things.
- A likelihood for choosing . Draw training and held-out objects from the ten-feature example. The mean held-out log-likelihood per object is at , at and at , and it stays below the peak for every larger : the maximum is at the true . 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 in the E-step. EM never forms the 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 in the topic EM and Bayesian PCA, and the prior then chooses 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 reached through a kernel , as the topic Kernels promised. The principal directions in feature space are combinations of the mapped objects, . The eigenvalue problem then moves to the Gram matrix , centred in feature space:
Here is the matrix with all entries , and is scaled so that , which gives the direction unit length. The coordinate of an object on a component is : kernels only, no .
With the feature space is . The squared radius , which tells the rings apart, is a linear function there. Take points on two noisy rings. A logistic regression on two ordinary principal components reaches a training accuracy of , chance. On three kernel components it reaches . 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 ( against and ): 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 entries and its eigenproblem costs about operations. A new object needs kernels with all 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 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.
- Turn distances in the data into neighbour probabilities. For each , over . Each bandwidth is set so that the distribution has a chosen perplexity , with the entropy in bits: roughly the number of neighbours that count, typically to . Symmetrize: .
- Define similar probabilities for points in the plane, with a heavy-tailed Student- kernel: , normalized over all pairs.
- Move the by gradient descent to minimize , the divergence from the topic Entropy, cross-entropy and KL of Generative Models.
The order of and 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 kernel lets moderately distant objects move far away instead of piling up in the middle. On the digits, of the nearest neighbours of each image in stay among its nearest neighbours in a t-SNE map (perplexity ). In the two-component PCA plane only do.
UMAP (McInnes, Healy and Melville, 2018) follows the same plan with other choices: a weighted graph of 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 , decode , minimize the squared reconstruction error. Now train a linear network with a bottleneck of 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 and a decoder , 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.
Answers are saved on the server and tied to this browser until you sign in.