Take a collection of 768-feature embeddings. You might need a 64-feature representation that can process the next request, or a two-dimensional view that helps you investigate why certain examples keep getting confused. PCA, t-SNE, and UMAP each remove dimensions, but they give you different evidence about the original data. Choose what you want to preserve before treating a plot or a variance percentage as a result.
By the end you can fit and apply PCA by hand, connect its reconstruction to SVD, explain the quantities t-SNE and UMAP preserve, and check neighborhoods against the original representation. You need the covariance example from Matrix Transformations and Eigenvalues and the reduced decomposition from SVD and Low-Rank Structure.
PCA fits a coordinate system to centered training data#
Let X have shape [N,D], with N observations as rows and D features as columns. Assume N>1. Compute the training mean μ with one entry per feature, and let Xc=X-μ be the centered matrix. Its sample covariance is C=XcᵀXc/(N-1). The covariance's unit eigenvectors are feature directions, and their eigenvalues give the variance of the data projected along each one.
If the reduced SVD is Xc=UΣ Vᵀ, the columns of V are those feature directions for the returned modes. Its sample variances are σⱼ²/(N-1), where σⱼ is singular value j. This follows by multiplying XcᵀXc and using UᵀU=I. A wide matrix may have extra orthogonal feature directions with zero sample variance, which do not contribute to reconstruction.
Let Vₖ contain the leading k directions. For any set of feature-aligned rows Y, compute scores Z and reconstruct rows Ŷ by
The scores have k features, while the reconstruction has D. The shift and basis stay fixed after fitting. For training observations, XcVₖ=UₖΣₖ. Those are the scores, while the columns of Vₖ are the directions. scikit-learn stores the latter as rows in components_.
Calculate a one-component fit by hand
Use four observations (6,2), (4,2), (5,4), and (5,0) with equal sample weight. The mean is (5,2). Centering gives (1,0), (-1,0), (0,2), and (0,-2). The cross-products are zero and the squared column sums are 2 and 8, so C has diagonal (2/3,8/3) and off-diagonal zeros. The larger variance belongs to v₁=(0,1)ᵀ. Its sign could be reversed without changing the projection.
The training scores along v₁ are 0,0,2,-2. The first row's reconstruction is (5,2) because its score is zero. The second row also reconstructs to (5,2), and the final two rows reconstruct exactly. The squared entrywise reconstruction error is 1+1=2. The retained variance share is (8/3)/(10/3)=80%. If a new row is (7,3), subtract the same training mean to get (2,1), project to score 1, and reconstruct (5,3). Recomputing a mean from that new row would produce a zero score regardless of its value.
Diagram key and text version
- Entry
- Process
- Outcome
- New row (7, 3) → Centered (2, 1)
- Centered (2, 1) → Score 1
- Score 1 → Reconstruction (5, 3)
PCA's top subspace minimizes the squared reconstruction error among projections of the same dimension. By the SVD residual identity, the training sum of squared errors equals the sum of squared discarded singular values. Dividing both retained and total squared singular values by N-1 leaves their ratio unchanged. This explains why maximizing explained variance and minimizing squared reconstruction error pick the same subspace. For a constant training matrix the total variance is zero. A percentage of it has no meaning, even though reconstruction can be exact.
Fit once and validate the compressed features
import numpy as np
train = np.array([[6., 2.], [4., 2.], [5., 4.], [5., 0.]])
mean = train.mean(axis=0)
_, values, directions_t = np.linalg.svd(train - mean, full_matrices=False)
basis = directions_t[:1].T
held_out = np.array([[7., 3.]])
scores = (held_out - mean) @ basis
restored = scores @ basis.T + mean
assert np.allclose(restored, [[5., 3.]])
assert np.isclose(values[0] ** 2 / (values @ values), 0.8)
For a library pipeline, fit PCA(n_components=k) on training data, then call transform on validation and serving rows. PCA centers the input, and each feature retains its original units unless you add a scaling stage. Fit the scaler on training data too. Standardizing can be defensible when features carry unrelated units. It also changes the optimization problem and can amplify low-variance noise. Compare both options using the metric that matters downstream.
If you need a reusable transform, save the feature names and order, imputation and scaling policy, mean, basis, and model version. Keep the downstream model paired with the same basis. A sign flip leaves reconstruction unchanged but changes the sign of the score seen by a fixed downstream model. With a small gap between leading eigenvalues, the fitted directions can rotate noticeably after refitting. Validate subspace or task behavior instead of comparing raw component coordinates across runs.
t-SNE fits a layout from similarities#
t-SNE begins with a distance between original rows. For each row it turns distances to other rows into conditional neighbor probabilities using a Gaussian whose scale is adapted locally. Perplexity controls the effective number of neighbors represented by this probability distribution. It can be viewed as an entropy-based neighborhood size, so it need not equal the number of points inside any fixed-radius ball. The conditional probabilities are combined into a symmetric joint distribution pᵢⱼ over pairs of distinct points i and j.
The layout assigns a position yᵢ to each point. For the two-dimensional formulation, pair (i,j) gets an unnormalized weight wᵢⱼ=1/(1+‖yᵢ-yⱼ‖₂²). Normalize by the sum over all ordered pairs of distinct points to get qᵢⱼ. For example, points one unit apart get weight 1/2 and points three units apart get 1/10. The corresponding probabilities have the same five-to-one ratio because they share a denominator. The heavy tail gives moderately separated points more room in the layout.
The objective is ∑[i ≠ j] pᵢⱼlog(pᵢⱼ/qᵢⱼ). This asymmetric discrepancy charges a large penalty when a pair with substantial original probability gets very little layout probability. Across many pairs it produces pressure to preserve neighborhoods. A cluster's apparent area and the blank distance between groups depend on the fit and offer little direct evidence about original variance or distance. Compare multiple perplexities and seeds before interpreting groups, and verify candidate neighbors in the input space. The default scikit-learn workflow fits coordinates for its input set with fit_transform and provides no general transform for new rows.
UMAP builds a weighted neighbor graph#
UMAP finds nearby rows according to your chosen metric and builds a graph with one node per observation. A directed neighbor's membership is stronger when its distance is small relative to the source row's local scale. The implementation estimates a local distance offset and scale, then combines directed memberships into a graph. In the default fuzzy union, memberships a and b in opposite directions combine to a+b-ab. A pair with strengths 0.8 and 0.25 therefore gets 0.8+0.25-0.2=0.85. Membership is a weight in [0,1], with each pair carrying its own value. It differs from t-SNE's probability distribution over all pairs.
UMAP then arranges points so strong edges tend to remain close and points without a matching edge exert repulsive pressure. The paper describes a fuzzy-set cross-entropy objective and the implementation uses edge sampling and negative samples for optimization. Here negative samples are sampled node pairs used to approximate the repulsion term. A small n_neighbors emphasizes fine neighborhoods. A larger value can connect broader structure while smoothing small groups. A smaller min_dist allows tighter packing in the layout. Treat the resulting visual density as a consequence of the method and its parameters.
The fitted umap-learn estimator can transform new rows by locating them relative to the training data and placing them in the existing layout. That is useful when comparing new cohorts to a frozen reference. Check behavior when new rows are far outside training support. The transform still has to assign coordinates, so an attractive plot is weak evidence of a good match for out-of-distribution data. Make the same metric choice at fit and evaluation. For example, use cosine for a direction-based embedding workflow where that is how relevance was defined.
Compare methods on the quantity you want to preserve#
| Question | Start with | Verification |
|---|---|---|
| Can these features be compressed for serving? | PCA | Held-out reconstruction, task quality, and transform latency |
| Which observations share local neighborhoods? | PCA as a baseline, then t-SNE or UMAP | Neighbor overlap under the original-space metric at several neighborhood sizes |
| Can new cohorts be compared in a fixed reference layout? | Fitted PCA or UMAP | Transform held-out cohorts and check neighbor membership and drift |
| Are the colored groups real classes? | Inspect original samples and labels | Cross-validated task metrics or independent domain evidence |
For a quantitative check, choose a small positive integer k below the number of samples. For every row, take the intersection of its k nearest neighbors in the original data and its k nearest neighbors in the map, excluding the row itself from both. Divide the intersection size by k and average across rows. For three original neighbors (A,B,C) and mapped neighbors (A,C,D) the overlap is 2/3. Include a deterministic tie policy when many distances coincide. A high score at k=5 can coexist with broken larger neighborhoods. Compare across several k values and across data slices. Duplicate points and degenerate layouts make overlaps harder to interpret.
The downloadable lab checks PCA, the t-SNE layout weights, and UMAP edge union with NumPy. With scikit-learn and umap-learn installed, run python3 07-pca-tsne-umap.py --compare to fit the three methods to the same curved point cloud and print neighbor overlap at two scales. To plot the layouts yourself, add --csv layouts.csv. The file contains method, point ID, two coordinates, and a continuous parameter along the curve for coloring. The comparison uses Euclidean distance throughout. The metrics are diagnostics for this fixture and do not imply a universal ranking.
When debugging real representations, hold the row sample fixed and color it by a known label, recency, source, or model version. Trace suspicious neighbors back to their source examples. Check feature scale and missing values first, then compare seeds and neighborhood sizes. A fixed random seed makes an experiment easier to repeat in the same environment. Record the data, preprocessing, versions, and configuration as well. A change in the data sample shifts the graphs or probabilities and can move every point in a refitted layout.
A monitoring dashboard can use this workflow to investigate a model rollout. Sample the same document IDs before and after the rollout, preserve their version labels, and compare loss or retrieval quality in the original feature spaces. If embeddings share a compatible feature basis, use one fitted reference transform and compare changes in neighbors for the same IDs. If the models use incompatible bases, compare neighbor identities and task outcomes separately in each space. Overlapping clusters in two independently fitted maps do not establish continuity, because the fits choose their coordinates independently.
Try it yourself
Explain a lower-dimensional model failure
A two-feature dataset has one column with variance 100 and another with variance 1. Their cross-covariance is zero. Keeping one principal component lets you retain about 99% of the variance, but classification accuracy drops. Explain how this can happen and how to test it.
Reveal solution
The one-component projection retains the high-variance column. The lower-variance feature could contain most of the label information. Compare the full and compressed pipelines on the same held-out split, inspect the discarded feature's relationship to the target, and evaluate performance by label or cohort. Fit each pipeline only on the training split.
Try it yourself
Diagnose a neighborhood plot
A t-SNE plot has two tight islands. You want to claim they were far apart in the original representation. What would you measure?
Reveal solution
Compare distributions of within-group and between-group distances in the original representation under the task's metric. Measure neighbor overlap at multiple scales, examine boundary points by ID, and check whether the islands persist across nearby perplexities and seeds. A visual gap is a hypothesis to investigate.
Memory chart#
- PCA learns linear directions from centered data. Variance by direction is squared singular value divided by N-1.
- t-SNE fits map coordinates to a distribution of original-space neighbor probabilities.
- UMAP fits a layout to a weighted neighbor graph and can place new observations relative to a fitted reference.
- Validation uses original-space neighbors, held-out reconstruction, or task quality according to your goal.
The next lesson, Derivatives and Gradients for Machine Learning, starts with what happens when you perturb an input or model parameter. Derivatives will let you reason about how a fit improves an objective, including objectives such as the pairwise layout losses introduced here.
References#
- Mathematics for Machine Learning, Chapter 10 explains both PCA objectives and how they agree.
- Visualizing Data using t-SNE defines the probability model and crowding problem.
- UMAP research paper describes graph construction and the layout objective.
- scikit-learn PCA and scikit-learn t-SNE document estimator conventions and parameters.
- UMAP parameter guide explains the neighborhood and layout controls.