intermediate embedding-geometry 34 min read

Random Projections and the Johnson–Lindenstrauss Lemma

Reducing embedding dimension with a matrix that never saw the data — and the dimension-independent price of preserving every distance

Overview & motivation

The previous topic reduced an embedding cloud’s dimension by reading the cloud’s own covariance: principal component analysis finds the directions the data actually varies along and projects onto the top kk of them. It is variance-optimal, but it pays a price that is easy to overlook — it must see the data first, eigendecompose a d×dd \times d covariance, and recompute when the corpus changes. This topic asks a question that sounds too good to be true: can we shrink dd with a map that never looks at the data at all?

The answer is the Johnson–Lindenstrauss lemma, and it is yes. Draw a random matrix ARk×dA \in \mathbb{R}^{k \times d} — Gaussian entries will do — and the map f(x)=1kAxf(x) = \tfrac{1}{\sqrt{k}} A x preserves every pairwise distance in a set of nn points to within a factor of 1±ε1 \pm \varepsilon, provided kk is on the order of ε2logn\varepsilon^{-2}\log n. The headline is the dimension that does not appear: the target kk depends on logn\log n and the tolerance ε\varepsilon, but not on the ambient dimension dd. A million points embed into the same target dimension whether they started in R768\mathbb{R}^{768} or R100000\mathbb{R}^{100000}.

Before the algebra, drag the target-dimension slider and watch the distortion concentrate:

0.51.01.51 ± ε band
Histogram of the pairwise squared-distortion ‖f(u)−f(v)‖²/‖u−v‖² across all 124,750 pairs. At small k the distortion spreads everywhere; as k grows it concentrates into the ±ε band around 1 — the chi-squared law tightening at rate √(2/k).
distortion std at k = 128
0.106
√(2/k)
0.125
mean (≈ 1)
0.962

The first panel is the histogram of pairwise distortions: at small kk the projected distances scatter wildly, and as kk grows they pull into the ±ε\pm\varepsilon band around 11 — the visual signature of the chi-squared law tightening. The second separates the typical pair from the worst pair, which is the difference between an average and a guarantee. The third shows that the dense Gaussian matrix is a luxury: Rademacher and sparse variants concentrate just as tightly. The fourth marks the edge of the job: a random projection is a distance sketch, so it preserves distances rather than exact rankings — which is why it belongs at the front of an approximate-search pipeline, not in place of the retriever.

What we cover

  1. The random map, and the unbiasedness that every Johnson–Lindenstrauss proof begins from.
  2. The chi-squared law of the squared norm, and the concentration that makes it useful.
  3. The lemma itself: a union bound over the difference vectors, and the dimension-independent target kk.
  4. Why the bound is worst-case, and how far the typical pair beats it.
  5. Database-friendly projections: binary and sparse matrices with the same guarantee.
  6. Optimality of the bound, and the division of labor with PCA: what a data-oblivious distance sketch is for.
  7. A finance case study and the tested code.

The random map, and why it preserves norm in expectation

Fix a target dimension k<dk < d and draw ARk×dA \in \mathbb{R}^{k \times d} with independent standard-normal entries AijN(0,1)A_{ij} \sim \mathcal{N}(0,1). The random projection of a vector xRdx \in \mathbb{R}^d is

f(x)=1kAxRk.f(x) = \frac{1}{\sqrt{k}}\, A x \in \mathbb{R}^k .

The scaling 1/k1/\sqrt{k} is the only piece of design in the whole construction, and it is there to make the map preserve length on average. Write aia_i^{\top} for the ii-th row of AA, so the ii-th coordinate of AxAx is the inner product aixa_i \cdot x.

Theorem 1 (The random projection is unbiased, and its squared norm is chi-squared).

For x0x \neq 0 and a Gaussian random matrix AA,

Ef(x)2=x2,f(x)2x2χk2k,\mathbb{E}\,\lVert f(x)\rVert^2 = \lVert x\rVert^2, \qquad \frac{\lVert f(x)\rVert^2}{\lVert x\rVert^2} \sim \frac{\chi^2_k}{k},

where χk2\chi^2_k is the chi-squared distribution with kk degrees of freedom. In particular the normalized squared norm has mean 11 and variance 2/k2/k.

Proof.

Each row aia_i is a standard Gaussian vector in Rd\mathbb{R}^d, so the inner product aix=jAijxja_i \cdot x = \sum_{j} A_{ij}\,x_j is a linear combination of independent normals and is therefore itself normal, with mean 00 and variance jxj2=x2\sum_j x_j^2 = \lVert x\rVert^2. Hence aixN(0,x2)a_i \cdot x \sim \mathcal{N}(0, \lVert x\rVert^2), and the standardized quantity Zi:=(aix)/xN(0,1)Z_i := (a_i \cdot x)/\lVert x\rVert \sim \mathcal{N}(0,1). Because the rows of AA are independent, the Z1,,ZkZ_1, \dots, Z_k are independent. Now

f(x)2x2=Ax2kx2=1ki=1k(aix)2x2=1ki=1kZi2,\frac{\lVert f(x)\rVert^2}{\lVert x\rVert^2} = \frac{\lVert A x\rVert^2}{k\,\lVert x\rVert^2} = \frac{1}{k}\sum_{i=1}^k \frac{(a_i \cdot x)^2}{\lVert x\rVert^2} = \frac{1}{k}\sum_{i=1}^k Z_i^2 ,

and a sum of kk independent squared standard normals is by definition the chi-squared distribution with kk degrees of freedom. So f(x)2/x2=χk2/k\lVert f(x)\rVert^2/\lVert x\rVert^2 = \chi^2_k / k, which has mean k/k=1k/k = 1 and variance 2k/k2=2/k2k/k^2 = 2/k. Multiplying through by x2\lVert x\rVert^2 gives Ef(x)2=x2\mathbb{E}\lVert f(x)\rVert^2 = \lVert x\rVert^2. \blacksquare

Two things are worth reading off this. The map is unbiased — on average it neither stretches nor shrinks — and its fluctuation, with variance 2/k2/k, shrinks as the target dimension grows. The standard deviation 2/k\sqrt{2/k} is the single number the histogram panel is tracking: at k=64k = 64 it is about 0.180.18, at k=512k = 512 about 0.060.06. Unbiasedness alone is useless — a map can be right on average and wrong every time. What rescues the construction is that this fluctuation does not merely shrink, it concentrates exponentially.


Concentration: the chi-squared tail

The variance 2/k2/k tells us the typical deviation, but the lemma needs a statement about rare deviations: how unlikely is it that a single vector’s squared norm strays from 11 by more than ε\varepsilon? The answer is the chi-squared tail, and it decays exponentially in kε2k\varepsilon^2.

Theorem 2 (Sub-exponential concentration of the squared norm).

For the Gaussian random projection and any ε(0,1)\varepsilon \in (0,1),

Pr ⁣[f(x)2x21>ε]    2exp ⁣(k2(ε22ε33)).\Pr\!\left[\,\left|\frac{\lVert f(x)\rVert^2}{\lVert x\rVert^2} - 1\right| > \varepsilon \,\right] \;\le\; 2\,\exp\!\left(-\frac{k}{2}\left(\frac{\varepsilon^2}{2} - \frac{\varepsilon^3}{3}\right)\right).
Proof.

Write Y=f(x)2/x2=1kiZi2Y = \lVert f(x)\rVert^2/\lVert x\rVert^2 = \tfrac1k\sum_i Z_i^2 with ZiN(0,1)Z_i \sim \mathcal{N}(0,1) independent, so kYχk2kY \sim \chi^2_k. We bound the upper tail Pr[Y1+ε]\Pr[Y \ge 1+\varepsilon] with the Chernoff / moment-generating-function method developed in concentration inequalities. For any t(0,12)t \in (0, \tfrac12), the moment generating function of a single Zi2Z_i^2 is EetZi2=(12t)1/2\mathbb{E}\,e^{tZ_i^2} = (1-2t)^{-1/2}, so by independence EetkY=(12t)k/2\mathbb{E}\,e^{t\,kY} = (1-2t)^{-k/2}, and Markov’s inequality applied to etkYe^{t\,kY} gives

Pr[kYk(1+ε)]    etk(1+ε)(12t)k/2=exp ⁣( ⁣k[t(1+ε)+12ln(12t)]).\Pr[\,kY \ge k(1+\varepsilon)\,] \;\le\; e^{-t k (1+\varepsilon)}\,(1-2t)^{-k/2} = \exp\!\Big(\!-k\big[t(1+\varepsilon) + \tfrac12\ln(1-2t)\big]\Big).

The exponent is minimized at t=ε2(1+ε)t^\star = \tfrac{\varepsilon}{2(1+\varepsilon)}, where 12t=(1+ε)11 - 2t^\star = (1+\varepsilon)^{-1}. Substituting collapses the bracket to 12(εln(1+ε))\tfrac12\big(\varepsilon - \ln(1+\varepsilon)\big), so

Pr[Y1+ε]    exp ⁣(k2(εln(1+ε)))    exp ⁣(k2(ε22ε33)),\Pr[Y \ge 1+\varepsilon] \;\le\; \exp\!\left(-\frac{k}{2}\big(\varepsilon - \ln(1+\varepsilon)\big)\right) \;\le\; \exp\!\left(-\frac{k}{2}\left(\frac{\varepsilon^2}{2} - \frac{\varepsilon^3}{3}\right)\right),

using the elementary inequality ln(1+ε)εε22+ε33\ln(1+\varepsilon) \le \varepsilon - \tfrac{\varepsilon^2}{2} + \tfrac{\varepsilon^3}{3} for ε0\varepsilon \ge 0. The lower tail Pr[Y1ε]\Pr[Y \le 1-\varepsilon] is bounded the same way with t<0t < 0 and yields the same right-hand side (in fact a slightly smaller one); the sharp two-sided constants are Laurent and Massart’s (2000). Adding the two tails gives the factor of 22. \blacksquare

This is the load-bearing estimate. The probability that a fixed vector’s length is mangled by more than ε\varepsilon decays like eckε2e^{-c k \varepsilon^2}, so we can drive it as low as we like by spending dimensions: doubling kk squares the failure probability. The next step spends exactly enough of them to cover not one vector but every pairwise difference in a data set at once.


The Johnson–Lindenstrauss lemma

A distance is the norm of a difference: xaxb\lVert x_a - x_b\rVert. Because ff is linear, f(xa)f(xb)=f(xaxb)f(x_a) - f(x_b) = f(x_a - x_b), so preserving the distance between two points is exactly preserving the norm of their difference vector. Theorem 2 controls one such vector; to control all of them we apply it to every difference and add up the failure probabilities — the union bound.

Theorem 3 (Johnson–Lindenstrauss (1984)).

Let x1,,xnRdx_1, \dots, x_n \in \mathbb{R}^d and ε(0,1)\varepsilon \in (0,1). If

k    4lnnε2/2ε3/3,k \;\ge\; \frac{4\ln n}{\,\varepsilon^2/2 - \varepsilon^3/3\,},

then a single Gaussian random projection f:RdRkf : \mathbb{R}^d \to \mathbb{R}^k satisfies, with positive probability,

(1ε)xaxb2    f(xa)f(xb)2    (1+ε)xaxb2for all pairs a,b.(1-\varepsilon)\,\lVert x_a - x_b\rVert^2 \;\le\; \lVert f(x_a) - f(x_b)\rVert^2 \;\le\; (1+\varepsilon)\,\lVert x_a - x_b\rVert^2 \qquad\text{for all pairs } a, b .

In particular such an ff exists.

Proof.

Apply Theorem 2 to each of the (n2)\binom{n}{2} difference vectors xaxbx_a - x_b. The event that some pair is distorted by more than ε\varepsilon is the union of the per-pair failure events, so by the union bound its probability is at most the sum of the per-pair probabilities:

Pr[some pair fails]    (n2)2exp ⁣(k2(ε22ε33))  <  n2exp ⁣(k2(ε22ε33)),\Pr[\,\text{some pair fails}\,] \;\le\; \binom{n}{2}\cdot 2\exp\!\left(-\frac{k}{2}\left(\frac{\varepsilon^2}{2} - \frac{\varepsilon^3}{3}\right)\right) \;<\; n^2 \exp\!\left(-\frac{k}{2}\left(\frac{\varepsilon^2}{2} - \frac{\varepsilon^3}{3}\right)\right),

using (n2)<n2/2\binom{n}{2} < n^2/2. This is strictly below 11 exactly when k2(ε22ε33)>2lnn\tfrac{k}{2}\big(\tfrac{\varepsilon^2}{2} - \tfrac{\varepsilon^3}{3}\big) > 2\ln n, that is when k>4lnn/(ε2/2ε3/3)k > 4\ln n/(\varepsilon^2/2 - \varepsilon^3/3). When the failure probability is below 11, the success probability is positive, so at least one realization of AA embeds every pair within tolerance — and a random draw succeeds with probability at least 1n2exp()1 - n^2\exp(\cdots), which we can push toward 11 by taking kk a constant factor larger. \blacksquare

Look at what the target dimension depends on. The denominator is a function of ε\varepsilon alone; the numerator is lnn\ln n. The ambient dimension dd has vanished. This is the sense in which random projection beats the curse of dimensionality at its own game: the cost of preserving the geometry of nn points is set by how many points there are, not by how many coordinates they arrived with. The companion harness confirms the lemma directly — at the guaranteed kk, a single Gaussian projection holds all (n2)\binom{n}{2} pairs inside the band across every random seed it tries.


The bound is worst-case: typical versus worst

The lemma is a guarantee, and a guarantee must hold for the worst pair, not the average one — which is why its constant is pessimistic. Set n=500n = 500 and ε=0.2\varepsilon = 0.2, the finance configuration: the formula demands

k    4ln5000.22/20.23/31435,k \;\ge\; \frac{4\ln 500}{0.2^2/2 - 0.2^3/3} \approx 1435 ,

larger than many ambient dimensions one would actually project from. Yet project the same cloud to a practical k=128k = 128 and the typical pair distorts by only about 9%9\%. The gap is the difference between an average and a maximum: with 124,750124{,}750 pairs, the worst of them still distorts by about 51%51\% at k=128k = 128, and pulling that worst pair inside ±ε\pm\varepsilon is what the large guaranteed kk buys. The “Typical vs worst” panel makes this concrete — the p01p_{01}p99p_{99} band slips inside ±ε\pm\varepsilon while the worst-pair envelope is still well outside it.

Two honest consequences follow. The constant 44 is loose, and in practice one uses a far smaller kk than the lemma demands, accepting that a handful of pairs are badly distorted — random projection is a tool for approximate geometry. And the dimension independence is a statement about the worst case over arbitrary point sets; a structured, near-low-rank cloud of real embeddings is far easier than the worst case, which is exactly the slack the next sections exploit and measure.


Database-friendly projections

The dense Gaussian matrix is expensive: projecting one vector costs kdkd multiplications, and storing AA costs kdkd floats. Achlioptas (2003) showed that neither the Gaussian entries nor the density is necessary. Replace AijA_{ij} with random signs, or with a matrix that is mostly zero, and the guarantee survives.

Proposition 1 (Rademacher and sparse projections are unbiased).

Let the entries of AA be drawn independently as either Rademacher signs, Aij=±1A_{ij} = \pm 1 with equal probability, or the sparse Achlioptas values Aij=s{+1,0,1}A_{ij} = \sqrt{s}\cdot\{+1, 0, -1\} with probabilities {12s,11s,12s}\{\tfrac{1}{2s}, 1-\tfrac1s, \tfrac{1}{2s}\}. In both cases E[Aij2]=1\mathbb{E}[A_{ij}^2] = 1, and the map f(x)=1kAxf(x) = \tfrac{1}{\sqrt{k}}Ax is unbiased: Ef(x)2=x2\mathbb{E}\lVert f(x)\rVert^2 = \lVert x\rVert^2.

Proof.

For the Rademacher case Aij2=1A_{ij}^2 = 1 deterministically, so E[Aij2]=1\mathbb{E}[A_{ij}^2] = 1. For the sparse case E[Aij2]=s(12s+12s)=s1s=1\mathbb{E}[A_{ij}^2] = s \cdot (\tfrac{1}{2s} + \tfrac{1}{2s}) = s\cdot\tfrac1s = 1; with s=3s = 3 the matrix is two-thirds zeros. In either case the entries are independent with mean 00 and second moment 11, so

EAx2=i=1kE[(jAijxj)2]=i=1kjE[Aij2]xj2=i=1kx2=kx2,\mathbb{E}\lVert Ax\rVert^2 = \sum_{i=1}^k \mathbb{E}\Big[\big(\textstyle\sum_j A_{ij}x_j\big)^2\Big] = \sum_{i=1}^k \sum_{j} \mathbb{E}[A_{ij}^2]\,x_j^2 = \sum_{i=1}^k \lVert x\rVert^2 = k\lVert x\rVert^2 ,

the cross terms vanishing because E[AijAi]=0\mathbb{E}[A_{ij}A_{i\ell}] = 0 for jj \neq \ell. Dividing by kk gives Ef(x)2=x2\mathbb{E}\lVert f(x)\rVert^2 = \lVert x\rVert^2. \blacksquare

Unbiasedness is the easy half; what makes these valid Johnson–Lindenstrauss maps is that their squared norm concentrates at the same 2/k\sqrt{2/k} rate as the Gaussian one. Both families are sub-Gaussian, and Achlioptas proves a tail of the same exponential form — we cite that result rather than re-prove it, and the harness verifies it numerically: at k=64k = 64 the Gaussian, Rademacher, and sparse distortion spreads are 0.1540.154, 0.1660.166, and 0.1620.162, all hugging the predicted 2/640.177\sqrt{2/64} \approx 0.177. The “Projection families” panel shows the three side by side. The sparse map is the practical winner: it preserves distances for a third of the arithmetic, the property that makes random projection a cheap front end for large indexes.

There is an honest footnote, which the code surfaces: on a low-rank cloud, where the signal lives in a few coordinates, the very sparse map has a heavier-tailed per-matrix fluctuation than the Gaussian one — zeroing two-thirds of the matrix occasionally under-samples the signal directions. The concentration rate is unchanged, but the constant is a little worse, which is the kind of trade the sparsity buys.


Optimality, and the division of labor with PCA

Could a cleverer map do better than k=Θ(ε2logn)k = \Theta(\varepsilon^{-2}\log n)? For a data-oblivious map asked to preserve all pairwise distances, no.

Proposition 2 (The target dimension is optimal (Larsen–Nelson 2017)).

For every nn and ε\varepsilon in the relevant range there exist nn points in Rd\mathbb{R}^d such that any embedding into Rk\mathbb{R}^k preserving all pairwise distances to within (1±ε)(1\pm\varepsilon) must have k=Ω(ε2logn)k = \Omega(\varepsilon^{-2}\log n). The Johnson–Lindenstrauss bound is therefore tight up to the constant.

We cite this rather than prove it; the construction takes a near-orthogonal point set on which no projection can do better. So within its remit — preserving all pairwise distances without ever looking at the data — Johnson–Lindenstrauss is not merely serviceable but optimal: no data-oblivious map reaches a smaller target dimension. That is the achievement to keep in view. What the bound does not claim is optimality on a particular, structured cloud, and that is where PCA divides the labor rather than competing. PCA is data-dependent: it reads the covariance and spends every kept dimension on a direction the cloud actually varies along, so on a structured corpus it captures, per dimension, geometry that a map asking nothing of the data does not. The two are built for different jobs — JL for a fixed, dimension-independent guarantee over any point set with no training; PCA for the most it can wring from this one.

That division of labor has one sharp edge worth stating plainly, because it decides where each tool belongs. Johnson–Lindenstrauss preserves distances — which is exactly the currency an approximate-nearest-neighbor index trades in — but preserving every distance to ±ε\pm\varepsilon does not preserve the order of distances when neighbors sit closer together than ε\varepsilon. On a tightly clustered cloud the tenth and eleventh nearest neighbors are nearly equidistant, so a ±ε\pm\varepsilon wobble can swap them, and exact recall@10 falls — about 23%23\% for the random projection at k=128k = 128 against about 96%96\% for the data-dependent PCA of the same width (the “Recall after projection” panel). That is not the sketch underperforming; it is the sketch being a distance sketch rather than a retriever. Its role, by design, is the front end of an approximate-search pipeline — the dimensionality-reduction step before locality-sensitive hashing, the forthcoming topic — where a cheap, distance-preserving sketch is precisely what the next stage consumes, and the exact ordering is restored downstream by a rerank.


Finance case study


Honest caveats


Implementation

The companion module johnson_lindenstrauss.py owns every number this page and the laboratory cite. It builds the three projection families through a single generator stream — a deliberate choice, since drawing each random matrix from a freshly seeded generator over consecutive integers leaves their opening values weakly correlated and inflates the sampled variance with dd, a real and easily-missed NumPy pitfall. Its eight assertions encode the claims in order: unbiasedness for all three families; the chi-squared mean, variance, and Laurent–Massart tail; the lemma holding at the guaranteed kk; dimension independence (a fixed vector’s distortion spread is 2/k\sqrt{2/k} for every dd, while the worst pairwise distortion grows with nn); the three families concentrating alike; the recall gap between oblivious and data-dependent projection; a cross-check of the target dimension and distortion against scikit-learn’s random_projection; and the finance headline. The narrative notebook walks the same path section by section. Both run in about seven seconds and must exit cleanly before the topic ships.

Connections

  • PCA is the data-dependent counterpart to this topic's data-oblivious projection: it reads the covariance and spends each kept dimension where the cloud actually varies, so at the same width it preserves far more nearest-neighbor recall, while random projection asks nothing of the data and pays for that obliviousness in retrieval — the two are the variance-optimal and the distance-preserving answers to the same dimensionality-reduction question pca-dimensionality-reduction
  • the concentration of measure proved there is exactly the engine here: Johnson-Lindenstrauss works because the squared norm of a random projection is a sum of many independent contributions that concentrates sharply about its mean, the same thin-shell phenomenon that topic develops, now turned from a curse into the guarantee that distances survive high-dimensional-geometry

References & Further Reading