Unit 8, lesson 60

Dimensionality Reduction and Visualization

How dimensionality reduction serves compression, prediction or visualization, how to fit a PCA pipeline inside training folds, why high explained variance can hide information loss, and what t-SNE, perplexity and UMAP preserve.

  • Video 60
  • Principal Components and Dimensionality Reduction

A feature table with hundreds of correlated measurements per row is slow to store, slow to model and impossible to plot directly. Replacing each row by a few coordinates can help, but help with what? A coordinate system that is good for compression can be poor for prediction, and a picture that looks clean can misstate the data it shows. This lesson separates the three purposes, fits a PCA pipeline honestly inside the training data, builds a case in which a projection keeps 99 percent of the variance and none of the label information, and introduces t-SNE and UMAP as tools for looking at local neighborhoods rather than for measuring distances or group sizes.

Key terms

Dimensionality reduction

Definition Dimensionality reduction replaces each feature vector x∈Rp\mathbf{x} \in \mathbb{R}^p by a vector z∈Rd\mathbf{z} \in \mathbb{R}^d with d<pd < p. A linear method such as PCA fits a map, z=Vd⊤(x−xˉ)\mathbf{z} = V_d^{\top}(\mathbf{x} - \bar{\mathbf{x}}) with training mean xˉ\bar{\mathbf{x}} and loadings VdV_d, that applies to any new observation. A nonlinear embedding such as t-SNE computes coordinates for the observations it is fitted on, and a method may or may not provide a map for new ones. Keeping a subset of the original features is the special case called feature selection. When the reduced coordinates feed a model that will be evaluated, the reduction is fitted on training data only. What counts as success depends on the purpose. Compression is judged by reconstruction error at a given storage cost, prediction by the held-out performance of the model that uses the coordinates, and visualization by how faithfully the plot shows the relationships it is meant to show, usually local neighborhoods.

In plain words Fewer coordinates always cost something. The question is whether what was lost mattered for the job at hand. A reduction that serves one purpose well can serve another badly, so name the purpose before choosing the method or the number of dimensions.

Example A constructed table has 10,000 rows of 200 correlated sensor measurements, 2,000,000 numbers in all. Keeping 10 principal components stores 10,000×10=100,00010{,}000 \times 10 = 100{,}000 scores, the 200 training means and the 10×200=2,00010 \times 200 = 2{,}000 loadings, a total of 102,200 numbers or about 5.1 percent of the original. The saving is worth having for compression only if the reconstruction error is acceptable, and for prediction only if a model on the 10 scores does as well on held-out rows as a model on all 200 features. Neither follows from the storage count.

PCA pipeline

Definition A PCA pipeline is an ordered sequence of fitted steps, for example imputation of missing values, scaling, PCA with kk components and a predictor. Fitting the pipeline on training rows estimates every step there, the imputation values, the means and standard deviations, the PCA mean and loadings, and then the predictor’s parameters from the training scores. Predicting for a new row applies the same fitted steps in the same order, without refitting any of them. In cross-validation the whole pipeline is refitted on the training part of each fold. The number of components kk is a hyperparameter chosen by the downstream validation score, inside an inner loop when the same data also estimate performance. Fitting the scaler or the PCA on all rows, held-out rows included, lets the held-out features shape the coordinate system, so the evaluation no longer describes a pipeline applied to new data and can be biased, even though PCA never sees the labels.

In plain words The pipeline is the model. Everything learned from data, including means, scales and principal axes, belongs on the training side of every split. A rule such as keeping 95 percent of the variance is a compression heuristic and says nothing about predictive accuracy, so the result should be compared with the unreduced features and with simple baselines under the same splits.

Example Four constructed training rows (−10,−1)(-10, -1), (−10,1)(-10, 1), (10,−1)(10, -1) and (10,1)(10, 1) have labels 00, 11, 00, 11, so the sign of the second feature decides the label and the first feature is unrelated to it. Separate evaluation rows (−5,−1)(-5, -1), (−5,1)(-5, 1), (5,−1)(5, -1) and (5,1)(5, 1) follow the same rule. Three pipelines end in the same logistic regression, fitted by minimizing the average log loss plus 0.12∥w∥22\tfrac{0.1}{2}\lVert \mathbf{w} \rVert_2^2 with the intercept unpenalized, and predict class 1 when the probability is at least 0.50.5. On the raw features and on features standardized with the training means (0,0)(0, 0) and standard deviations (10,1)(10, 1), the fitted weight is 00 on the first feature and about 1.631.63 on the second, and all four evaluation rows are classified correctly. The third pipeline keeps one principal component of the centered raw features, the first feature, so the evaluation rows receive the scores −5-5, −5-5, 55, 55, up to a common sign. Its fitted weight and intercept are both 00, every probability is 0.50.5, everything is predicted as class 1, and the accuracy is 0.50.5. Standardizing first does not rescue this pipeline. The standardized training features have equal variances and zero covariance, so the first principal axis is not determined, and a program may keep either feature or any rotation of them. These constructed results show a mechanism, not the performance of PCA on real data.

Information loss

Definition A reduction z=f(x)\mathbf{z} = f(\mathbf{x}) loses information about a quantity when that quantity cannot be recovered from z\mathbf{z}. For PCA with kk components, the discarded part of a centered observation xc\mathbf{x}_c is xc−VkVk⊤xc\mathbf{x}_c - V_k V_k^{\top}\mathbf{x}_c, whose squared length is its reconstruction error. For a target, the loss appears as collisions. If f(x)=f(x′)f(\mathbf{x}) = f(\mathbf{x}'), every predictor that sees only z\mathbf{z} gives the two observations the same prediction, so when their targets differ at least one of them is predicted wrongly. PCA ranks directions by variance and never uses the target, so a direction with little variance that determines the target can be discarded while the explained variance ratio stays close to 11.

In plain words Explained variance measures how much spread was kept, not how much of what matters was kept. A direction can be small in squared length and still carry the whole answer.

Example The training rows of the previous card have sample variances 400/3400/3 and 4/34/3 and zero covariance, so the first component explains

400404=100101≈0.9901\frac{400}{404} = \frac{100}{101} \approx 0.9901

of the variance. The rank-one reconstruction misses each row by (0,±1)(0, \pm 1), a squared error of 11 per row and 1/1011/101 of the total. Yet the projection sends (−10,−1)(-10, -1) and (−10,1)(-10, 1) to the same score with labels 00 and 11, and likewise the two rows at 1010. Any classifier that uses only this score gets at most 2 of the 4 rows right, 50 percent on this balanced table. The discarded second coordinate was the label.

Local neighborhood structure

Definition Fix a representation of nn observations, a distance and an integer kk with 1≤k≤n−11 \le k \le n - 1. The kk-neighborhood Nk(i)N_k(i) of observation ii is the set of the kk other observations closest to it, with ties broken by a fixed rule. The local neighborhood structure of the data is the collection of these sets, or equivalently the kk-nearest-neighbor graph that joins each observation to its neighbors. A low-dimensional map preserves it to the degree that the neighborhoods Nk′(i)N_k'(i) computed in the map agree with those of the original representation, which can be measured by the average overlap

1nk∑i=1n∣Nk(i)∩Nk′(i)∣,\frac{1}{nk} \sum_{i=1}^{n} \lvert N_k(i) \cap N_k'(i) \rvert ,

a number between 00 and 11. The structure depends on the features, their scaling, the distance and kk.

In plain words Neighborhood structure asks who sits next to whom, not how far apart distant points are. A map can keep every observation’s nearest neighbors and still distort the distances between groups, the sizes of groups, and anything the neighbors do not share, such as a target that differs between neighbors.

Example In the training rows of the pipeline card, the nearest neighbor of (−10,−1)(-10, -1) is (−10,1)(-10, 1) at distance 22, while the other rows are at distances 2020 and about 20.1020.10, and the same pairing holds for every row. In the one-component PCA projection the paired rows coincide, at distance 00, and the other rows are 2020 away, so every nearest neighbor is kept and the overlap for k=1k = 1 is 11. Each of these neighbor pairs has opposite labels. A map that preserves neighborhoods perfectly has lost the label completely.

t-SNE

Definition The t-distributed stochastic neighbor embedding, or t-SNE, places observations x1,…,xn\mathbf{x}_1, \dots, \mathbf{x}_n as points y1,…,yn\mathbf{y}_1, \dots, \mathbf{y}_n in a low-dimensional space, usually the plane. For each ii and each j≠ij \ne i it sets

gij=exp⁡(−∥xi−xj∥222σi2),pj∣i=gij∑l≠igil,\begin{aligned} g_{ij} &= \exp\Bigl(-\frac{\lVert \mathbf{x}_i - \mathbf{x}_j \rVert_2^2}{2\sigma_i^2}\Bigr), \\[0.4em] p_{j \mid i} &= \frac{g_{ij}}{\sum_{l \ne i} g_{il}} , \end{aligned}

a conditional distribution over the other observations with its own bandwidth σi>0\sigma_i > 0. The perplexity of that distribution is

Perp⁡(Pi)=2H(Pi),H(Pi)=−∑j≠ipj∣ilog⁡2pj∣i,\begin{gathered} \operatorname{Perp}(P_i) = 2^{H(P_i)}, \\[0.4em] H(P_i) = -\sum_{j \ne i} p_{j \mid i} \log_2 p_{j \mid i} , \end{gathered}

and each σi\sigma_i is found by a numerical search so that this perplexity equals one value set by the user, also called the perplexity. A uniform distribution over mm observations has perplexity mm, so perplexity is an effective number of neighbors. It always lies between 11 and n−1n - 1, and it is n−1n - 1 for every bandwidth when all other observations are equally far from xi\mathbf{x}_i, so the setting has to be smaller than n−1n - 1. Typical values are between 5 and 50. The input affinities are symmetrized, and the map affinities use a Student t kernel with one degree of freedom,

pij=pj∣i+pi∣j2n,hij=(1+∥yi−yj∥22)−1,qij=hij∑r≠shrs.\begin{aligned} p_{ij} &= \frac{p_{j \mid i} + p_{i \mid j}}{2n} , \\[0.4em] h_{ij} &= \bigl(1 + \lVert \mathbf{y}_i - \mathbf{y}_j \rVert_2^2\bigr)^{-1}, \\[0.4em] q_{ij} &= \frac{h_{ij}}{\sum_{r \ne s} h_{rs}} . \end{aligned}

The points yi\mathbf{y}_i minimize the Kullback-Leibler divergence

KL⁡(P ∥ Q)=∑i≠jpijln⁡pijqij\operatorname{KL}(P \,\Vert\, Q) = \sum_{i \ne j} p_{ij} \ln \frac{p_{ij}}{q_{ij}}

by gradient descent from a random or PCA-based start. The objective is not convex, so different starts and settings can end in different layouts. Standard t-SNE produces coordinates only for the observations it was fitted on.

In plain words The method turns distances into neighbor probabilities and then arranges points so that strong neighbors stay close. Each pair is weighted by its input probability, so the objective cares a great deal when close neighbors are placed far apart and little about exactly how far apart unrelated points end up. The heavy tail of the map kernel lets moderately distant points move far apart, which opens gaps between groups. Distances between islands, the sizes of islands and the empty space between them are therefore not measurements of the original data, and they can change with the perplexity, the random start and the preprocessing.

Example Suppose there are four observations, and observation ii has the other three at distances 11, 22 and 33. For perplexity 22 the bandwidth is σi≈1.156\sigma_i \approx 1.156, and the conditional probabilities are about 0.7270.727, 0.2360.236 and 0.0360.036, whose entropy is 11 bit. If the distances were 1010, 2020 and 3030, the bandwidth would be about 11.5611.56 with the same probabilities, so a sparse region and a dense region can look equally tight in the map. In the map, three points on a line at 00, 11 and 33 have kernel values 0.50.5, 0.20.2 and 0.10.1 for the pairs at distances 11, 22 and 33. Over ordered pairs each value is counted twice, so the normalizing sum is 1.61.6 and the map affinities are 0.31250.3125, 0.1250.125 and 0.06250.0625. The t kernel at distance 33 is one fifth of its value at distance 11, while the Gaussian e−d2e^{-d^2} falls by a factor of e8≈2981e^8 \approx 2981 over the same range.

UMAP

Definition Uniform manifold approximation and projection, or UMAP, as defined in its original paper, first finds the kk nearest neighbors Nk(i)N_k(i) of each observation, where kk is the neighbor count set by the user. Let dijd_{ij} be the distance between observations ii and jj, and let ρi\rho_i be the distance from observation ii to its nearest neighbor at positive distance. The directed weights are

δij=max⁡(0, dij−ρi),wi→j=exp⁡(−δij/σi)\begin{aligned} \delta_{ij} &= \max(0,\, d_{ij} - \rho_i) , \\[0.4em] w_{i \to j} &= \exp(-\delta_{ij} / \sigma_i) \end{aligned}

for j∈Nk(i)j \in N_k(i), with wi→j=0w_{i \to j} = 0 for every other jj. The local scale σi>0\sigma_i > 0 is found by a numerical search so that the kk weights of observation ii add to log⁡2k\log_2 k, or come as close to it as the distances allow. The directed weights are combined by

wij=wi→j+wj→i−wi→j wj→i,\begin{aligned} w_{ij} &= w_{i \to j} + w_{j \to i} \\[0.4em] &\quad - w_{i \to j}\, w_{j \to i} , \end{aligned}

a number between 00 and 11 for each pair. In the map, similarity is vij=(1+a∥yi−yj∥22b)−1v_{ij} = (1 + a \lVert \mathbf{y}_i - \mathbf{y}_j \rVert_2^{2b})^{-1}, with constants a,b>0a, b > 0 fitted to the minimum distance setting, which controls how tightly points can pack. The points minimize ∑i<jc(wij,vij)\sum_{i < j} c(w_{ij}, v_{ij}), where

c(w,v)=wln⁡wv+(1−w)ln⁡1−w1−v,\begin{aligned} c(w, v) &= w \ln \frac{w}{v} \\[0.4em] &+ (1 - w) \ln \frac{1 - w}{1 - v} , \end{aligned}

with 0ln⁡00 \ln 0 read as 00, by stochastic gradient descent with sampled non-neighbor pairs, usually starting from a spectral layout of the graph. Some implementations can place new observations into a fitted map, which does not remove concerns about distribution shift or information loss.

In plain words UMAP also builds a neighbor graph and asks the map to keep it, with mathematical choices that differ from those of t-SNE. Each observation’s nearest neighbor gets weight 11, and the local scale σi\sigma_i adapts to how crowded its region is. The neighbor count sets how local the view is, small values emphasizing fine structure and large values broader structure. As with t-SNE, the islands, their sizes and the gaps between them depend on the settings and the random optimization, so they are not evidence of true classes or of population proportions by themselves. Checking whether the neighbors in the map make sense in the data, and whether the picture survives other settings and seeds, comes before any interpretation.

Example Take k=3k = 3 and an observation whose three nearest neighbors are at distances 11, 22 and 33. Then ρi=1\rho_i = 1, and the condition

1+e−1/σi+e−2/σi=log⁡23≈1.585\begin{aligned} 1 + e^{-1/\sigma_i} + e^{-2/\sigma_i} &= \log_2 3 \\[0.4em] &\approx 1.585 \end{aligned}

gives σi≈1.133\sigma_i \approx 1.133 and the weights 11, 0.4140.414 and 0.1710.171. Distances 1010, 2020 and 3030 give σi≈11.33\sigma_i \approx 11.33 and the same weights. If the second neighbor in turn gives observation ii the weight 0.50.5, the combined weight of the pair is 0.414+0.5−0.414⋅0.5≈0.7070.414 + 0.5 - 0.414 \cdot 0.5 \approx 0.707.

Check yourself

  1. A data set has diagonal feature covariance with variances 2525 and 11. The target is whether the second feature is positive, and both target classes occur at every value of the first feature. A one-component PCA keeps the first direction. What fraction of the variance does it explain, and does that fraction guarantee a useful classifier?
Show the answer

The covariance is diagonal, so the principal axes are the feature axes and the first one belongs to the variance 2525. It explains

2525+1=2526≈0.9615\frac{25}{25 + 1} = \frac{25}{26} \approx 0.9615

of the variance. That gives no guarantee. The retained score is the first feature, and the discarded second coordinate is the one that defines the target. Since both classes occur at every value of the first feature, observations of different classes share a score, and any rule based on the score alone misclassifies some of them. If the second feature is positive half of the time independently of the first, no such rule beats 50 percent accuracy, while the two original features determine the class exactly. The reduced pipeline should be compared with an unreduced or target-aware alternative under the same split.

  1. In t-SNE, suppose the conditional probabilities of one observation are 0.50.5, 0.250.25, 0.1250.125 and 0.1250.125 on four other observations and, as a simplification, 00 on all the rest. What is the perplexity of this distribution? With 30 observations in all, can the perplexity setting be 4040?
Show the answer

The entropy in bits is

H=0.5⋅1+0.25⋅2+2⋅0.125⋅3=1.75,\begin{aligned} H &= 0.5 \cdot 1 + 0.25 \cdot 2 + 2 \cdot 0.125 \cdot 3 \\[0.4em] &= 1.75 , \end{aligned}

since −log⁡20.5=1-\log_2 0.5 = 1, −log⁡20.25=2-\log_2 0.25 = 2 and −log⁡20.125=3-\log_2 0.125 = 3. The perplexity is 21.75≈3.3642^{1.75} \approx 3.364. Four observations have positive probability, but the effective number of neighbors is smaller because the probability is uneven.

The setting 4040 is impossible. Each conditional distribution lives on the 29 other observations, and its perplexity is at most 29, reached only by the uniform distribution. No bandwidth can reach 4040, so the setting has to be lowered, in practice well below 2929.

  1. A colleague standardizes all 1,000 rows of a table, fits PCA with 20 components to all of them, and then runs five-fold cross-validation of a logistic regression on the 20 scores. Since PCA does not use the labels, the colleague argues that nothing can leak. What is wrong, and how should the evaluation be set up?
Show the answer

The means, standard deviations and loadings were estimated from all 1,000 rows, so in every fold the held-out rows helped choose the coordinate system in which the model was trained. Cross-validation is meant to imitate data that were not available at fitting time, and here they were partly available. The resulting estimate describes a different procedure from the one that will be used on new data, and it can be biased even though no label was used.

The fix is to make the scaler, the PCA and the logistic regression one pipeline that is refitted on the training part of each fold, with the held-out part passed through that fold’s fitted scaler and PCA. If the number of components is also chosen by cross-validation, the choice belongs in an inner loop, with an outer loop or a separate test set for the final estimate. A logistic regression on all standardized features under the same folds is the natural baseline.

How this lesson connects