intermediate embedding-geometry 38 min read

PCA as Optimal Linear Dimensionality Reduction for Embeddings

The variance-optimal projection of an embedding cloud — what truncating 1536 dimensions to k keeps, and the honest reason it can still hurt retrieval

Overview & motivation

A vector retriever pays for every dimension twice. A single 15361536-dimensional float32 embedding is about six kilobytes, so an index of ten million of them is sixty gigabytes before any structure is added, and the cost of scanning or traversing that index — whether exact or approximate — scales with the dimension dd as well. The natural response is to shrink dd. The previous topic told us this should be possible without much loss: real embeddings do not fill Rd\mathbb{R}^d, they lie near a low-dimensional surface, so most of the ambient coordinates carry little of the variation that distinguishes one document from another. The question this topic answers is how to shrink dd optimally, and how much retrieval quality survives when we do.

Principal component analysis is the variance-optimal linear answer. Given a cloud of embeddings, PCA finds the orthogonal directions along which the cloud actually spreads — the first captures the most variance, the second the most of what remains, and so on — and projects onto the top kk of them. We will see that these directions are the top eigenvectors of the centered covariance matrix, that this single construction simultaneously maximizes retained variance, minimizes reconstruction error, and decorrelates the coordinates, and that the resulting truncation is the best possible rank-kk approximation in a precise sense (the Eckart–Young–Mirsky theorem). We will also prove the fact that makes PCA matter for retrieval rather than merely for compression: the fraction of squared distance a projection preserves is exactly the fraction of variance it keeps.

Before the algebra, drag the rank slider and watch the spectrum decide what survives:

1.00.502832128768
Cumulative explained variance (accent) and the per-dimension eigenvalue / scree (faint), against the kept dimension k (log axis). The steep rise is a concentrated spectrum: a few directions hold most of the variance.
EVR at k = 128
98.69%
effective rank n_eff
6.1
kept / ambient
128 / 1536

The first panel is the scree: a few directions hold most of the variance and the rest taper into a noise floor, so the cumulative explained-variance curve rises steeply then flattens. The second shows reconstruction error collapsing as kk grows — and a faint reference line for a random projection of the same width, which PCA always beats. The third projects three topical clusters onto the top two components, already enough to separate them. The fourth is the one that earns the word “retrieval”: nearest-neighbor recall retained after projection, PCA against random, as a function of how many dimensions we keep.

What we cover

  1. PCA’s three equivalent formulations, and why they all land on the covariance eigenvectors.
  2. The first principal direction as the maximizer of the Rayleigh quotient.
  3. Reconstruction error, and the identity that makes variance and error two views of one optimum.
  4. Eckart–Young–Mirsky, the SVD–PCA equivalence, explained variance, and effective rank.
  5. What survives projection: distortion equals explained variance, and PCA versus random.
  6. A finance case study, the honest caveat that variance-optimal is not retrieval-optimal, and the tested code.

PCA three equivalent ways

Fix a cloud of embeddings x1,,xnRdx_1, \dots, x_n \in \mathbb{R}^d with mean xˉ=1nixi\bar{x} = \tfrac{1}{n}\sum_i x_i, and let X~Rn×d\tilde{X} \in \mathbb{R}^{n \times d} be the centered data matrix whose ii-th row is xixˉx_i - \bar{x}. The object PCA studies is the centered covariance

Σ=1n1X~X~Rd×d,\Sigma = \frac{1}{n-1}\,\tilde{X}^{\top}\tilde{X} \in \mathbb{R}^{d \times d},

a symmetric positive-semidefinite matrix whose entry (a,b)(a, b) is the empirical covariance of coordinates aa and bb. A rank-kk linear compression keeps kk orthonormal directions, the columns of a matrix WRd×kW \in \mathbb{R}^{d \times k} with WW=IkW^{\top}W = I_k; the associated projector is P=WWP = WW^{\top}, which sends a centered vector z=xxˉz = x - \bar{x} to its best approximation WWzWW^{\top}z inside the chosen subspace, with coordinates (the scores) WzRkW^{\top}z \in \mathbb{R}^k.

There are three natural ways to ask for the best such WW, and the content of PCA is that they have the same answer:

  • Maximize retained variance. Keep the subspace along which the projected scores WzW^{\top}z vary the most, i.e. maximize tr(WΣW)\operatorname{tr}(W^{\top}\Sigma W).
  • Minimize reconstruction error. Keep the subspace whose projection loses the least, i.e. minimize the expected squared residual EzWWz2\mathbb{E}\lVert z - WW^{\top}z\rVert^2.
  • Decorrelate. Keep directions along which the scores are uncorrelated, so the compressed coordinates carry independent information.

All three are solved by taking the columns of WW to be the top eigenvectors of Σ\Sigma. The next two sections prove the first two equivalences; the third is immediate once we have the eigenvectors, because in the eigenbasis Σ=QΛQ\Sigma = Q\Lambda Q^{\top} the scores along distinct eigenvectors have covariance WΣW=diag(λ1,,λk)W^{\top}\Sigma W = \operatorname{diag}(\lambda_1, \dots, \lambda_k), which is diagonal — exactly the decorrelation statement, and the same diagonalization of a covariance matrix developed in multivariate distributions.


The principal directions are the top covariance eigenvectors

Start with the very first direction. Which unit vector ww captures the most variance of the projected data? The variance of the scalar scores w,z\langle w, z\rangle is wΣww^{\top}\Sigma w, the Rayleigh quotient of Σ\Sigma at ww, so the question is to maximize it over the unit sphere.

Theorem 1 (The principal directions maximize the Rayleigh quotient).

Let Σ\Sigma be symmetric positive-semidefinite with eigenvalues λ1λ2λd0\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d \ge 0 and orthonormal eigenvectors v1,,vdv_1, \dots, v_d. Then

maxw=1wΣw=λ1,attained at w=v1,\max_{\lVert w\rVert = 1} w^{\top}\Sigma w = \lambda_1, \quad \text{attained at } w = v_1,

and, maximizing over unit vectors orthogonal to the first j1j-1 eigenvectors, the jj-th principal direction is vjv_j with value λj\lambda_j. The top-kk subspace maximizing the total projected variance tr(WΣW)\operatorname{tr}(W^{\top}\Sigma W) is therefore spanned by v1,,vkv_1, \dots, v_k.

Proof.

By the spectral theorem a symmetric matrix factors as Σ=QΛQ\Sigma = Q\Lambda Q^{\top}, where Q=[v1vd]Q = [v_1 \cdots v_d] is orthogonal and Λ=diag(λ1,,λd)\Lambda = \operatorname{diag}(\lambda_1, \dots, \lambda_d). Any unit vector ww can be written in this eigenbasis as w=Qcw = Qc, and because QQ is orthogonal c=w=1\lVert c\rVert = \lVert w\rVert = 1. Substituting,

wΣw=(Qc)QΛQ(Qc)=cΛc=i=1dλici2    λ1i=1dci2=λ1,w^{\top}\Sigma w = (Qc)^{\top} Q\Lambda Q^{\top} (Qc) = c^{\top}\Lambda c = \sum_{i=1}^d \lambda_i c_i^2 \;\le\; \lambda_1 \sum_{i=1}^d c_i^2 = \lambda_1,

since λ1\lambda_1 is the largest eigenvalue and ici2=1\sum_i c_i^2 = 1. Equality holds exactly when all the weight sits on the largest eigenvalue, c=e1c = e_1, that is w=v1w = v_1 (uniquely so when λ1>λ2\lambda_1 > \lambda_2). For the jj-th direction, restricting to wv1,,vj1w \perp v_1, \dots, v_{j-1} forces c1==cj1=0c_1 = \dots = c_{j-1} = 0, so the same bound gives wΣw=ijλici2λjw^{\top}\Sigma w = \sum_{i \ge j}\lambda_i c_i^2 \le \lambda_j, attained at vjv_j. Summing the per-direction maxima, no orthonormal WW can exceed tr(WΣW)=j=1kwjΣwjj=1kλj\operatorname{tr}(W^{\top}\Sigma W) = \sum_{j=1}^k w_j^{\top}\Sigma w_j \le \sum_{j=1}^k \lambda_j, with equality at W=[v1vk]W = [v_1 \cdots v_k]. The general statement that this greedy, one-direction-at-a-time argument is globally optimal over all kk-subspaces is the Courant–Fischer min-max theorem, which we cite (Horn and Johnson, 2013); the companion code confirms no random unit vector exceeds the Rayleigh maximum λ1\lambda_1. \blacksquare

The geometric reading is the one to keep: Σ\Sigma stretches space most along v1v_1, next-most along v2v1v_2 \perp v_1, and so on, and PCA keeps the directions of greatest stretch. The eigenvalue λj\lambda_j is the variance the cloud has along vjv_j.


Reconstruction error, and why variance and error are one optimum

The variance formulation and the reconstruction formulation look different — one maximizes what we keep, the other minimizes what we lose — but they are the same optimization, joined by the Pythagorean theorem.

Theorem 2 (Variance maximization equals reconstruction-error minimization).

For any orthonormal WRd×kW \in \mathbb{R}^{d \times k} and centered z=xxˉz = x - \bar{x},

EzWWz2=tr(Σ)tr(WΣW).\mathbb{E}\lVert z - WW^{\top}z\rVert^2 = \operatorname{tr}(\Sigma) - \operatorname{tr}(W^{\top}\Sigma W).

Hence minimizing the expected squared reconstruction error over rank-kk orthonormal projectors is identical to maximizing the retained variance tr(WΣW)\operatorname{tr}(W^{\top}\Sigma W), and both are solved by W=[v1vk]W = [v_1 \cdots v_k], leaving the minimum residual

EzWWz2=i>kλi.\mathbb{E}\lVert z - WW^{\top}z\rVert^2 = \sum_{i > k}\lambda_i .
Proof.

The projector P=WWP = WW^{\top} onto the column space of WW is orthogonal (P2=P=PP^2 = P = P^{\top}, using WW=IkW^{\top}W = I_k), so for every zz the decomposition z=Pz+(zPz)z = Pz + (z - Pz) is orthogonal and the Pythagorean theorem gives z2=Pz2+zPz2\lVert z\rVert^2 = \lVert Pz\rVert^2 + \lVert z - Pz\rVert^2 pointwise. Taking expectations, EzPz2=Ez2EPz2\mathbb{E}\lVert z - Pz\rVert^2 = \mathbb{E}\lVert z\rVert^2 - \mathbb{E}\lVert Pz\rVert^2. Now Ez2=E[tr(zz)]=tr(Σ)\mathbb{E}\lVert z\rVert^2 = \mathbb{E}[\operatorname{tr}(zz^{\top})] = \operatorname{tr}(\Sigma) and, since Pz2=Wz2=zWWz\lVert Pz\rVert^2 = \lVert W^{\top}z\rVert^2 = z^{\top}WW^{\top}z,

EPz2=E[tr(WzzW)]=tr(WΣW),\mathbb{E}\lVert Pz\rVert^2 = \mathbb{E}\bigl[\operatorname{tr}(W^{\top}zz^{\top}W)\bigr] = \operatorname{tr}(W^{\top}\Sigma W),

which proves the identity. Because tr(Σ)=iλi\operatorname{tr}(\Sigma) = \sum_i \lambda_i is fixed, minimizing the left side is maximizing tr(WΣW)\operatorname{tr}(W^{\top}\Sigma W) — the variance problem of Theorem 1, whose optimum is ikλi\sum_{i \le k}\lambda_i at the top-kk eigenvectors. The residual is then iλiikλi=i>kλi\sum_i \lambda_i - \sum_{i \le k}\lambda_i = \sum_{i > k}\lambda_i. \blacksquare

So the best kk-dimensional summary of an embedding cloud, whether you measure “best” by variance kept or by reconstruction lost, is the same top-kk eigenspace, and the price of the compression is the sum of the eigenvalues you discard. The next theorem turns this from a statement about the covariance into the classical statement about the data matrix itself.


Eckart–Young–Mirsky and the SVD–PCA equivalence

PCA is usually computed not from the covariance but from the singular value decomposition of the centered data matrix, X~=USV\tilde{X} = U S V^{\top}, with singular values s1sr>0s_1 \ge \dots \ge s_r > 0 on the diagonal of SS. The two pictures are the same object.

Proposition 1 (SVD–PCA equivalence).

If X~=USV\tilde{X} = U S V^{\top} then Σ=1n1X~X~=V(1n1S2)V\Sigma = \tfrac{1}{n-1}\tilde{X}^{\top}\tilde{X} = V\bigl(\tfrac{1}{n-1}S^2\bigr)V^{\top}, so the principal directions are the right singular vectors (the columns of VV) and the eigenvalues are λi=si2/(n1)\lambda_i = s_i^2/(n-1).

This is the result developed in pca-low-rank and svd; the one-line derivation substitutes the SVD into X~X~=VSUUSV=VS2V\tilde{X}^{\top}\tilde{X} = VS U^{\top}USV^{\top} = VS^2V^{\top}, and the companion harness verifies eigenvalue-by-eigenvalue that the covariance eigendecomposition and the SVD agree. With this identification, “best rank-kk approximation of the data” and “top-kk PCA projection” become the same truncation, and its optimality is the Eckart–Young–Mirsky theorem.

Theorem 3 (Eckart–Young–Mirsky (best low-rank approximation)).

Let X~=USV\tilde{X} = USV^{\top} and let X~k=UkSkVk\tilde{X}_k = U_k S_k V_k^{\top} be the truncated SVD keeping the top kk singular triples. Then over all matrices BB of rank at most kk,

X~k=argminrank(B)kX~BF,X~X~kF2=i>ksi2=(n1)i>kλi.\tilde{X}_k = \arg\min_{\operatorname{rank}(B) \le k}\lVert \tilde{X} - B\rVert_F, \qquad \lVert \tilde{X} - \tilde{X}_k\rVert_F^2 = \sum_{i > k} s_i^2 = (n-1)\sum_{i > k}\lambda_i .
Proof.

The value first. The Frobenius norm is unitarily invariant — MF2=tr(MM)\lVert M\rVert_F^2 = \operatorname{tr}(M^{\top}M) equals the sum of squared singular values of MM — and X~X~k=U(SSk)V\tilde{X} - \tilde{X}_k = U(S - S_k)V^{\top} has singular values sk+1,,srs_{k+1}, \dots, s_r (the top kk canceled), so X~X~kF2=i>ksi2\lVert \tilde{X} - \tilde{X}_k\rVert_F^2 = \sum_{i > k}s_i^2, which is (n1)i>kλi(n-1)\sum_{i>k}\lambda_i by Proposition 1. For optimality, let BB have rank at most kk, so its null space has dimension at least dkd - k. The span of v1,,vk+1v_1, \dots, v_{k+1} has dimension k+1k+1, and two subspaces of Rd\mathbb{R}^d whose dimensions sum to more than dd must intersect, so there is a unit vector wnull(B)span{v1,,vk+1}w \in \operatorname{null}(B) \cap \operatorname{span}\{v_1, \dots, v_{k+1}\}. For that ww, Bw=0Bw = 0, so (X~B)w=X~w(\tilde{X} - B)w = \tilde{X}w, and writing w=ik+1civiw = \sum_{i \le k+1} c_i v_i gives X~w2=ik+1ci2si2sk+12\lVert \tilde{X}w\rVert^2 = \sum_{i \le k+1} c_i^2 s_i^2 \ge s_{k+1}^2 because each sisk+1s_i \ge s_{k+1} there. Hence X~B2sk+1=X~X~k2\lVert \tilde{X} - B\rVert_2 \ge s_{k+1} = \lVert \tilde{X} - \tilde{X}_k\rVert_2, the spectral-norm optimality; the Frobenius statement follows from the same interlacing applied to all the tail singular values, which we present as the truncated-SVD value above and cite in full to Eckart and Young (1936). The extension of this optimality to every unitarily-invariant norm is Mirsky’s theorem (Horn and Johnson, 2013), which we cite and the harness verifies numerically by checking that the truncated SVD beats every random rank-kk projection. \blacksquare

Two summaries of the spectrum do the practical work. The explained-variance ratio EVR(k)=ikλi/iλi\mathrm{EVR}(k) = \sum_{i \le k}\lambda_i / \sum_i \lambda_i is the fraction of total variance the top kk directions hold; by Theorem 2 it is also one minus the relative reconstruction error. The effective rank (participation ratio) neff=(iλi)2/iλi2n_{\text{eff}} = (\sum_i \lambda_i)^2 / \sum_i \lambda_i^2 is a soft count of how many directions carry appreciable variance — it is small when a few eigenvalues dominate and approaches the ambient dd when the spectrum is flat. For the synthetic 15361536-dimensional financial cloud in the companion code, the effective rank is about 66 and the top 128128 components already hold 98.7%98.7\% of the variance: the cloud is, for the purposes of distance, far lower-dimensional than its ambient size.


What survives projection: distortion equals explained variance

We have controlled reconstruction error. Retrieval, though, cares about distances — whether the nearest neighbor stays the nearest neighbor after we project. The bridge is a short identity that ties the geometry directly to the spectrum.

Theorem 4 (Projection distortion equals the explained-variance ratio).

Let Pk=VkVkP_k = V_k V_k^{\top} be the top-kk PCA projector and z=xxˉz = x - \bar{x} a centered embedding. The expected fraction of squared norm retained by the projection is

EPkz2Ez2=EVR(k),\frac{\mathbb{E}\lVert P_k z\rVert^2}{\mathbb{E}\lVert z\rVert^2} = \mathrm{EVR}(k),

and the fraction of the data’s mean pairwise squared distance that survives the projection is the same EVR(k)\mathrm{EVR}(k).

Proof.

Since PkP_k projects onto the top-kk eigenvectors, EPkz2=tr(PkΣ)=ikλi\mathbb{E}\lVert P_k z\rVert^2 = \operatorname{tr}(P_k \Sigma) = \sum_{i \le k}\lambda_i and Ez2=tr(Σ)=iλi\mathbb{E}\lVert z\rVert^2 = \operatorname{tr}(\Sigma) = \sum_i \lambda_i, whose ratio is EVR(k)\mathrm{EVR}(k) by definition. For pairwise distances, expand over the centered cloud: i,jzizj2=i,j(zi2+zj22zi,zj)=2nizi22izi2\sum_{i,j}\lVert z_i - z_j\rVert^2 = \sum_{i,j}\bigl(\lVert z_i\rVert^2 + \lVert z_j\rVert^2 - 2\langle z_i, z_j\rangle\bigr) = 2n\sum_i \lVert z_i\rVert^2 - 2\bigl\lVert \sum_i z_i\bigr\rVert^2, and the last term vanishes because the data are centered, izi=0\sum_i z_i = 0. So the total pairwise squared distance is exactly 2n2n times the total squared norm, and the identical computation for the projected cloud PkziP_k z_i (which is also centered) replaces izi2\sum_i\lVert z_i\rVert^2 by iPkzi2\sum_i\lVert P_k z_i\rVert^2. The retained fraction is therefore the same norm ratio, EVR(k)\mathrm{EVR}(k). \blacksquare

This is the sentence that makes PCA a retrieval tool rather than a compression trick: keep 90%90\% of the variance and you keep 90%90\% of the squared-distance energy, so the metric the retriever scores on is preserved in exactly the proportion the scree plot reports. It also sharpens the contrast with the alternative. A random projection — the data-oblivious method of the Johnson–Lindenstrauss lemma, the next topic in this track — preserves all pairwise distances of any point set with high probability, but only by keeping enough dimensions, k=O(ε2logn)k = O(\varepsilon^{-2}\log n), regardless of where the data actually live. PCA is data-dependent: it spends its kk dimensions on the directions this particular cloud occupies, so for a cloud of low effective rank it preserves far more distance per dimension. The companion code makes the gap concrete — at 128128 retained dimensions, PCA keeps 94%94\% of the top-1010 nearest-neighbor recall where a random projection of the same width keeps only 26%26\%.


Finance case study

A candid note on the companion code, in the spirit of the rest of the series: the cloud is a synthetic low-rank-plus-noise construction, sampled deterministically so the notebook is CPU-only and reproducible to the decimal with no model download, and the recall numbers are measured on it. It is not the output of a trained encoder, and — as the caveats spell out next — a real encoder’s top components carry nuisance structure that this clean synthetic spectrum does not, which is exactly where variance-optimal and retrieval-optimal part ways.


The honest catch: variance-optimal is not retrieval-optimal

Everything above optimizes one objective — reconstruction error, equivalently retained variance — and proves PCA optimal for it. Retrieval has a different objective: preserve the ranking of similarity scores, so that the documents a query would have retrieved in full dimension are the ones it retrieves after projection. The two objectives usually agree, which is why PCA is a workhorse, but they can disagree, and the disagreement is not a footnote.

The reason is that the top principal components — the directions of greatest variance — are not always the directions of greatest relevance. In real embedding sets the largest-variance directions frequently encode nuisance structure: a dominant “common” direction shared by almost every embedding, or variation that tracks token frequency and document length rather than topic. Projecting onto the top components faithfully keeps that nuisance and can wash out the finer, lower-variance distinctions a retriever actually ranks on. The striking empirical counterpoint is that removing the top few components — the “All-but-the-Top” postprocessing of Mu and Viswanath (2018) — often improves similarity and retrieval, the opposite of what a pure variance objective would recommend. That is a measured heuristic, not a theorem, and we flag it as such; it is the cleanest evidence that variance-optimal and retrieval-optimal are genuinely different targets. These nuisance directions are themselves a property of learned representations, and they connect to the spherical geometry of the previous topic: PCA’s mean-centering is in tension with the uncentered, normalized vectors cosine retrieval actually compares.


Honest caveats


Implementation

The companion notebook (notebookPath) is self-contained, CPU-only, and runs in a few seconds on numpy, scipy, and scikit-learn. It samples the synthetic embedding cloud, computes PCA both by eigendecomposition of the covariance and by SVD of the centered data matrix, measures reconstruction error and the random-projection baseline, the explained-variance ratio and effective rank, the projection-distortion fractions, and the nearest-neighbor recall after projection, and prints the grid table that the SpectrumLaboratory mirrors to the decimal. Its verification harness makes each claim executable: the eigendecomposition and the SVD agree on eigenvalues to machine precision and on components up to sign (Proposition 1); no random unit vector beats the Rayleigh maximum λ1\lambda_1 (Theorem 1); the reconstruction identity tr(Σ)tr(WΣW)\operatorname{tr}(\Sigma) - \operatorname{tr}(W^{\top}\Sigma W) holds and the residual equals the tail sum (Theorem 2); the truncated-SVD Frobenius error equals i>ksi2\sum_{i>k}s_i^2 and beats every random rank-kk projection (Theorem 3); the retained squared-norm and squared-distance fractions both equal EVR(k)\mathrm{EVR}(k) exactly (Theorem 4); recall@10 is monotone in the kept dimension and PCA beats random everywhere; and the whole pipeline agrees with scikit-learn’s reference PCA. The three pillars — the proofs above, the laboratory, and the tested code — agree by construction.

Connections

  • latent semantic analysis is exactly the truncated SVD of the TF-IDF term-document matrix, so the optimal-low-rank theory proved here is the linear-algebra engine under that classical sparse-retrieval model, and the Eckart-Young guarantee is what makes LSA's reduced space the best rank-k summary of the term space vector-space-model-tfidf
  • PCA centers and projects in R^d while that topic normalizes embeddings onto the sphere, and the tension between PCA's mean subtraction and cosine's uncentered angles is precisely the centering-versus-cosine caveat this topic raises about applying linear dimensionality reduction before spherical retrieval hypersphere-vmf-geometry

References & Further Reading