Module contents
Lesson 22 of 24Advanced 100 min

Concentration of measure in high dimensions and Johnson-Lindenstrauss

High-dimensional random geometry concentrates: Gaussian mass lies in a thin shell, random directions are nearly orthogonal, and ε-nets and Johnson-Lindenstrauss yield useful guarantees.

After this lesson you can

  • Prove that ‖Z‖ concentrates around √d for Z ~ N(0, I_d), with O(1) fluctuations.
  • Quantify near orthogonality of random vectors and how many nearly orthogonal vectors fit in ℝᵈ.
  • Construct ε-nets of the sphere and bound their size using volume.
  • Prove the Johnson-Lindenstrauss lemma and implement random projections satisfying it.
  • Explain why Euclidean distances become similar in high dimension.

Before you start

Motivation: a thousand dimensions are not three

A small embedding model converts each sentence into a vector of R384\R^{384}; a large one into one of R4096\R^{4096}. Transformer layers live in R768\R^{768} or R12288\R^{12288}, and their weights are initialized randomly. A vector database stores millions of those vectors and returns the nearest to a query. And a one-line dimension reduction technique, multiplication by a random matrix, compresses these vectors to a few hundred coordinates without inspecting the data while preserving all distances with controlled error.

That the last fact works is surprising. That it works because of high dimension, rather than despite it, is this lesson’s subject. In Rd\R^d with large dd, the geometry of random objects is almost deterministic:

  • A Gaussian vector Z∼N(0,Id)Z \sim \Normal(\vb{0}, \mat{I}_d) has norm d\sqrt d with fluctuations of size 1, even though its density is maximal at the origin.
  • Two random directions are nearly orthogonal: the cosine of their angle is of order 1/d1/\sqrt d.
  • Almost all the ball’s volume hugs its surface, while also lying near any equator.
  • Distances between random points are almost all equal.

All four statements are instances of the same phenomenon, concentration of measure: a smooth function of many independent variables is almost constant. You already have the tools to prove it. Chernoff and Bernstein inequalities control sums, and Gaussian concentration of Lipschitz functions controls any function with bounded slope. Here we apply them to the geometry of Rd\R^d and turn geometry into algorithms: ε-nets turn pointwise bounds into bounds for infinitely many points at once, and the Johnson–Lindenstrauss lemma reduces dimension with guarantees independent of dd.

The Gaussian is a soap bubble

Start with the simplest calculation. If Z=(Z1,…,Zd)Z = (Z_1, \dots, Z_d) has components Zi∼iidN(0,1)Z_i \iid \Normal(0, 1), its squared norm is a sum of dd independent variables with mean 1 and variance Var⁡(Zi2)=E[Zi4]−1=2\Var(Z_i^2) = \E[Z_i^4] - 1 = 2:

E∥Z∥2=d,Var⁡∥Z∥2=2d,∥Z∥2d=1+OP(1d).\E\norm{Z}^2 = d, \qquad \Var\norm{Z}^2 = 2d, \qquad \frac{\norm{Z}^2}{d} = 1 + \bigO_P\Big(\frac{1}{\sqrt d}\Big).

Thus ∥Z∥≈d\norm{Z} \approx \sqrt d. So far, the law of large numbers. What is striking is its geometric meaning: density φd(x)=(2π)−d/2e−∥x∥2/2\varphi_d(\vb{x}) = (2\pi)^{-d/2} e^{-\norm{\vb{x}}^2/2} is maximal at the origin, yet almost no sample falls near it. All mass is in a thin shell of radius d\sqrt d.

InteractiveThe Gaussian is a soap bubble
Histogram of ∥X∥/d\norm{X}/\sqrt d with d=100d = 100
origin
  • 3000 samples of ∥X∥\norm{X}
  • exact density (χd\chi_d)
  • origin, where density of XX is maximal
  • mode of ∥X∥\norm{X}: d−1\sqrt{d-1} (vertical)
Point density versus mass by radius (each curve divided by its maximum)
  • density of XX at radius rr: e−r2/2e^{-r^2/2}
  • mass at radius rr: rd−1e−r2/2r^{d-1}e^{-r^2/2}
100
Histogram scale
Mean of ∥X∥\norm{X} (simulated)9.973 (√d = 10.000)
Standard deviation of ∥X∥\norm{X}: simulated / exact0.713 / 0.706
Samples with ∣∥X∥−d∣≤1\abs{\norm{X} - \sqrt d} \le 184.5 %
P(∥X∥≤d/2)\Pr(\norm{X} \le \sqrt d / 2) (exact)1.1·10⁻¹⁵
Density at the origin / density at ∥x∥=d\norm{x} = \sqrt d5.2·10²¹
Left: histogram of 3000 norms ∥X∥\norm{X} with X∼N(0,Id)X \sim \Normal(\vb{0}, \mat{I}_d) and exact density of law χd\chi_d. With d=100d = 100 no sample is near the origin (orange line). Increase dd to 10410^4 on scale ∥X∥/d\norm{X}/\sqrt d: everything stacks up at 1. Switch to scale ∥X∥−d\norm{X} - \sqrt d: width stops shrinking and stabilizes at standard deviation 0.7070.707. Right: the paradox in a picture: point density (orange) falls from the origin, but the number of points at each radius grows as rd−1r^{d-1}, and their product, radial mass (blue), lives at r≈dr \approx \sqrt d. Compare d=1d = 1, where both curves coincide, with d=100d = 100.

The explanation is in the blue curve. The probability that ∥Z∥\norm{Z} falls in [r,r+ ⁣dr][r, r + \dd r] is the density at that radius times the area of the sphere of radius rr, proportional to rd−1r^{d-1}. Factor rd−1r^{d-1} grows rapidly and e−r2/2e^{-r^2/2} falls rapidly; their product rd−1e−r2/2r^{d-1}e^{-r^2/2} peaks at r=d−1r = \sqrt{d-1}, the mode of law χd\chi_d, with width of order 1.

This is norm concentration: ∥Z∥2\norm{Z}^2 deviates from dd by a fraction ε\eps with probability exponentially small in dε2d\eps^2, and ∥Z∥\norm{Z} deviates from d\sqrt d by tt with sub-Gaussian probability in tt, with no factor dd: fluctuations are O(1)\bigO(1).

Proof

First part (Chernoff). ∥Z∥2\norm{Z}^2 has law χd2\chi^2_d, the gamma distribution with shape d/2d/2 and scale 2, with moment-generating function Eeλ∥Z∥2=(1−2λ)−d/2\E e^{\lambda\norm{Z}^2} = (1 - 2\lambda)^{-d/2} for λ<1/2\lambda < 1/2. By the Chernoff method, for 0<λ<1/20 < \lambda < 1/2,

P(∥Z∥2≥(1+ε)d)≤e−λ(1+ε)d(1−2λ)−d/2.\Pr\big(\norm{Z}^2 \ge (1 + \eps)d\big) \le e^{-\lambda(1+\eps)d}(1 - 2\lambda)^{-d/2}.

The minimum is at λ=ε/(2(1+ε))\lambda = \eps/(2(1 + \eps)), where 1−2λ=1/(1+ε)1 - 2\lambda = 1/(1+\eps), and equals ((1+ε)e−ε)d/2\big((1 + \eps)e^{-\eps}\big)^{d/2}. Since log⁡(1+ε)≤ε−ε2/2+ε3/3\log(1 + \eps) \le \eps - \eps^2/2 + \eps^3/3, we have (1+ε)e−ε≤e−ε2/2+ε3/3(1+\eps)e^{-\eps} \le e^{-\eps^2/2 + \eps^3/3} and obtain the first bound. For the lower tail use λ<0\lambda < 0: with λ=−ε/(2(1−ε))\lambda = -\eps/(2(1 - \eps)) the same calculation gives ((1−ε)eε)d/2\big((1 - \eps)e^{\eps}\big)^{d/2}, and log⁡(1−ε)≤−ε−ε2/2\log(1 - \eps) \le -\eps - \eps^2/2 gives e−dε2/4e^{-d\eps^2/4}.

Second part (Lipschitz). The norm is 1-Lipschitz: ∣∥x∥−∥y∥∣≤∥x−y∥\abs{\norm{\vb{x}} - \norm{\vb{y}}} \le \norm{\vb{x} - \vb{y}} by the triangle inequality. Gaussian concentration of Lipschitz functions directly gives P(∣∥Z∥−E∥Z∥∣≥t)≤2e−t2/2\Pr(\abs{\norm{Z} - \E\norm{Z}} \ge t) \le 2e^{-t^2/2}. It remains to locate md=E∥Z∥m_d = \E\norm{Z}. By Jensen, md≤E∥Z∥2=dm_d \le \sqrt{\E\norm{Z}^2} = \sqrt d. For the lower bound, integrating the density of χd\chi_d gives md=2 Γ(d+12)/Γ(d2)m_d = \sqrt 2\,\Gamma(\tfrac{d+1}{2})/\Gamma(\tfrac d2), and hence

md md+1=2 Γ(d2+1)Γ(d2)=d.m_d\, m_{d+1} = \frac{2\,\Gamma(\tfrac d2 + 1)}{\Gamma(\tfrac d2)} = d.

With md+1≤d+1m_{d+1} \le \sqrt{d+1} this becomes md≥d/d+1m_d \ge d/\sqrt{d + 1}, and since 1−1−x≤x1 - \sqrt{1 - x} \le x at [0,1][0, 1], d−md≤d (1−d/(d+1))≤d/(d+1)≤1/d\sqrt d - m_d \le \sqrt d\,\big(1 - \sqrt{d/(d+1)}\big) \le \sqrt d/(d + 1) \le 1/\sqrt d.

∎

The first part also follows from general theory: each Zi2−1Z_i^2 - 1 is subexponential, and Bernstein’s inequality for their sum gives P(∣∥Z∥2/d−1∣≥ε)≤2exp⁡(−c dmin⁡(ε2,ε))\Pr(\abs{\norm{Z}^2/d - 1} \ge \eps) \le 2\exp(-c\,d\min(\eps^2, \eps)) with an absolute constant cc. This form generalizes to non-Gaussian inputs; direct calculation with χ2\chi^2 gives explicit constants, which we use in Johnson–Lindenstrauss. The second part refines fluctuation size: by the delta method, d (∥Z∥2/d−1)→N(0,2)\sqrt d\,(\norm{Z}^2/d - 1) \to \Normal(0, 2) implies ∥Z∥−d→N(0,1/2)\norm{Z} - \sqrt d \to \Normal(0, 1/2), and therefore the standard deviation in the figure tends to 1/2≈0.7071/\sqrt 2 \approx 0.707.

The mode that is not typical

The figure’s paradox can be quantified. With d=100d = 100, density at the origin is ed/2≈5×1021e^{d/2} \approx 5\times 10^{21} times density at a point of norm d=10\sqrt d = 10, yet P(∥Z∥≤d/2)≈1.1×10−15\Pr(\norm{Z} \le \sqrt d/2) \approx 1.1\times 10^{-15}. There is no contradiction: the ball of radius 5 has tiny volume compared with the shell of radius 10, because volume scales as rdr^d and 2100≈10302^{100} \approx 10^{30}.

The useful interpretation comes from information theory. −log⁡φd(Z)=d2log⁡(2π)+12∥Z∥2-\log\varphi_d(Z) = \tfrac d2\log(2\pi) + \tfrac12\norm{Z}^2 concentrates around its mean, the differential entropy: almost all mass lies in a typical set where density is approximately e−entropıˊae^{-\text{entropía}}, and the mode is outside it. For any high-dimensional distribution, “the most probable point” and “a typical point” are very different. The code checks this: the midpoint of two Gaussian latents is not a typical latent.

Near orthogonality

Normalizing a Gaussian vector produces a random direction. If Z∼N(0,Id)Z \sim \Normal(\vb{0}, \mat{I}_d) and Q\mat{Q} is orthogonal, QZ\mat{Q}Z has the same law as ZZ (the rotational invariance), so u=Z/∥Z∥\vb{u} = Z/\norm{Z} has a rotation-invariant law on sphere Sd−1S^{d-1}. That law is the uniform measure σ\sigma on the sphere, the unique probability on Sd−1S^{d-1} with that invariance.

What inner product do u\vb{u} and a fixed unit vector v\vb{v} have? By invariance, the same as u\vb{u} and e1\vb{e}_1, namely coordinate u1u_1. By symmetry, Eu1=0\E u_1 = 0 and all Eui2\E u_i^2 are equal; since they sum to E∥u∥2=1\E\norm{\vb{u}}^2 = 1,

E⟨u,v⟩=0,E⟨u,v⟩2=1d.\E\inner{\vb{u}}{\vb{v}} = 0, \qquad \E\inner{\vb{u}}{\vb{v}}^2 = \frac 1d.

The typical inner product of two random directions is order 1/d1/\sqrt d: in R104\R^{10^4}, a cosine of 0.010.01, an angle of 89.4°89.4°. The exact law is also accessible: u12=Z12/(Z12+W)u_1^2 = Z_1^2/(Z_1^2 + W) with W=Z22+⋯+Zd2W = Z_2^2 + \cdots + Z_d^2 independent of Z1Z_1, a ratio of independent gammas, so u12∼Beta⁡(12,d−12)u_1^2 \sim \operatorname{Beta}(\tfrac12, \tfrac{d-1}{2}) by the relationship between gamma and beta. Changing variable, u1u_1 has density proportional to (1−s2)(d−3)/2(1 - s^2)^{(d-3)/2} on (−1,1)(-1, 1), and angle θ=arccos⁡u1\theta = \arccos u_1 has density proportional to sin⁡d−2θ\sin^{d-2}\theta. For d=2d = 2 the angle is uniform; for large dd, sin⁡d−2θ\sin^{d-2}\theta is a very narrow bell centered at 90°90°.

This is the near orthogonality of random vectors in high dimension: a deviation of 90°90° with fixed cosine tt is exponentially unlikely in dd.

Proof

By invariance it suffices that v=e1\vb{v} = \vb{e}_1, and with u=Z/∥Z∥\vb{u} = Z/\norm{Z} the event is ∣Z1∣≥t∥Z∥\abs{Z_1} \ge t\norm{Z}. Either ∥Z∥<d/2\norm{Z} < \sqrt d/2 or ∣Z1∣≥td/2\abs{Z_1} \ge t\sqrt d/2:

P(∣Z1∣≥t∥Z∥)≤P(∣Z1∣≥td2)+P(∥Z∥2<d4)≤2e−dt2/8+e−9d/64.\Pr\big(\abs{Z_1} \ge t\norm{Z}\big) \le \Pr\Big(\abs{Z_1} \ge \frac{t\sqrt d}{2}\Big) + \Pr\Big(\norm{Z}^2 < \frac d4\Big) \le 2e^{-dt^2/8} + e^{-9d/64}.

The first bound is Gaussian tail P(∣Z1∣≥s)≤2e−s2/2\Pr(\abs{Z_1} \ge s) \le 2e^{-s^2/2} (Chernoff), and the second is the previous theorem’s lower tail with ε=3/4\eps = 3/4. Since t≤1t \le 1, 9/64≥t2/89/64 \ge t^2/8 and the sum is at most 3e−dt2/83e^{-dt^2/8}. If v\vb{v} is also random and independent, condition on v\vb{v} and apply the above.

∎

Constant 1/81/8 in the exponent is not optimal: the exact beta law gives P(⟨u,v⟩≥t)≤e−dt2/2\Pr(\inner{\vb{u}}{\vb{v}} \ge t) \le e^{-dt^2/2} in each tail (K. Ball, An elementary introduction to modern convex geometry, 1997, lemma 2.2), the tail of a N(0,1/d)\Normal(0, 1/d). What matters is the form e−c dt2e^{-c\,dt^2}.

Exponentially many nearly orthogonal directions

Exactly dd orthogonal vectors fit in Rd\R^d. Relax “orthogonal” to “with ∣cos⁡∣<t\abs{\cos} < t pairwise” and exponentially many fit. The argument is the probabilistic method: choose NN independent uniform vectors and apply the union bound to the N(N−1)/2N(N-1)/2 pairs,

P(alguˊn par con ∣cos⁡∣≥t)≤N22⋅3e−dt2/8<1siN≤0.8 edt2/16.\Pr\big(\text{algún par con } \abs{\cos} \ge t\big) \le \frac{N^2}{2}\cdot 3e^{-dt^2/8} < 1 \quad\text{si}\quad N \le 0.8\,e^{dt^2/16}.

If failure probability is less than 1, some configuration does not fail: eΩ(dt2)e^{\Omega(dt^2)} nearly orthogonal vectors exist. With the exact cosine law instead of the bound, the numbers are concrete. With t=0.2t = 0.2, the guarantee exceeds the dd orthogonal ones from d≈490d \approx 490, and at d=768d = 768, BERT base width, at least about 9500 vectors fit with ∣cos⁡∣<0.2\abs{\cos} < 0.2 pairwise: more than twelve times dd. This geometry underlies the interpretability superposition hypothesis: a network can represent far more features than neurons by encoding them in nearly orthogonal directions and tolerating some interference.

InteractiveAngles between random vectors
Angles among 80 random vectors in R100\R^{100} (3 160 pairs)
|cos θ| < 0.10
  • simulated angles
  • exact density ∝sin⁡d−2θ\propto \sin^{d-2}\theta
  • band ∣cos⁡θ∣<t\abs{\cos\theta} < t
How many vectors with pairwise ∣cos⁡∣<0.10\abs{\cos} < 0.10 fit in Rd\R^d?
N > d from d ≈ 2 619
  • guaranteed by the probabilistic method
  • N=dN = d (exactly orthogonal)
100
0.10
Mean angle between pairs (simulated)90.02°
Standard deviation of cos⁡θ\cos\theta: simulated / 1/d1/\sqrt d0.1016 / 0.1000
Pairs with ∣cos⁡θ∣<t\abs{\cos\theta} < t: simulated / exact67.3 % / 68.0 %
Vectors fitting with pairwise ∣cos⁡∣<t\abs{\cos} < t (guaranteed)3
Compared with dd exactly orthogonal vectorsstill fewer than d
Left: angles between the 3160 pairs of 80 random vectors in Rd\R^d, with exact density ∝sin⁡d−2θ\propto\sin^{d-2}\theta. In d=2d = 2 angle is uniform; increase dd and angles stack at 90°90° with width around 57°/d57°/\sqrt d. The aqua band marks ∣cos⁡θ∣<t\abs{\cos\theta} < t. Right, on a log scale, how many pairwise ∣cos⁡∣<t\abs{\cos} < t vectors the probabilistic method guarantees (with exact cosine law) versus dd exactly orthogonal ones. The pink curve grows exponentially in dd and crosses line N=dN = d: with t=0.1t = 0.1 around d≈2600d \approx 2600, with t=0.3t = 0.3 around d≈170d \approx 170. Move tt and observe the crossing shift.

The converse also holds: no more than exponentially many fit. If ∣cos⁡∣<t\abs{\cos} < t, then ∥u−v∥2=2−2cos⁡>2−2t\norm{\vb{u} - \vb{v}}^2 = 2 - 2\cos > 2 - 2t, so vectors are separated by at least δ=2−2t\delta = \sqrt{2 - 2t}, and the ε-net section’s volume argument gives N≤(1+2/δ)dN \le (1 + 2/\delta)^d. The number of nearly orthogonal directions is eΘ(d)e^{\Theta(d)} for each fixed tt.

High-dimensional volume: orange peel

Move from the Gaussian to unit ball Bd={x:∥x∥≤1}B^d = \{\vb{x} : \norm{\vb{x}} \le 1\} with Lebesgue measure. Its volume has a closed formula obtained by calculating ∫Rde−∥x∥2 ⁣dx\int_{\R^d} e^{-\norm{\vb{x}}^2}\dd\vb{x} in two ways. As a product of one-dimensional integrals it equals πd/2\pi^{d/2}. In polar coordinates the area of a sphere of radius rr is d Vd rd−1d\,V_d\,r^{d-1} (the derivative of volume VdrdV_d r^d), and the integral is ∫0∞e−r2d Vd rd−1 ⁣dr=Vd Γ(d2+1)\int_0^\infty e^{-r^2} d\,V_d\,r^{d-1}\dd r = V_d\,\Gamma(\tfrac d2 + 1). Equating them,

Vd=vol⁡(Bd)=πd/2Γ(d2+1).V_d = \operatorname{vol}(B^d) = \frac{\pi^{d/2}}{\Gamma(\tfrac d2 + 1)}.

It increases until V5≈5.26V_5 \approx 5.26 and then collapses: V20≈0.026V_{20} \approx 0.026 and V100≈2.4×10−40V_{100} \approx 2.4\times 10^{-40}. Compared with enclosing cube [−1,1]d[-1, 1]^d of volume 2d2^d, the inscribed ball is a negligible fraction: almost all cube volume lies in corners, up to distance d\sqrt d from the center.

Two calculations describe where the ball’s volume lies, both using only that Lebesgue measure scales as vol⁡(cA)=cdvol⁡(A)\operatorname{vol}(c A) = c^d\operatorname{vol}(A).

The shell. The fraction of volume at distance less than ε\eps from the boundary is

vol⁡(Bd)−vol⁡((1−ε)Bd)vol⁡(Bd)=1−(1−ε)d≥1−e−εd.\frac{\operatorname{vol}(B^d) - \operatorname{vol}((1 - \eps)B^d)}{\operatorname{vol}(B^d)} = 1 - (1 - \eps)^d \ge 1 - e^{-\eps d}.

With d=1000d = 1000 and ε=0.01\eps = 0.01, 99.996 %99.996\,\% of the volume is in the last hundredth of the radius.

The equator. For any unit direction a\vb{a}, the fraction of volume with ⟨x,a⟩≥t\inner{\vb{x}}{\vb{a}} \ge t is at most (1−t2)d/2≤e−dt2/2(1 - t^2)^{d/2} \le e^{-dt^2/2}. The proof fits in one line: if ∥x∥≤1\norm{\vb{x}} \le 1 and x1≥tx_1 \ge t, then ∥x−te1∥2=∥x∥2−2tx1+t2≤1−t2\norm{\vb{x} - t\vb{e}_1}^2 = \norm{\vb{x}}^2 - 2tx_1 + t^2 \le 1 - t^2, so that region lies inside a ball of radius 1−t2\sqrt{1 - t^2}, whose volume is (1−t2)d/2Vd(1 - t^2)^{d/2}V_d.

These two facts are what we call high-dimensional volume: in the ball of Rd\R^d, almost all volume is simultaneously near the surface and in band ∣⟨x,a⟩∣≤t\abs{\inner{\vb{x}}{\vb{a}}} \le t of any equator. There is no contradiction with many equators: for two directions a,b\vb{a}, \vb{b}, bands almost completely overlap because almost every point is nearly orthogonal to both.

InteractiveOrange peel
The sphere in R3\R^3: equatorial band and shell outline
acorteza
Fraction of mass versus dimension (t=0.10t = 0.10, ε=0.05\eps = 0.05)
  • volume in shell
  • sphere area in band
  • ball volume in band
  • shell and band simultaneously (lower bound)
0.10
0.05
3
Points on the sphere in R3\R^3 in the band (1200)8.9 % (exact: 10 %)
Volume in shell, 1−(1−ε)31 - (1-\eps)^{3}14.3 %
Sphere area in R3\R^{3} within the band10.0 %
Ball volume in R3\R^{3} within the band15.0 %
Volume in both shell and band (at least)0.0 %
Left: the sphere of R3\R^3 in projection: drag to rotate. Aqua points belong to band ∣⟨x,a⟩∣≤t\abs{\langle x, a\rangle} \le t around the equator of axis aa; in R3\R^3 the band has exactly fraction tt of the area (Archimedes), checked with 1200 points. The orange ring is the silhouette of shell 1−ε≤∥x∥≤11 - \eps \le \norm{x} \le 1. Press ‘Another equator’: any direction works. Right, versus dimension, the volume fraction in the shell, sphere-area and ball-volume fractions in the band (exact beta laws), and a lower bound on the fraction in both. With t=0.1t = 0.1 and ε=0.05\eps = 0.05, in d=3d = 3 the band has 10 %10\,\% of the sphere; in d=1000d = 1000, 99.8 %99.8\,\%.

The sphere and ball bands nearly coincide in the figure. This is reasonable: almost all ball volume is in the shell, and the shell resembles the sphere. Thus statements for uniform measure on sphere and ball are interchangeable in high dimension, up to constants.

Concentration on the sphere for Lipschitz functions

Cosine ⟨u,v⟩\inner{\vb{u}}{\vb{v}} is a special case of a function of u\vb{u} with bounded slope. The phenomenon is general: on a high-dimensional sphere, every Lipschitz function is nearly constant.

This is concentration on the sphere: fluctuations of f(u)f(\vb{u}) are of order L/dL/\sqrt d, although ff may vary over a range of size 2L2L on the sphere.

Proof

The idea is to write u=Z/∥Z∥\vb{u} = Z/\norm{Z} and compare with Z/dZ/\sqrt d, a Lipschitz function of a Gaussian.

  1. Extension. F(x)=inf⁡y∈Sd−1(f(y)+L∥x−y∥)F(\vb{x}) = \inf_{\vb{y} \in S^{d-1}}\big(f(\vb{y}) + L\norm{\vb{x} - \vb{y}}\big) extends ff to all of Rd\R^d with the same constant (McShane extension): it is an infimum of LL-Lipschitz functions, and on x∈Sd−1\vb{x} \in S^{d-1} equals f(x)f(\vb{x}) because f(y)+L∥x−y∥≥f(x)f(\vb{y}) + L\norm{\vb{x} - \vb{y}} \ge f(\vb{x}).
  2. Gaussian. h(z)=F(z/d)h(\vb{z}) = F(\vb{z}/\sqrt d) is (L/d)(L/\sqrt d)-Lipschitz. With Z∼N(0,Id)Z \sim \Normal(\vb{0}, \mat{I}_d) and m=Eh(Z)m = \E h(Z), Gaussian concentration gives P(∣h(Z)−m∣≥s)≤2e−ds2/(2L2)\Pr(\abs{h(Z) - m} \ge s) \le 2e^{-ds^2/(2L^2)}.
  3. Comparison. With u=Z/∥Z∥\vb{u} = Z/\norm{Z}, ∣f(u)−h(Z)∣=∣F(Z/∥Z∥)−F(Z/d)∣≤L∥Z∥ ∣1/∥Z∥−1/d∣=L∣d−∥Z∥∣/d\abs{f(\vb{u}) - h(Z)} = \abs{F(Z/\norm{Z}) - F(Z/\sqrt d)} \le L\norm{Z}\,\abs{1/\norm{Z} - 1/\sqrt d} = L\abs{\sqrt d - \norm{Z}}/\sqrt d.
  4. Union. P(∣f(u)−m∣≥t)≤P(∣h(Z)−m∣≥t/2)+P(∣∥Z∥−d∣≥s)\Pr(\abs{f(\vb{u}) - m} \ge t) \le \Pr(\abs{h(Z) - m} \ge t/2) + \Pr(\abs{\norm{Z} - \sqrt d} \ge s) with s=td/(2L)s = t\sqrt d/(2L). The first term is at most 2e−dt2/(8L2)2e^{-dt^2/(8L^2)}. If s≥2s \ge 2, since ∣E∥Z∥−d∣≤1\abs{\E\norm{Z} - \sqrt d} \le 1, the second is at most P(∣∥Z∥−E∥Z∥∣≥s/2)≤2e−s2/8=2e−dt2/(32L2)\Pr(\abs{\norm{Z} - \E\norm{Z}} \ge s/2) \le 2e^{-s^2/8} = 2e^{-dt^2/(32L^2)}, and the sum at most 4e−dt2/(32L2)4e^{-dt^2/(32L^2)}. If s<2s < 2, then dt2/(32L2)<1/2dt^2/(32L^2) < 1/2 and the bound exceeds 4e−1/2>14e^{-1/2} > 1: there is nothing to prove.

For the mean, ∣Ef(u)−m∣≤E∣f(u)−m∣=∫0∞P(∣f(u)−m∣≥t) ⁣dt≤∫0∞4e−dt2/(32L2) ⁣dt=8L2π/d\abs{\E f(\vb{u}) - m} \le \E\abs{f(\vb{u}) - m} = \int_0^\infty \Pr(\abs{f(\vb{u}) - m} \ge t)\dd t \le \int_0^\infty 4e^{-dt^2/(32L^2)}\dd t = 8L\sqrt{2\pi/d}.

∎

The constants of this proof are deliberately poor: the goal was to see that spherical concentration follows from Gaussian concentration. The optimal form, due to P. Lévy, follows from the isoperimetric inequality on the sphere (among sets of given area, caps have the smallest neighborhood) and gives an exponent of order dt2/(2L2)dt^2/(2L^2) around the median. Three examples reappear shortly:

  • f(u)=⟨u,v⟩f(\vb{u}) = \inner{\vb{u}}{\vb{v}} is 1-Lipschitz: near orthogonality again.
  • f(u)=max⁡iuif(\vb{u}) = \max_i u_i is 1-Lipschitz and concentrates near 2log⁡d/d\sqrt{2\log d/d}: no coordinate of a random direction is large.
  • f(u)=∥PEu∥f(\vb{u}) = \norm{\mat{P}_E\vb{u}}, with PE\mat{P}_E the orthogonal projection onto a fixed subspace EE of dimension kk, is 1-Lipschitz because projections do not stretch. Since E∥PEu∥2=k/d\E\norm{\mat{P}_E\vb{u}}^2 = k/d, the projection norm is k/d\sqrt{k/d} with fluctuations O(1/d)\bigO(1/\sqrt d), that is, relative error O(1/k)\bigO(1/\sqrt k). By invariance, projecting a fixed vector onto a randomly selected kk-dimensional subspace is the same. This was Johnson and Lindenstrauss’s original proof (1984).

All distances look alike

An uncomfortable consequence for nearest-neighbor search. If X,Y∼iidN(0,Id)X, Y \iid \Normal(\vb{0}, \mat{I}_d), then X−Y∼N(0,2Id)X - Y \sim \Normal(\vb{0}, 2\mat{I}_d) and ∥X−Y∥2=2χd2\norm{X - Y}^2 = 2\chi^2_d. By the norm concentration theorem and union bound over n2/2n^2/2 pairs of nn points, with probability at least 1−n2e−d(ε2/4−ε3/6)1 - n^2 e^{-d(\eps^2/4 - \eps^3/6)} all squared distances lie in 2d(1±ε)2d(1 \pm \eps). Taking ε\eps of order log⁡n/d\sqrt{\log n/d}, relative contrast between longest and shortest distance is

Dmax⁡−Dmin⁡Dmin⁡=O(log⁡nd)⟶0.\frac{D_{\max} - D_{\min}}{D_{\min}} = \bigO\Big(\sqrt{\frac{\log n}{d}}\Big) \longrightarrow 0.

For high-dimensional isotropic data, the nearest and farthest neighbors are almost equally distant, and small perturbations exchange them. Beyer, Goldstein, Ramakrishnan and Shaft formalized this in “When is “nearest neighbor” meaningful?” (1999). The way out is that real data are not isotropic: they have low intrinsic dimension, and that dimension matters, not ambient dimension. You will measure it in code with a Gaussian cloud, a cube and an intrinsically 3-dimensional set embedded in R5000\R^{5000}.

ε-nets: from one point to all

So far all bounds are pointwise: for a fixed vector x\vb{x}, something random behaves well with high probability. Many questions ask the same for all x\vb{x} at once. Operator norm ∥A∥2=sup⁡x∈Sd−1∥Ax∥\norm{\mat{A}}_2 = \sup_{\vb{x} \in S^{d-1}}\norm{\mat{A}\vb{x}} is the typical example. A union bound over infinitely many points does not work, but it does over a well-chosen finite discretization.

The proof is a volume argument with a maximal set of separated points; you will do it in the guided exercise. The essential feature is the form: the number of points needed is exponential in dd, so log⁡N=O(dlog⁡(1/ε))\log\mathcal{N} = \bigO(d\log(1/\eps)) and a union bound over the net costs a factor eO(d)e^{\bigO(d)}. If the pointwise bound is e−c kε2e^{-c\,k\eps^2}, k≳d/ε2k \gtrsim d/\eps^2 suffices to absorb it. The second ingredient says controlling the net is enough.

Proof

Let x∈Sd−1\vb{x} \in S^{d-1} with ∣x⊤Bx∣=∥B∥2\abs{\vb{x}\T\mat{B}\vb{x}} = \norm{\mat{B}}_2 (it exists by compactness; for a symmetric matrix the supremum of the quadratic form is the norm) and y∈N\vb{y} \in \mathcal{N} with ∥x−y∥≤ε\norm{\vb{x} - \vb{y}} \le \eps. Then

x⊤Bx−y⊤By=x⊤B(x−y)+(x−y)⊤By,\vb{x}\T\mat{B}\vb{x} - \vb{y}\T\mat{B}\vb{y} = \vb{x}\T\mat{B}(\vb{x} - \vb{y}) + (\vb{x} - \vb{y})\T\mat{B}\vb{y},

and each summand is bounded by ∥B∥2 ε\norm{\mat{B}}_2\,\eps. Thus ∥B∥2≤∣y⊤By∣+2ε∥B∥2\norm{\mat{B}}_2 \le \abs{\vb{y}\T\mat{B}\vb{y}} + 2\eps\norm{\mat{B}}_2, and rearranging suffices.

∎

Together these form the ε-net argument, a three-step recipe: a concentration bound for each fixed point, a union bound over a net of size eO(d)e^{\bigO(d)}, and an approximation lemma extending control from the net to the full set. Its first application is the infinite-set version of Johnson–Lindenstrauss.

Proof

Let U∈Rd×r\mat{U} \in \R^{d \times r} be an orthonormal basis of EE and B=1kU⊤G⊤GU−Ir\mat{B} = \tfrac1k\mat{U}\T\mat{G}\T\mat{G}\mat{U} - \mat{I}_r symmetric. The conclusion is equivalent to ∥B∥2≤ε\norm{\mat{B}}_2 \le \eps. Take an 1/41/4-net of Sr−1S^{r-1} with at most 9r9^r points. For each y\vb{y} of the net, GUy∼N(0,Ik)\mat{G}\mat{U}\vb{y} \sim \Normal(\vb{0}, \mat{I}_k) because ∥Uy∥=1\norm{\mat{U}\vb{y}} = 1, so y⊤By=∥GUy∥2/k−1\vb{y}\T\mat{B}\vb{y} = \norm{\mat{G}\mat{U}\vb{y}}^2/k - 1 is a χk2/k−1\chi^2_k/k - 1, and by the norm theorem P(∣y⊤By∣>ε/2)≤2e−k(ε2/16−ε3/48)≤2e−kε2/48\Pr(\abs{\vb{y}\T\mat{B}\vb{y}} > \eps/2) \le 2e^{-k(\eps^2/16 - \eps^3/48)} \le 2e^{-k\eps^2/48}. By the union bound, with probability at least 1−2⋅9re−kε2/48≥1−δ1 - 2\cdot 9^r e^{-k\eps^2/48} \ge 1 - \delta all net points satisfy ∣y⊤By∣≤ε/2\abs{\vb{y}\T\mat{B}\vb{y}} \le \eps/2, and the approximation lemma with ε=1/4\eps = 1/4 gives ∥B∥2≤2⋅ε/2=ε\norm{\mat{B}}_2 \le 2\cdot\eps/2 = \eps.

∎

The result does not depend on dd or the number of points of EE, which is infinite: only on dimension rr. It underlies least-squares sketching: if EE is the column space of [X  y][\mat{X}\;\vb{y}], solving min⁡w∥G(Xw−y)∥\min_{\vb{w}}\norm{\mat{G}(\mat{X}\vb{w} - \vb{y})} with k=O(r/ε2)k = \bigO(r/\eps^2) rows gives a nearly optimal solution to the original n≫kn \gg k-row problem. The argument’s constants are pessimistic, and in code you will see the worst vector in the subspace distorted on the order of 2r/k2\sqrt{r/k}: the extreme singular values of a rectangular Gaussian k×rk \times r lie at k±r\sqrt k \pm \sqrt r, the topic of lesson 24. The same net argument gives ∥G∥2≤C(k+d)\norm{\mat{G}}_2 \le C(\sqrt k + \sqrt d) with high probability.

The Johnson–Lindenstrauss lemma

Now the central result. You have nn points in Rd\R^d and want to represent them in Rk\R^k, with kk much smaller, so all pairwise distances change by at most a factor 1±ε1 \pm \eps. Remarkably kk depends only on nn and ε\eps, and a random matrix achieves this without inspecting the points.

This is the Johnson–Lindenstrauss lemma. Since ε2/4−ε3/6≥ε2/12\eps^2/4 - \eps^3/6 \ge \eps^2/12 in (0,1)(0, 1), k≥12(2log⁡n+log⁡(1/δ))/ε2k \ge 12(2\log n + \log(1/\delta))/\eps^2 suffices: the order is k=O(log⁡n/ε2)k = \bigO(\log n/\eps^2).

Proof

One fixed vector. For fixed x≠0\vb{x} \ne \vb{0}, coordinates of Gx\mat{G}\vb{x} are ⟨gr,x⟩\inner{\vb{g}_r}{\vb{x}} with gr\vb{g}_r row rr of G\mat{G}; they are independent and each is N(0,∥x∥2)\Normal(0, \norm{\vb{x}}^2) (a linear transformation of a Gaussian). Therefore ∥Gx∥2/∥x∥2∼χk2\norm{\mat{G}\vb{x}}^2/\norm{\vb{x}}^2 \sim \chi^2_k and, by the norm concentration theorem in dimension kk,

P(∣∥f(x)∥2∥x∥2−1∣>ε)≤2e−k(ε2/4−ε3/6).\Pr\Big(\Big|\frac{\norm{f(\vb{x})}^2}{\norm{\vb{x}}^2} - 1\Big| > \eps\Big) \le 2e^{-k(\eps^2/4 - \eps^3/6)}.

All pairs. ff is linear, so f(xi)−f(xj)=f(xi−xj)f(\vb{x}_i) - f(\vb{x}_j) = f(\vb{x}_i - \vb{x}_j), and it suffices to apply the above to each of the n(n−1)/2n(n-1)/2 difference vectors. By the union bound, probability that any pair fails is at most n(n−1)e−k(ε2/4−ε3/6)<n2e−k(ε2/4−ε3/6)n(n-1)e^{-k(\eps^2/4 - \eps^3/6)} < n^2 e^{-k(\eps^2/4 - \eps^3/6)}, which is at most δ\delta with the statement’s kk.

∎

Four observations before playing with it.

  1. dd does not appear. Projecting 10610^6 points from R105\R^{10^5} or R109\R^{10^9} with ε=0.1\eps = 0.1 and δ=0.01\delta = 0.01 asks for the same k=13 816k = 13\,816 rows. If dd is already smaller, the lemma is useless.
  2. The order is optimal. Larsen and Nelson (2017) proved that there are sets of nn points for which any map, linear or not, with distortion 1±ε1 \pm \eps needs k=Ω(log⁡n/ε2)k = \Omega(\log n/\eps^2) dimensions, provided ε\eps is not tiny (ε>min⁡(n,d)−0.4999\eps > \min(n, d)^{-0.4999}; below that, log⁡n/ε2\log n/\eps^2 already exceeds min⁡(n,d)\min(n, d) and there is nothing to reduce).
  3. Distances or squares. The statement controls squared distances. For distances, 1−ε≥1−ε\sqrt{1 - \eps} \ge 1 - \eps and 1+ε≤1+ε/2\sqrt{1 + \eps} \le 1 + \eps/2: distortion is even smaller.
  4. The union bound is pessimistic. The sklearn formula johnson_lindenstrauss_min_dim is k≥4log⁡n/(ε2/2−ε3/3)=2log⁡n/(ε2/4−ε3/6)k \ge 4\log n/(\eps^2/2 - \eps^3/3) = 2\log n/(\eps^2/4 - \eps^3/6): ours with log⁡(1/δ)=0\log(1/\delta) = 0. It is Dasgupta and Gupta’s (2003), whose success guarantee is only 1/n1/n. It works in practice because pairs do not all fail as much as the union assumes, and in the figure observed maximum distortion is well below the guarantee.
InteractiveRandom projections with guarantees
Distortion ρ\rho of 1 225 pairs with k=128k = 128
projecting…
  • simulated pairs
  • exact law with Gaussian R\mat{R}: χk2/k−1\chi^2_k/k - 1
  • target ±ε\pm\eps
Distortion versus kk (logarithmic scales)
  • observed maximum
  • observed median
  • theorem guarantee (δ=0.05\delta = 0.05)
  • sklearn formula
Random matrix R\mat{R}
Points
Number of points nn
Original dimension dd
128
0.20
Maximum distortion among 1 225 pairsprojecting…
Pairs with ∣ρ∣≤ε\abs{\rho} \le \eps…
Smallest tested kk with all pairs inside…
kk from the theorem (δ=0.05\delta = 0.05)1 249
sklearn kk (johnson_lindenstrauss_min_dim)903
Compression d/kd/k15.6×
nn points in Rd\R^d are projected with f(x)=Rx/kf(\vb{x}) = \mat{R}\vb{x}/\sqrt k and distortion ρ\rho is measured for each pair. Left: histogram of ρ\rho with exact law χk2/k−1\chi^2_k/k - 1 of the Gaussian matrix. Right, on log scales, maximum and median distortion versus kk, with theorem and sklearn guarantees. Move kk: everything falls as 1/k1/\sqrt k. Change dd from 2000 to 200 (the histogram does not change) and nn from 20 to 150 (the maximum rises little: log⁡n\sqrt{\log n}). Change the matrix to signs ±1\pm 1 or Achlioptas: equally good. Finally, choose the very sparse matrix with the canonical basis: distortion shoots up because a mostly-zero matrix barely sees a mostly-zero vector.

Sign matrices and sparse matrices

Multiplication by a dense Gaussian matrix costs O(kd)\bigO(kd) per vector and requires generating kdkd normals. Achlioptas (2003) observed that the proof uses only independent entries of mean 0 and variance 1 whose tails are no heavier than Gaussian. With equiprobable ±1\pm 1 entries, or 3⋅{+1,0,−1}\sqrt 3\cdot\{+1, 0, -1\} with probabilities 1/6,2/3,1/61/6, 2/3, 1/6, the same kk works, and the second has two-thirds zeros: projection is three times cheaper. In the guided exercise you will reconstruct the proof for arbitrary sub-Gaussian entries.

Why not push sparsity to the extreme? Li, Hastie and Church (2006) proposed s⋅{+1,0,−1}\sqrt s\cdot\{+1, 0, -1\} with probabilities 1/(2s),1−1/s,1/(2s)1/(2s), 1 - 1/s, 1/(2s) and s=ds = \sqrt d, the default used by sklearn SparseRandomProjection. The price shows up in variance. For a row r\vb{r} with independent entries of mean 0, variance 1 and fourth moment κ=Eri4\kappa = \E r_i^4,

E⟨r,x⟩4=κ∑ixi4+3∑i≠jxi2xj2⟹Var⁡⟨r,x⟩2=2∥x∥4+(κ−3)∑ixi4.\E\inner{\vb{r}}{\vb{x}}^4 = \kappa\sum_i x_i^4 + 3\sum_{i \ne j}x_i^2x_j^2 \quad\Longrightarrow\quad \Var\inner{\vb{r}}{\vb{x}}^2 = 2\norm{\vb{x}}^4 + (\kappa - 3)\sum_i x_i^4.

For the Gaussian κ=3\kappa = 3; for signs, κ=1\kappa = 1, and variance is even smaller; for Achlioptas, κ=3\kappa = 3 again. For the very sparse one, κ=s\kappa = s, and term (s−3)∑ixi4(s - 3)\sum_i x_i^4 is small only if the mass of x\vb{x} is spread across many coordinates. With x=ei−ej\vb{x} = \vb{e}_i - \vb{e}_j, ∑ixi4/∥x∥4=1/2\sum_i x_i^4/\norm{\vb{x}}^4 = 1/2 and variance per row is (2+(s−3)/2)∥x∥4=s+12∥x∥4\big(2 + (s - 3)/2\big)\norm{\vb{x}}^4 = \tfrac{s + 1}{2}\norm{\vb{x}}^4, or (s+1)/4(s + 1)/4 times the Gaussian: with d=2000d = 2000, about 11 times, and the distortion standard deviation about 3.43.4 times. This is exactly what the figure shows with the canonical basis. The fast Johnson–Lindenstrauss transform of Ailon and Chazelle (2006) solves the problem by first applying a Hadamard transform with random signs, spreading any vector’s mass across all coordinates, then a sparse projection: O(dlog⁡d)\bigO(d\log d) per vector.

Implementation from scratch

First, the soap bubble in numbers: norms of Gaussian vectors in dimensions from 1 to 10410^4, and the exact probability of falling below half the typical radius.

[ ]The soap bubble in numbersBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(0)

def normas(d, m=1000, bloque=100):
    """m muestras de ‖Z‖ con Z ~ N(0, I_d), por bloques para no llenar la memoria."""
    return np.concatenate([np.linalg.norm(rng.standard_normal((bloque, d)), axis=1) for _ in range(m // bloque)])

print(f"{'d':>6} {'media ‖Z‖/√d':>13} {'desv. ‖Z‖':>10} {'mín ‖Z‖/√d':>11} {'máx ‖Z‖/√d':>11} {'P(‖Z‖ ≤ √d/2)':>15}")
for d in [1, 10, 100, 1000, 10000]:
    r = normas(d)
    p = stats.chi2.cdf(d / 4, d)                      # exacta: ‖Z‖² ~ χ²_d
    print(f"{d:6d} {r.mean() / np.sqrt(d):13.4f} {r.std():10.3f} {r.min() / np.sqrt(d):11.3f} "
          f"{r.max() / np.sqrt(d):11.3f} {p:15.2e}")

d = 100
print(f"\nd = {d}: densidad en el origen / densidad a radio √d = e^(d/2) = {np.exp(d / 2):.2e}")
print(f"cota de Chernoff de P(‖Z‖² ≤ d/4): e^(-d(3/4)²/4) = {np.exp(-d * 0.75**2 / 4):.2e}")

The mean of ∥Z∥/d\norm{Z}/\sqrt d sticks to 1, the range between smallest and largest sample narrows as 1/d1/\sqrt d, and the standard deviation of ∥Z∥\norm{Z} stays close to 0.70.7 in all dimensions from 10 onward (between 0.680.68 and 0.700.70 with a thousand samples; the limit is 1/21/\sqrt 2). The last-line Chernoff bound 7.8×10−77.8\times 10^{-7} is valid but very loose compared to exact probability 1.1×10−151.1\times 10^{-15}: the theorem gives tail shape, not the best constant.

The best-known practical consequence appears in generative models with Gaussian latents (VAE, GAN, diffusion). Linear interpolation between two latents passes through atypical points.

[ ]Interpolating latents: linear versus sphericalBrowser
d = 512
z1, z2 = rng.standard_normal((2, d))

def slerp(a, b, s):
    """Interpolación esférica: recorre el arco entre a y b en lugar de la cuerda."""
    om = np.arccos(np.clip(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)), -1, 1))
    return (np.sin((1 - s) * om) * a + np.sin(s * om) * b) / np.sin(om)

print(f"√d = {np.sqrt(d):.2f}")
for s in [0, 0.25, 0.5, 0.75, 1]:
    lineal = (1 - s) * z1 + s * z2
    print(f"s = {s:4.2f}   ‖lineal‖ = {np.linalg.norm(lineal):6.2f}   ‖esférica‖ = {np.linalg.norm(slerp(z1, z2, s)):6.2f}")
medio = (z1 + z2) / 2
print(f"\nP(‖Z‖ ≤ ‖punto medio lineal‖) = {stats.chi2.cdf(medio @ medio, d):.1e}")

The linear midpoint has norm close to d/2=16\sqrt{d/2} = 16, and the probability that a true latent is so short is astronomically small: the decoder has never seen anything similar. Spherical interpolation preserves the typical norm (White, “Sampling generative networks”, 2016).

Now near orthogonality: cosine standard deviation multiplied by d\sqrt d, the largest cosine among 100 vectors and the frequency of ∣cos⁡∣≥0.1\abs{\cos} \ge 0.1 versus the exact law and theorem bound.

[ ]Near orthogonalityBrowser
from scipy import special

t, m = 0.1, 100
iu = np.triu_indices(m, 1)
print(f"{'d':>6} {'√d·desv(cos)':>13} {'máx |cos|':>10} {'frec. |cos|≥t':>14} {'exacta':>10} {'cota 3e^(-dt²/8)':>17}")
for d in [10, 100, 1000, 10000]:
    U = rng.standard_normal((m, d))
    U /= np.linalg.norm(U, axis=1, keepdims=True)
    c = (U @ U.T)[iu]
    exacta = special.betainc((d - 1) / 2, 0.5, 1 - t**2)   # P(|u1| ≥ t), u1² ~ Beta(1/2, (d-1)/2)
    print(f"{d:6d} {np.sqrt(d) * c.std():13.3f} {np.abs(c).max():10.3f} {np.mean(np.abs(c) >= t):14.4f} "
          f"{exacta:10.2e} {min(1, 3 * np.exp(-d * t**2 / 8)):17.2e}")

The cosine standard deviation is 1/d1/\sqrt d in every dimension, as E⟨u,v⟩2=1/d\E\inner{\vb{u}}{\vb{v}}^2 = 1/d predicts, and the exact beta law matches simulated frequencies. The theorem bound is valid but pessimistic: with 1/81/8 in the exponent instead of optimal 1/21/2, at d=104d = 10^4 it stays at 10−510^{-5} when exact probability is 10−2310^{-23}. In d=104d = 10^4, none of the 4950 pairs deviates from 90°90° by more than cosine 0.040.04.

Distances: relative contrast (Dmax⁡−Dmin⁡)/Dmin⁡(D_{\max} - D_{\min})/D_{\min} among pairs of 200 points, for a Gaussian cloud, cube [0,1]d[0, 1]^d and an intrinsically 3-dimensional set embedded in Rd\R^d with a little noise.

[ ]All distances look alikeBrowser
from scipy.spatial.distance import pdist

n = 200
def contraste(X):
    D = pdist(X)
    return (D.max() - D.min()) / D.min()

print(f"{'d':>6} {'gaussiana':>10} {'cubo':>8} {'intrínseca 3':>13}   {'√(log n / d)':>12}")
for d in [3, 10, 100, 1000, 5000]:
    latente = rng.standard_normal((n, 3))
    Q, _ = np.linalg.qr(rng.standard_normal((d, 3)))          # 3 direcciones ortonormales de R^d
    baja = latente @ Q.T + 0.01 * rng.standard_normal((n, d))
    print(f"{d:6d} {contraste(rng.standard_normal((n, d))):10.2f} {contraste(rng.random((n, d))):8.2f} "
          f"{contraste(baja):13.2f}   {np.sqrt(np.log(n) / d):12.3f}")

In the cloud and cube contrast falls with dd at rate log⁡n/d\sqrt{\log n/d}, up to a factor between 2 and 3 once dd exceeds a few hundred: in d=5000d = 5000 the longest distance exceeds the shortest by only 8%. The intrinsically 3-dimensional set keeps contrasts of tens up to d=1000d = 1000 because its distances are those of 200 points in R3\R^3. But it also falls with dd, for an instructive reason: noise of 0.010.01 per coordinate adds about 2⋅10−4d2\cdot 10^{-4}d to each squared distance, the same for all pairs, and in d=5000d = 5000 that is already comparable to shortest distances. Isotropic noise in many dimensions equalizes distances. Neighbor methods make sense insofar as data have low-dimensional structure dominating that noise.

Now Johnson–Lindenstrauss from scratch: theorem dimension, the four matrices and distortion of all pairs.

[ ]Johnson–Lindenstrauss from scratchBrowser
def jl_dimension(n, eps, delta):
    """k del teorema: (2 log n + log(1/δ)) / (ε²/4 − ε³/6)."""
    return int(np.ceil((2 * np.log(n) + np.log(1 / delta)) / (eps**2 / 4 - eps**3 / 6)))

def jl_eps(n, k, delta):
    """ε que garantiza el teorema con k filas (resuelve la ecuación anterior por bisección)."""
    objetivo, lo, hi = (2 * np.log(n) + np.log(1 / delta)) / k, 1e-6, 0.999
    if hi**2 / 4 - hi**3 / 6 < objetivo:
        return float("nan")
    for _ in range(60):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if mid**2 / 4 - mid**3 / 6 < objetivo else (lo, mid)
    return hi

def matriz(tipo, k, d, rng):
    if tipo == "gaussiana":
        return rng.standard_normal((k, d))
    if tipo == "signos":
        return rng.choice([-1.0, 1.0], size=(k, d))
    if tipo == "achlioptas":                                    # √3·{+1, 0, −1} con prob. 1/6, 2/3, 1/6
        return np.sqrt(3) * rng.choice([-1.0, 0.0, 1.0], size=(k, d), p=[1 / 6, 2 / 3, 1 / 6])
    s = np.sqrt(d)                                              # muy dispersa: s = √d (Li, Hastie y Church)
    return np.sqrt(s) * rng.choice([-1.0, 0.0, 1.0], size=(k, d), p=[1 / (2 * s), 1 - 1 / s, 1 / (2 * s)])

def distorsion(X, Y):
    """ρ = ‖f(xᵢ) − f(xⱼ)‖² / ‖xᵢ − xⱼ‖² − 1 para todos los pares."""
    return pdist(Y, "sqeuclidean") / pdist(X, "sqeuclidean") - 1

n, d, delta = 100, 500, 0.05
conjuntos = {"nube gaussiana": rng.standard_normal((n, d)), "base canónica": np.eye(n, d)}
ks = [50, 200, 800]
print("ε garantizado (δ = 0.05):", "   ".join(f"k = {k}: {jl_eps(n, k, delta):.3f}" for k in ks))
for nombre, X in conjuntos.items():
    print(f"\n{nombre}: distorsión máxima entre los {n * (n - 1) // 2} pares")
    for tipo in ["gaussiana", "signos", "achlioptas", "muy dispersa"]:
        fila = []
        for k in ks:
            R = matriz(tipo, k, d, rng)
            fila.append(np.abs(distorsion(X, X @ R.T / np.sqrt(k))).max())
        print(f"  {tipo:13s}" + "".join(f"   k = {k:3d}: {v:.3f}" for k, v in zip(ks, fila)))
print("\nk para n = 1000, ε = 0.2, δ = 0.01:", jl_dimension(1000, 0.2, 0.01))

With the Gaussian cloud all four matrices behave alike, and observed maximum distortion remains well below the guarantee: 0.370.37 versus 0.660.66 with k=200k = 200 and 0.190.19 versus 0.270.27 with k=800k = 800 (with k=50k = 50 the theorem guarantees no ε<1\eps < 1). With the canonical basis, Gaussian and Achlioptas behave as before, signs somewhat better because of their κ=1\kappa = 1, and the very sparse matrix with s=500≈22s = \sqrt{500} \approx 22 doubles or triples distortion.

Finally, the ε-net argument in both directions: a greedily constructed net on the sphere of R3\R^3 versus the volume bound, and exact distortion of the worst vector in a subspace, read from singular values of GU/k\mat{G}\mat{U}/\sqrt k.

[ ]ε-nets and subspacesBrowser
def red_voraz(P, eps):
    """Recorre los puntos y toma como centro cada uno que aún no esté cubierto."""
    centros, cubierto = [], np.zeros(len(P), dtype=bool)
    for i in range(len(P)):
        if not cubierto[i]:
            centros.append(i)
            cubierto |= np.linalg.norm(P - P[i], axis=1) <= eps
    return P[centros]

P = rng.standard_normal((20000, 3))
P /= np.linalg.norm(P, axis=1, keepdims=True)
for eps in [0.5, 0.25, 0.1]:
    N = red_voraz(P, eps)
    print(f"ε = {eps:4.2f}: red voraz con {len(N):5d} puntos   cota (1 + 2/ε)^3 = {(1 + 2 / eps)**3:7.0f}")

d, r = 2000, 10
U, _ = np.linalg.qr(rng.standard_normal((d, r)))                  # base ortonormal de un subespacio E
print(f"\nsubespacio de dimensión r = {r} en R^{d}: distorsión del peor vector de E")
for k in [50, 200, 800]:
    G = rng.standard_normal((k, d))
    s = np.linalg.svd(G @ U / np.sqrt(k), compute_uv=False)
    peor = max(s.max()**2 - 1, 1 - s.min()**2)
    print(f"  k = {k:4d}: {peor:.3f}   2√(r/k) + r/k = {2 * np.sqrt(r / k) + r / k:.3f}")

The greedy net is several times smaller than bound (1+2/ε)3(1 + 2/\eps)^3, which aims only to capture order ε−d\eps^{-d}. In the subspace, the supremum over infinitely many vectors is calculated exactly because sup⁡x∈E, ∥x∥=1∥Gx∥2/k\sup_{\vb{x} \in E,\,\norm{\vb{x}} = 1}\norm{\mat{G}\vb{x}}^2/k is the square of the largest singular value of GU/k\mat{G}\mat{U}/\sqrt k. It is order 2r/k+r/k2\sqrt{r/k} + r/k, as given by extreme singular values ≈1±r/k\approx 1 \pm \sqrt{r/k} (with fluctuations on both sides: k±r\sqrt k \pm \sqrt r is only the scale of extreme singular values, not their exact value), far from kk required by the proof: with ε=0.4\eps = 0.4 and δ=0.05\delta = 0.05, the bound asks for k≈7700k \approx 7700, while with k=200k = 200 the worst vector is already around 0.40.4 and with k=800k = 800 falls to 0.180.18.

The professional version

ToolWhat it doesDetail
sklearn.random_projection.johnson_lindenstrauss_min_dim(n, eps=0.1)4log⁡n/(ε2/2−ε3/3)4\log n/(\eps^2/2 - \eps^3/3)Dasgupta and Gupta bound, without δ\delta
GaussianRandomProjection(n_components)R\mat{R} with entries N(0,1/k)\Normal(0, 1/k)'auto' uses the preceding formula with eps=0.1
SparseRandomProjection(n_components, density='auto')entries ±s/k\pm\sqrt{s/k} with probability 1/(2s)1/(2s) each'auto' takes density 1/s=1/d1/s = 1/\sqrt d (Li et al.)
torch.randn(k, d) / k**0.5Gaussian on GPU for projecting batches
scipy.linalg.clarkson_woodruff_transform(A, k)sketch with a single ±1\pm 1 per columnleast-squares sketching
[ ]sklearn.random_projectionBrowser
from sklearn.random_projection import johnson_lindenstrauss_min_dim, GaussianRandomProjection, SparseRandomProjection

print("n           sklearn (ε = 0.1, 0.2, 0.5)         lección con δ = 0.01")
for n in [100, 10_000, 1_000_000]:
    sk = [int(johnson_lindenstrauss_min_dim(n, eps=e)) for e in (0.1, 0.2, 0.5)]
    nuestra = [jl_dimension(n, e, 0.01) for e in (0.1, 0.2, 0.5)]
    print(f"{n:<10d}  {str(sk):34s} {nuestra}")

X = rng.standard_normal((100, 2000))
for proy in [GaussianRandomProjection(n_components=300, random_state=0), SparseRandomProjection(n_components=300, random_state=0)]:
    Y = np.asarray(proy.fit_transform(X))
    dens = getattr(proy, "density_", 1.0)
    print(f"{type(proy).__name__:26s} forma {Y.shape}, densidad {dens:.4f}, máx |ρ| = {np.abs(distorsion(X, Y)).max():.3f}")

The sklearn formula matches ours when term log⁡(1/δ)\log(1/\delta) is removed, as explained above, and SparseRandomProjection chooses density 1/2000≈0.0221/\sqrt{2000} \approx 0.022: 98% of its matrix is zero. On the dense Gaussian cloud, both projections have similar distortion (0.280.28 and 0.330.33 with k=300k = 300).

Near orthogonality in real embeddings

Do model embeddings behave like random vectors? The next cell encodes 40 unrelated sentences using multilingual-e5-small (384 dimensions, fixed revision) and compares their cosines with 40 random vectors. It needs transformers and the model, downloaded from Hugging Face on first use. It deliberately runs on CPU: 40 short sentences encode in a couple of seconds and there is no need to occupy the GPU.

[ ]Real embeddings versus random vectorsLocal GPU
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModel

torch.set_num_threads(4)
MODEL, REV = "intfloat/multilingual-e5-small", "614241f622f53c4eeff9890bdc4f31cfecc418b3"
tok = AutoTokenizer.from_pretrained(MODEL, revision=REV)
model = AutoModel.from_pretrained(MODEL, revision=REV).eval()      # CPU

textos = [
    "El volcán entró en erupción durante la noche y obligó a evacuar dos pueblos.",
    "La receta pide cien gramos de harina, dos huevos y una pizca de sal.",
    "El Real Madrid ganó la final en la prórroga con un gol de cabeza.",
    "La inflación interanual bajó tres décimas en septiembre.",
    "Los pulpos tienen tres corazones y sangre azul.",
    "El compilador avisa de una variable que nunca se usa.",
    "Mañana lloverá en el norte y habrá nieve por encima de mil metros.",
    "La sonata se toca en re menor y dura unos veinte minutos.",
    "El paciente presenta fiebre alta y dolor articular desde hace tres días.",
    "La catedral gótica tardó más de dos siglos en terminarse.",
    "Para cambiar la rueda, afloja primero los tornillos con el coche en el suelo.",
    "El satélite completó su órbita número diez mil.",
    "La novela narra la vida de una familia de pescadores en Galicia.",
    "El tipo de interés del préstamo hipotecario es variable.",
    "Las abejas se comunican la posición de las flores bailando.",
    "El ajedrecista sacrificó la dama en la jugada veintidós.",
    "Riega los tomates por la mañana temprano en verano.",
    "La ley entrará en vigor el primero de enero.",
    "El telescopio detectó una galaxia a trece mil millones de años luz.",
    "Esta camiseta de algodón se encoge si la lavas con agua caliente.",
    "El tren de alta velocidad une las dos ciudades en dos horas y media.",
    "La teoría de cuerdas propone dimensiones adicionales compactificadas.",
    "El gato duerme unas quince horas al día.",
    "Se recomienda cambiar la contraseña cada pocos meses.",
    "El río se desbordó tras las lluvias torrenciales.",
    "La pintura al óleo tarda semanas en secarse por completo.",
    "La bolsa abrió con caídas generalizadas en el sector bancario.",
    "Los dinosaurios se extinguieron hace unos sesenta y seis millones de años.",
    "El concierto se aplazó por la tormenta.",
    "La fotosíntesis convierte la luz en energía química.",
    "El alcalde inauguró la nueva biblioteca municipal.",
    "Ese restaurante sirve el mejor arroz negro de la costa.",
    "La vacuna se administra en dos dosis separadas por tres semanas.",
    "El equipo de baloncesto fichó a un base lituano.",
    "La impresora no responde porque se ha quedado sin tóner.",
    "Los glaciares de los Pirineos han perdido la mitad de su superficie.",
    "El examen de matemáticas incluye integrales y series.",
    "El vuelo a Lima salió con cuatro horas de retraso.",
    "La seda se obtiene del capullo del gusano.",
    "El museo exhibe una colección de relojes del siglo dieciocho.",
]
with torch.no_grad():
    b = tok(["passage: " + t for t in textos], padding=True, truncation=True, return_tensors="pt")
    h = model(**b).last_hidden_state
    m = b["attention_mask"].unsqueeze(-1).float()
    E = ((h * m).sum(1) / m.sum(1)).numpy().astype(np.float64)    # media sobre los tokens, como pide e5

n, d = E.shape
E /= np.linalg.norm(E, axis=1, keepdims=True)
iu = np.triu_indices(n, 1)

def resumen(nombre, V):
    c = (V @ V.T)[iu]
    print(f"{nombre:22s} media {c.mean():+.3f}   desv. típ. {c.std():.3f}   mín {c.min():+.3f}   máx {c.max():+.3f}")
    return c

print(f"{n} frases, d = {d}, 1/√d = {1 / np.sqrt(d):.3f}")
resumen("embeddings e5", E)
G = np.random.default_rng(0).standard_normal((n, d))
resumen("vectores al azar", G / np.linalg.norm(G, axis=1, keepdims=True))
mu = E.mean(axis=0)
print(f"norma de la media: {np.linalg.norm(mu):.3f}   (con vectores al azar sería ~{1 / np.sqrt(n):.3f})")
C = (E - mu) / np.linalg.norm(E - mu, axis=1, keepdims=True)
c = resumen("embeddings centrados", C)
i, j = iu[0][c.argmax()], iu[1][c.argmax()]
print(f"par más parecido tras centrar:\n  {textos[i]}\n  {textos[j]}")
lam = np.linalg.svd(E - mu, compute_uv=False) ** 2
print(f"varianza en la 1.ª componente principal: {lam[0] / lam.sum():.1%}   "
      f"dimensión efectiva (cociente de participación): {lam.sum()**2 / (lam**2).sum():.1f} de {n - 1}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The result refutes naive intuition. Unrelated sentences have mean cosine 0.820.82, not 00: e5 embeddings occupy a narrow cone around a common direction (the mean of 40 vectors has norm 0.910.91, versus about 0.160.16 for 40 random vectors). This anisotropy is common in language models and explains why a “high” cosine means nothing without a reference. After subtracting the mean, cosines center on −1/(n−1)≈−0.026-1/(n-1) \approx -0.026 (centered vectors sum to zero), but their spread is nearly twice that of random vectors of the same dimension, and the closest pair is the expected one: the river flooded by rain and the concert postponed by the storm, the only two sentences about bad weather. That extra spread is the nonrandom part: semantics. Participation ratio, around 30 out of a maximum 39, says these 40 unrelated sentences occupy almost every direction they can occupy.

Common mistakes

Exercises

NumericThe shell of the ball in ℝ¹⁰⁰
What fraction of the volume of the unit ball in R100\R^{100} is at distance less than 0.050.05 from the boundary?
QuizThe size of the inner product
Let u,v\vb{u}, \vb{v} be independent unit vectors uniform on Sd−1S^{d-1}. What is the typical order of ∣⟨u,v⟩∣\abs{\inner{\vb{u}}{\vb{v}}} when dd is large?
NumericNorm fluctuations
Let Z∼N(0,I1000)Z \sim \Normal(\vb{0}, \mat{I}_{1000}). Approximately what is the standard deviation of ∥Z∥\norm{Z}?
QuizThe midpoint of two latents
Let z1,z2∼iidN(0,I512)\vb{z}_1, \vb{z}_2 \iid \Normal(\vb{0}, \mat{I}_{512}). Approximately what is ∥(z1+z2)/2∥\norm{(\vb{z}_1 + \vb{z}_2)/2}?
NumericDimension for ten thousand points
Using the lesson bound, k≥(2log⁡n+log⁡(1/δ))/(ε2/4−ε3/6)k \ge (2\log n + \log(1/\delta))/(\eps^2/4 - \eps^3/6), what is the smallest integer kk guaranteeing distortion ε=0.2\eps = 0.2 in squared distances of n=104n = 10^4 points with probability at least 0.990.99?
NumericThe ball inside the cube
What fraction of cube [−1,1]10[-1, 1]^{10} is occupied by the unit ball of R10\R^{10}?
QuizWhat Johnson–Lindenstrauss says and does not say
Let f(x)=Gx/kf(\vb{x}) = \mat{G}\vb{x}/\sqrt k with Gaussian G\mat{G} k×dk\times d, k<dk < d, and kk as in the theorem. Which statements are true?

More than one answer may be correct.

ProofSphere nets by volume
Prove: For every ε∈(0,1]\eps \in (0, 1], sphere Sd−1S^{d-1} admits an ε-net with at most (1+2/ε)d(1 + 2/\eps)^d points.
0
Call a set of points in Sd−1S^{d-1} separated (at distance ε) if all pairwise distances exceed ε\eps.

Step 1 of 4. Which set do you take as a candidate net?

ProofJohnson–Lindenstrauss with sub-Gaussian entries
Prove: Let R∈Rk×d\mat{R} \in \R^{k\times d} have independent entries with mean 0, variance 1 and sub-Gaussian norm ∥rij∥ψ2≤K\norm{r_{ij}}_{\psi_2} \le K (for example signs ±1\pm 1). There exists a constant c>0c > 0 depending only on KK such that, if k≥(2log⁡n+log⁡(1/δ))/(c ε2)k \ge (2\log n + \log(1/\delta))/(c\,\eps^2), map f(x)=Rx/kf(\vb{x}) = \mat{R}\vb{x}/\sqrt k preserves squared distances of nn fixed points with distortion ε∈(0,1)\eps \in (0, 1) and probability at least 1−δ1 - \delta.
0
Write r1,…,rk\vb{r}_1, \dots, \vb{r}_k for the rows of R\mat{R}.

Step 1 of 4. What does the problem reduce to?

CodeA projection with guarantee
Implement jl_dimension(n, eps, delta=0.01), returning the smallest integer k≥(2log⁡n+log⁡(1/δ))/(ε2/4−ε3/6)k \ge (2\log n + \log(1/\delta))/(\eps^2/4 - \eps^3/6), and jl_project(X, eps, delta=0.01, seed=0), projecting rows of X (n×dn\times d) to kk = jl_dimension(n, eps, delta) dimensions with an appropriate random matrix and correct scaling, using np.random.default_rng(seed). Tests measure squared-distance distortion on adversarial sets: canonical basis vectors, very tight clusters and aligned points. The starter code selects random coordinates: check it against the canonical basis.
import numpy as np

def jl_dimension(n, eps, delta=0.01):
  """Filas k que garantizan distorsión eps en los n(n-1)/2 pares con probabilidad >= 1 - delta."""
  # tu código: la cota de la lección
  return int(np.ceil(1 / eps**2))

def jl_project(X, eps, delta=0.01, seed=0):
  """Proyecta las filas de X (n x d) a k = jl_dimension(n, eps, delta) dimensiones."""
  X = np.asarray(X, dtype=float)
  n, d = X.shape
  k = jl_dimension(n, eps, delta)
  rng = np.random.default_rng(seed)
  # tu código: una matriz aleatoria adecuada y la escala correcta
  idx = rng.choice(d, size=min(k, d), replace=False)
  return X[:, idx] * np.sqrt(d / len(idx))
Shift+Enter to run

Summary

Key idea
In high dimension, a Lipschitz function of many independent variables is almost constant: a Gaussian norm is d±O(1)\sqrt d \pm \bigO(1), two random directions are orthogonal up to O(1/d)\bigO(1/\sqrt d), and ball volume lives in the shell and near every equator. A union bound turns concentration into guarantees for nn points (Johnson–Lindenstrauss, k=O(log⁡n/ε2)k = \bigO(\log n/\eps^2)), and an ε-net does so for infinite sets of dimension rr (k=O(r/ε2)k = \bigO(r/\eps^2)).
  • ∥Z∥2/d\norm{Z}^2/d with Z∼N(0,Id)Z \sim \Normal(\vb{0}, \mat{I}_d) deviates from 1 by ε\eps with probability e−Ω(dε2)e^{-\Omega(d\eps^2)} (Chernoff with χ2\chi^2, or subexponential Bernstein), and ∥Z∥−d\norm{Z} - \sqrt d has sub-Gaussian tails of size O(1)\bigO(1). The mode (origin) is not typical.
  • ⟨u,v⟩\inner{\vb{u}}{\vb{v}} for random directions has variance 1/d1/d and tails e−Ω(dt2)e^{-\Omega(dt^2)}; by the probabilistic method eΩ(dt2)e^{\Omega(dt^2)} directions with ∣cos⁡∣<t\abs{\cos} < t fit.
  • Vd=πd/2/Γ(d/2+1)→0V_d = \pi^{d/2}/\Gamma(d/2 + 1) \to 0; the shell of thickness ε\eps has fraction 1−(1−ε)d1 - (1 - \eps)^d of volume, and band ∣x1∣≤t\abs{x_1} \le t at least 1−2e−dt2/21 - 2e^{-dt^2/2}.
  • Every LL-Lipschitz function on Sd−1S^{d-1} concentrates with fluctuations O(L/d)\bigO(L/\sqrt d); this follows from Gaussian concentration by writing u=Z/∥Z∥\vb{u} = Z/\norm{Z}.
  • The sphere has ε-nets of size (1+2/ε)d(1 + 2/\eps)^d; pointwise concentration, union over the net and approximation give uniform bounds such as subspace embedding.
  • Johnson–Lindenstrauss: k≥(2log⁡n+log⁡(1/δ))/(ε2/4−ε3/6)k \ge (2\log n + \log(1/\delta))/(\eps^2/4 - \eps^3/6) Gaussian, sign or Achlioptas rows preserve n2/2n^2/2 distances; kk does not depend on dd and order log⁡n/ε2\log n/\eps^2 is optimal. Very sparse matrices fail on sparse data.
  • In isotropic data all distances look alike; real embeddings are anisotropic and of lower intrinsic dimension: always compare with a random reference.