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 by a vector with . A linear method such as PCA fits a map, with training mean and loadings , 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 scores, the 200 training means and the 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 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 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 , , and have labels , , , , so the sign of the second feature decides the label and the first feature is unrelated to it. Separate evaluation rows , , and follow the same rule. Three pipelines end in the same logistic regression, fitted by minimizing the average log loss plus with the intercept unpenalized, and predict class 1 when the probability is at least . On the raw features and on features standardized with the training means and standard deviations , the fitted weight is on the first feature and about 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 , , , , up to a common sign. Its fitted weight and intercept are both , every probability is , everything is predicted as class 1, and the accuracy is . 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 loses information about a quantity when that quantity cannot be recovered from . For PCA with components, the discarded part of a centered observation is , whose squared length is its reconstruction error. For a target, the loss appears as collisions. If , every predictor that sees only 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 .
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 and and zero covariance, so the first component explains
of the variance. The rank-one reconstruction misses each row by , a squared error of per row and of the total. Yet the projection sends and to the same score with labels and , and likewise the two rows at . 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 observations, a distance and an integer with . The -neighborhood of observation is the set of the 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 -nearest-neighbor graph that joins each observation to its neighbors. A low-dimensional map preserves it to the degree that the neighborhoods computed in the map agree with those of the original representation, which can be measured by the average overlap
a number between and . The structure depends on the features, their scaling, the distance and .
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 is at distance , while the other rows are at distances and about , and the same pairing holds for every row. In the one-component PCA projection the paired rows coincide, at distance , and the other rows are away, so every nearest neighbor is kept and the overlap for is . 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 as points in a low-dimensional space, usually the plane. For each and each it sets
a conditional distribution over the other observations with its own bandwidth . The perplexity of that distribution is
and each 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 observations has perplexity , so perplexity is an effective number of neighbors. It always lies between and , and it is for every bandwidth when all other observations are equally far from , so the setting has to be smaller than . 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,
The points minimize the Kullback-Leibler divergence
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 has the other three at distances , and . For perplexity the bandwidth is , and the conditional probabilities are about , and , whose entropy is bit. If the distances were , and , the bandwidth would be about 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 , and have kernel values , and for the pairs at distances , and . Over ordered pairs each value is counted twice, so the normalizing sum is and the map affinities are , and . The t kernel at distance is one fifth of its value at distance , while the Gaussian falls by a factor of over the same range.
UMAP
Definition Uniform manifold approximation and projection, or UMAP, as defined in its original paper, first finds the nearest neighbors of each observation, where is the neighbor count set by the user. Let be the distance between observations and , and let be the distance from observation to its nearest neighbor at positive distance. The directed weights are
for , with for every other . The local scale is found by a numerical search so that the weights of observation add to , or come as close to it as the distances allow. The directed weights are combined by
a number between and for each pair. In the map, similarity is , with constants fitted to the minimum distance setting, which controls how tightly points can pack. The points minimize , where
with read as , 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 , and the local scale 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 and an observation whose three nearest neighbors are at distances , and . Then , and the condition
gives and the weights , and . Distances , and give and the same weights. If the second neighbor in turn gives observation the weight , the combined weight of the pair is .
Check yourself
- A data set has diagonal feature covariance with variances and . 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 . It explains
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.
- In t-SNE, suppose the conditional probabilities of one observation are , , and on four other observations and, as a simplification, on all the rest. What is the perplexity of this distribution? With 30 observations in all, can the perplexity setting be ?
Show the answer
The entropy in bits is
since , and . The perplexity is . Four observations have positive probability, but the effective number of neighbors is smaller because the probability is uneven.
The setting 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 , so the setting has to be lowered, in practice well below .
- 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.