Back to Streaming Sketching

Dimensionality Reduction

September 26, 2026 Wasil Zafar 23 min read

Preserve geometry while reducing dimension.

Table of Contents

  1. Preserving Geometry with Fewer Coordinates
  2. Distances, Projections and Distortion
  3. Why Random Embeddings Work
  4. Nearest Neighbors and Compressed Features
  5. Choose Dimensions from a Distortion Budget

Preserving Geometry with Fewer Coordinates

A map can omit most details of a city yet preserve what a traveller needs: which places are near, which are far, and roughly how distances compare. Dimensionality reduction asks for an analogous map of data. A point with a million coordinates is replaced by one with far fewer coordinates while selected geometric relationships remain approximately true.

Consider three points in two dimensions: $a=(1,0)$, $b=(0,1)$, and $c=(1,1)$. Their squared distances are $\lVert a-b\rVert_2^2=2$ and $\lVert a-c\rVert_2^2=\lVert b-c\rVert_2^2=1$. Mapping every point to its first coordinate sends $a$ and $c$ to the same value, destroying one distance. A random projection does not promise perfection, but with enough target dimensions it makes such large distortions unlikely for a fixed finite set.

The Johnson–Lindenstrauss idea is striking because the required target dimension depends logarithmically on the number of points, not directly on the original dimension. Gaussian and Rademacher matrices provide dense random projections; sparse JL and feature hashing reduce update cost; fast JL transforms mix coordinates before subsampling; subspace embeddings preserve every vector in a low-dimensional linear subspace rather than merely a fixed list of points.

The boundary matters. An embedding preserves the geometry named in its theorem—usually Euclidean norms or distances, with stated probability and distortion. It does not automatically preserve labels, fairness, rare semantic features, nearest-neighbor identity when margins are tiny, or arbitrary future points chosen after seeing the map.

From a detailed city map to a geometric embedding A familiar map preserves approximate relationships, leading to high-dimensional points, a random projection, and lower-dimensional points with similar pairwise distances. Useful map less detail, useful distances Points in Rⁿ many coordinates Random R k × nk ≪ n Points in Rᵏ distances approximately preserved Guarantee: multiplicative distortion, not semantic perfection.
ConceptIntuitive meaningExact exampleNon-example or boundaryAssumptionQuestion answered
DistortionRelative change in length or distanceSquared distance $10$ mapped into $[9,11]$ has $10\%$ distortionAdditive error one means different things at distances $1$ and $100$Original distance is nonzero for a ratioHow faithfully is geometry retained?
JL embeddingRandom map preserving all pairwise distances in a fixed finite set$N$ points mapped to $k=O(\varepsilon^{-2}\log(N/\delta))$ dimensionsOne map preserving every vector in $\mathbb R^n$ when $k\lt n$Set is fixed independently of the random mapCan finite Euclidean geometry be compressed?
Gaussian projectionDense matrix with scaled independent normal entries$R_{ij}\sim N(0,1/k)$Unscaled normals, whose expected norm grows with $k$Independent subgaussian rowsWhat simple map supports concentration?
Rademacher projectionDense random signs with scale $1/\sqrt{k}$$R_{ij}\in\{-1,+1\}/\sqrt{k}$Deterministic repeated sign rowsSufficient independence and scalingCan simpler randomness replace Gaussians?
Sparse JL / feature hashingEach input coordinate touches few output coordinatesOne signed bucket per feature in hashingCollision-free preservation for every inputSparsity and input-coherence conditions of the theoremHow can projection cost be reduced?
Subspace embeddingPreserve every vector in one $d$-dimensional subspaceNorms of all $Ax$ preserved for every $x$Preserving only the matrix columns separatelyOblivious map independent of the fixed subspaceCan regression and low-rank geometry be compressed?
Warm-up

Preserving Geometry with Fewer Coordinates

Use points $a=(1,0)$, $b=(0,1)$, and $c=(1,1)$.

  1. Compute squared pairwise distances: $d^2(a,b)=2$, $d^2(a,c)=1$, and $d^2(b,c)=1$.
  2. Project onto the first coordinate with $P(x_1,x_2)=x_1$. The images are $1,0,1$, so the $a,c$ distance collapses from $1$ to $0$.
  3. Project onto the unit direction $u=(1,1)/\sqrt2$. The images are $1/\sqrt2,1/\sqrt2,\sqrt2$. Now $a,b$ collapse instead.
  4. Neither one-dimensional map can preserve all three distances well. This is consistent with JL: it promises a sufficient target dimension depending on distortion and set size, not that $k=1$ always works.

Reflection: a projection may preserve most distances but collapse the particular pair that determines a nearest-neighbor decision. What additional margin condition would make approximate distances sufficient to preserve that decision?

Distances, Projections and Distortion

For a linear map $R:\mathbb R^n\to\mathbb R^k$, norm preservation for a vector $v$ means

$$ (1-\varepsilon)\lVert v\rVert_2^2\le\lVert Rv\rVert_2^2\le(1+\varepsilon)\lVert v\rVert_2^2. $$

Distance preservation for points $x_i,x_j$ follows by applying the norm statement to $v=x_i-x_j$. A fixed-vector guarantee quantifies over one vector chosen independently of $R$. A finite-set JL guarantee applies a tail bound to all pairwise differences and uses a union bound. A subspace embedding is stronger: with high probability, the inequality holds simultaneously for every vector in a fixed $d$-dimensional subspace.

For a Gaussian matrix with entries $N(0,1/k)$ and fixed $v$, rotational symmetry gives $\lVert Rv\rVert_2^2/\lVert v\rVert_2^2$ distributed like $\chi_k^2/k$. Its expectation is one, and concentration gives a failure probability exponentially small in $k\varepsilon^2$ for $0\lt\varepsilon\lt1$. Rademacher projections obtain comparable concentration using independent scaled signs.

For $N$ fixed points, there are fewer than $N^2/2$ pairwise differences. Making the per-difference failure probability roughly $\delta/N^2$ yields target dimension $k=O(\varepsilon^{-2}(\log N+\log(1/\delta)))$, with constant and lower-order dependence determined by the chosen tail inequality.

Sparse JL uses fewer nonzeros per column to accelerate multiplying sparse inputs, but extreme input concentration can increase collisions unless the construction and sparsity meet the relevant theorem. Feature hashing is an especially sparse signed map: each feature hashes to a bucket with a random sign. FJLT first randomizes signs and applies a fast orthogonal mixing transform, then samples or projects fewer coordinates, spreading a concentrated vector before reduction.

Dimensionality Reduction: Distances, Projections and Distortion
flowchart TD
    A[Choose fixed data object] --> B{What must be preserved?}
    B -->|One vector| C[Fixed-vector norm]
    B -->|N points| D[All pairwise differences]
    B -->|d-dimensional subspace| E[All vectors in the subspace]
    C --> F[Random projection expectation]
    F --> G[Concentration around norm one]
    D --> H[Apply fixed-vector tail to fewer than N squared pairs]
    H --> I[Union bound]
    E --> J[Net argument or matrix concentration]
    G --> K[Choose k from epsilon and delta]
    I --> L[Choose k from epsilon, delta, and log N]
    J --> M[Choose k from epsilon, delta, and d]
    classDef navy fill:#17365D,color:#fff,stroke:#17365D;
    classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
    classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
    classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
    class A,B navy;
    class C,D,E teal;
    class F,H,J purple;
    class G,I,K,L,M crimson;
From fixed-vector norm preservation to all pairwise distances A set of N points creates pairwise difference vectors. Random projection preserves each fixed difference with high probability; a union bound controls all pairs simultaneously. N fixed points data chosen before R Differences vᵢⱼ = xᵢ − xⱼ fewer than N²/2 distance = norm of difference Random R fixed-v tail ≈ exp(−c k ε²) scaled entries Union bound all pairs fail ≤ δ k grows with log N Quantifiers: one random R succeeds for every pair in the fixed set.
Definition or resultExact scopeRequired assumptionsWhat it does not implyCounterexample or consequence
Fixed-vector JL tailOne fixed $v$ has its squared norm preserved with high probability$v$ independent of the random map and correctly scaled randomnessSimultaneous preservation of uncountably many vectorsAfter seeing $R$, choose a nonzero vector in its null space
Finite-set JLAll pairwise distances among $N$ fixed points are preservedUnion bound over fixed differencesExact nearest-neighbor identity without a marginTwo candidates with almost equal distances may swap order
Gaussian projectionDense subgaussian map with isotropic rowsIndependent $N(0,1/k)$ entriesFast multiplication for huge sparse inputsDense matrix touches every input coordinate-output pair
Rademacher projectionSimilar norm concentration using scaled signsAdequate independence and $1/\sqrt{k}$ scalingDeterministic signs with the same guaranteeRepeated rows can annihilate a structured vector
Feature hashingVery sparse signed projectionRandom hash/signs and appropriate input/model conditionsWorst-case preservation for every vector at arbitrarily small $k$Two large features collide with opposite signs and cancel
FJLTFast mixing plus sampling/projectionFast orthogonal transform, random signs, suitable dimensionsUniversally faster for every sparse or hardware settingPadding and dense mixing may dominate small problems
Subspace embeddingSimultaneously preserves all vectors in a fixed $d$-dimensional subspaceMap independent of the subspace and target dimension sized for $d$Preserving all of $\mathbb R^n$ with $k\lt n$A vector outside the subspace may lie in the null space

JL preserves pairwise distance by preserving norms of difference vectors. The probability statement is over the random map for a fixed set chosen independently of it; choosing a bad vector after inspecting a dimension-reducing map defeats any claim about all of $\mathbb R^n$.

Why Random Embeddings Work

Take a fixed nonzero vector $v$ and a Gaussian projection $R\in\mathbb R^{k\times n}$ with entries $N(0,1/k)$. Each row dot product is normal with variance $\lVert v\rVert_2^2/k$. Therefore

$$ \frac{\lVert Rv\rVert_2^2}{\lVert v\rVert_2^2}=\frac1k\sum_{r=1}^k Z_r^2, $$

where the $Z_r$ are independent standard normals. The mean is one. A chi-square tail bound shows deviations beyond $\varepsilon$ occur with probability at most roughly $2e^{-c k\varepsilon^2}$ for $0\lt\varepsilon\lt1$ and an absolute constant $c$.

For $N$ points, apply this to every difference $x_i-x_j$. There are at most $N(N-1)/2$ pairs. The union bound does not require pairwise failure events to be independent; it simply adds their probabilities. Choosing $k$ large enough that each failure probability is at most about $2\delta/N^2$ makes the probability of any distorted pair at most $\delta$.

The logarithm appears when solving an exponential tail for $k$: $e^{-c k\varepsilon^2}$ must beat a polynomial number of pairs. Reducing distortion by half is expensive because $k$ scales quadratically with $1/\varepsilon$. Increasing the dataset size multiplicatively only adds to $\log N$.

This proof fails if the set is selected adaptively after $R$ is exposed. When $k\lt n$, $R$ has a nonzero null-space vector $v$ with $Rv=0$, causing total distortion. It also fails if rows are unscaled or strongly dependent, because isotropy or concentration can disappear. Sparse transforms need their own analysis; copying the dense proof without checking collision structure is not valid.

Concentration converts random coordinate energy into norm preservation Independent projected coordinates contribute squared energy. Their average concentrates near the original squared norm, and a union bound extends one-vector control to a fixed point set. Fixed vector v energy ‖v‖² k random rows independent squared contributions Average energy concentrates near 1 Tail bound bad event≤ 2e−ckε² then union bound Expectation gives the center; concentration gives reliability.
Dimensionality Reduction: Why Random Embeddings Work
flowchart TD
    A[Fix nonzero vector v independently of R] --> B[Scale random rows so expected projected energy equals original energy]
    B --> C[Express projected norm as average of independent squared variables]
    C --> D[Apply chi-square or subgaussian concentration]
    D --> E[Fixed-vector failure decays exponentially in k epsilon squared]
    E --> F[Replace v by every pairwise difference]
    F --> G[At most N squared over two bad events]
    G --> H[Union bound total failure by delta]
    H --> I[Solve for k proportional to epsilon inverse squared times log N over delta]
    A -. choose v after seeing R .-> X[Null-space counterexample]
    B -. wrong scale or dependence .-> Y[Expectation or concentration fails]
    classDef navy fill:#17365D,color:#fff,stroke:#17365D;
    classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
    classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
    classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
    class A,B navy;
    class C,D,E purple;
    class F,G,H,I teal;
    class X,Y crimson;
Worked Derivation

Why Random Embeddings Work

Suppose a particular JL tail bound guarantees that a fixed vector fails with probability at most $2e^{-k\varepsilon^2/8}$. You have $N=100$ fixed points, want $\varepsilon=0.25$, and require total failure at most $\delta=0.01$.

  1. There are $M=N(N-1)/2=4{,}950$ pairwise differences.
  2. Require $2M e^{-k\varepsilon^2/8}\le\delta$.
  3. Rearranging gives $k\ge(8/\varepsilon^2)\ln(2M/\delta)$.
  4. Here $8/0.0625=128$ and $\ln(990{,}000)\approx13.81$, so this conservative bound gives $k\ge1{,}768$.
  5. The result exceeds the original dimension in many small examples. A sufficient worst-case bound can be conservative; projection is useful only if the actual $n$, workload, constants, and empirical behavior justify it.

Assumption-breaking variation: generate a random $R$ with $k\lt n$, inspect it, and then choose nonzero $v\in\ker(R)$. The projected norm is zero. Identify exactly which “fixed independently of $R$” quantifier the construction violates.

Proof tool or viewpointWhat it establishesAssumptionsTightness or limitationFailure case
Isotropy / expectation$\mathbb E\lVert Rv\rVert_2^2=\lVert v\rVert_2^2$Correct scaling and second momentsMean preservation alone permits large varianceOne row receives nearly all projected energy
Chi-square concentrationExponential fixed-vector tail for Gaussian mapsIndependent Gaussian rowsSpecific to dense Gaussian structureCorrelated duplicate rows reduce effective sample size
Subgaussian concentrationComparable tails for signs and other light-tailed mapsIndependence or suitable limited independence and subgaussian controlConstants and randomness differ by constructionHeavy-tailed entries create frequent large distortions
Union boundSimultaneous finite-set guaranteeFixed finite event family; independence not requiredCan be conservativeTreating an uncountable sphere as finitely many points without a net
Epsilon-net argumentExtends finite control to a fixed subspace sphereCovering-number argument plus operator controlIntroduces dimension and constant overheadNet result applied without controlling points between the net
Preconditioning / mixingReduces coordinate concentration before sparse samplingRandom signs and an orthogonal fast transformExtra passes and hardware costsOmitting mixing on a basis vector before coordinate sampling
Empirical distortion auditMeasures workload-specific qualityRepresentative fixed evaluation pairsNo universal guarantee under drift or adaptivityTest set excludes rare high-coherence vectors

Nearest Neighbors and Compressed Features

For a small image collection, projection can compress embedding vectors before approximate nearest-neighbor search. If distances are preserved within $1\pm\varepsilon$, a neighbor with a clear margin over the runner-up usually remains preferred. With almost tied candidates, even a theorem-compliant distortion can reverse the order, so recall must be measured at the actual margin distribution.

In text or advertising systems, feature hashing maps millions of sparse categorical features into a smaller vector. Signed hashing reduces systematic collision bias in inner products, but collisions can erase rare high-value features. The feature dictionary, hash seed, normalization, and target dimension become model-versioned production artifacts.

For least squares and randomized linear algebra, a subspace embedding compresses the rows of a design matrix while preserving norms in its column space. Solving the smaller problem can approximate the original objective. This is a different quantifier from finite-point JL: every vector in the column space must be preserved.

Misleading cases include data selected after the map is published, distribution drift toward highly coherent vectors, and protected or rare groups whose decision margins are smaller. An embedding can satisfy a global geometric metric while harming a critical slice. Random projection preserves mathematical distance; it does not certify that the upstream embedding or metric represents the desired semantics.

Production dimensionality-reduction pipeline with validation boundaries High-dimensional features pass through normalization and a versioned random map before search or modeling. Exact reranking and monitoring guard against distortion, drift, and adaptive inputs. Raw featurestext / image / designdimension n Normalizeunits + centeringfixed semantics Project Rseed + dimension kversioned transform Search / solvecompressed candidatesfast objective Verifyexactrerank Semantic riskbad metric or scaling Geometry riskcollision or drift Decision risksmall margins, rare slices Projected geometry proposes; exact data and slice metrics validate.
Case Study

Nearest Neighbors and Compressed Features: Dimensionality Reduction

A learner stores four two-dimensional feature vectors: query $q=(1,1)$ and candidates $a=(1,2)$, $b=(3,1)$, $c=(-1,-1)$. Their squared distances from $q$ are $1$, $4$, and $8$.

Use the one-dimensional signed projection $R=(1,1)/\sqrt2$. Images are $Rq=\sqrt2$, $Ra=3/\sqrt2$, $Rb=4/\sqrt2$, and $Rc=-\sqrt2$. Projected squared distances are $1/2$, $2$, and $8$; every value is exactly half its original because these particular difference vectors have components aligned in a favorable way. If we rescale this one-row map by $\sqrt2$, these three query distances become exact.

Now add $d=(2,0)$. Its original squared distance from $q$ is $2$, but $Rd=Rq$, so the projected distance is zero. The same map is not uniformly reliable even for this tiny expanded set.

Model-selection conclusion: use the example to understand linear projection, not to justify $k=1$. For a real fixed collection, select $k$ from a distortion/failure budget and validate all relevant query-candidate pairs.

Success criteria: reproduce all distances, identify the collapsed difference $(1,-1)$ as orthogonal to $R$, and state a measurable acceptance rule such as $99\%$ recall@10 with p99 relative distance distortion below the chosen bound.

Production

Nearest Neighbors and Compressed Features: Dimensionality Reduction

A retrieval platform stores $N=50$ million normalized embeddings of dimension $n=4{,}096$. It targets recall@20 of at least $98\%$, p99 query latency below 80 ms, projected storage below 30% of the original, and no critical language slice below $96\%$ recall.

Design: compare dense Rademacher, sparse JL, and a fast transform at target dimensions $k\in\{256,384,512,768\}$. Version the normalization, seed, map family, and $k$. Search projected vectors to generate a larger candidate set, then rerank candidates with original-vector distance. Keep queries and corpus fixed independently of each evaluation seed.

Evidence: empirical distortion distributions on random pairs and hard-neighbor pairs; recall versus neighbor margin; slice metrics; storage, projection throughput, index-build cost, and latency; seed-to-seed variability; drift after embedding-model releases; collision/coherence stress tests; and adaptive-query red-team results.

Risks: a global average hides rare slices, feature normalization changes the geometry, sparse inputs can collide under feature hashing, and users may adapt queries after deployment. Exact reranking protects precision among retrieved candidates but cannot recover a true neighbor omitted during projected search.

Decision: choose the smallest $k$ whose confidence bounds meet every recall and slice target under the memory/latency budget. Trigger rollback or dual-index migration if margin-adjusted recall or distortion drifts beyond its control limit; do not infer safety from the asymptotic JL order alone.

Choose Dimensions from a Distortion Budget

Target dimension is a contract, not a magic constant. Identify the set or subspace, Euclidean geometry, acceptable multiplicative distortion, global failure probability, and downstream margin. Then choose a theorem appropriate to the transform, calculate a conservative $k$, and measure whether constants and workload structure permit a smaller operational value.

Practice

Practice: Choose Dimensions from a Distortion Budget

Assume a fixed-vector bound $2e^{-k\varepsilon^2/8}$ and a fixed set of $N=10{,}000$ points. Require all pairwise squared distances to have distortion at most $\varepsilon=0.2$ with total failure probability at most $\delta=10^{-3}$.

Tier 1 — Definitions. Define fixed-vector norm preservation, finite-set JL, feature hashing, FJLT, and subspace embedding. State the quantifiers for each. Checkpoint: distinguish a fixed point set from inputs chosen after the map.

Tier 2 — Dimension derivation. With at most $N^2/2$ pairs, solve $N^2e^{-k\varepsilon^2/8}\le\delta$. Obtain $k\ge(8/\varepsilon^2)\ln(N^2/\delta)$. Substitute the values: $8/0.04=200$ and $\ln(10^{11})\approx25.33$, yielding the conservative sufficient bound $k\ge5{,}066$. Record that exact constants depend on the selected theorem.

Tier 3 — Proof roadmap. Explain isotropy, concentration for one fixed difference, the union bound over pairs, and why logarithm and $\varepsilon^{-2}$ appear. Independence between pairwise bad events is not needed.

Tier 4 — Counterexamples. Give (a) an unscaled projection, (b) duplicate random rows, (c) a vector chosen from the map’s null space after inspection, and (d) two nearly tied neighbors whose order can reverse within the allowed distortion.

Tier 5 — Transform choice. Compare Gaussian, Rademacher, sparse JL/feature hashing, and FJLT for a dense batch matrix and for single sparse online vectors. Include multiplication cost, memory, randomness, hardware fit, and theorem assumptions.

Tier 6 — Professional artifact. Produce a dimension-selection memo with $N$ or subspace dimension $d$, $n$, $\varepsilon$, $\delta$, theorem and constants, calculated $k$, candidate operational values, seed policy, distance and recall metrics, slice analysis, drift monitoring, exact-verification stage, and rollback rule.

Debugging prompts: if norms inflate with $k$, check scaling; if basis vectors collapse, inspect sparse collisions; if offline results vary across runs, version seeds; if recall falls despite acceptable average distortion, inspect neighbor margins and tail pairs; if post-launch queries degrade, examine adaptivity and drift.

Stretch goal: derive how $k$ changes when $N$ grows tenfold, $\delta$ decreases one hundredfold, or $\varepsilon$ halves. Explain why halving $\varepsilon$ is typically the most expensive of these changes.

Rubric (10 points): definitions and quantifiers 2; correct dimension derivation 2; proof logic 2; valid counterexamples 2; measurable production decision 2. Full credit requires separating theorem-level squared-norm distortion from downstream nearest-neighbor recall.

Decision checklist: name the fixed set or subspace, metric, distortion, failure budget, transform family, scaling, randomness, and downstream margin; calculate $k$ from the matching theorem; then validate tail pairs, slices, speed, and drift. Expectation is not concentration, fixed-vector success is not all-vector success, and exact reranking cannot restore missed candidates. These embeddings connect linear sketches to randomized linear algebra, least squares, low-rank approximation, and large-scale graph and matrix processing.

Next in the Series

In Randomized Numerical Linear Algebra, we'll explore Sketch matrices for regression, low rank, and spectral tasks..