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
- 04Sub-exponential random variablesBernstein's inequalitySub-Gaussian random variablesGaussian concentration for Lipschitz functionsUnion boundMultivariate Gaussian distributionRotational invariance of the standard GaussianAffine transformations of GaussiansLebesgue measureExponential, gamma and chi-squared distributions
- 02Vector normDot product
Motivation: a thousand dimensions are not three
A small embedding model converts each sentence into a vector of ; a large one into one of . Transformer layers live in or , 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 with large , the geometry of random objects is almost deterministic:
- A Gaussian vector has norm 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 .
- 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 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 .
The Gaussian is a soap bubble
Start with the simplest calculation. If has components , its squared norm is a sum of independent variables with mean 1 and variance :
Thus . So far, the law of large numbers. What is striking is its geometric meaning: density is maximal at the origin, yet almost no sample falls near it. All mass is in a thin shell of radius .
The explanation is in the blue curve. The probability that falls in is the density at that radius times the area of the sphere of radius , proportional to . Factor grows rapidly and falls rapidly; their product peaks at , the mode of law , with width of order 1.
This is norm concentration: deviates from by a fraction with probability exponentially small in , and deviates from by with sub-Gaussian probability in , with no factor : fluctuations are .
Proof
First part (Chernoff). has law , the gamma distribution with shape and scale 2, with moment-generating function for . By the Chernoff method, for ,
The minimum is at , where , and equals . Since , we have and obtain the first bound. For the lower tail use : with the same calculation gives , and gives .
Second part (Lipschitz). The norm is 1-Lipschitz: by the triangle inequality. Gaussian concentration of Lipschitz functions directly gives . It remains to locate . By Jensen, . For the lower bound, integrating the density of gives , and hence
With this becomes , and since at , .
∎The first part also follows from general theory: each is subexponential, and Bernstein’s inequality for their sum gives with an absolute constant . This form generalizes to non-Gaussian inputs; direct calculation with gives explicit constants, which we use in Johnson–Lindenstrauss. The second part refines fluctuation size: by the delta method, implies , and therefore the standard deviation in the figure tends to .
The mode that is not typical
The figure’s paradox can be quantified. With , density at the origin is times density at a point of norm , yet . There is no contradiction: the ball of radius 5 has tiny volume compared with the shell of radius 10, because volume scales as and .
The useful interpretation comes from information theory. concentrates around its mean, the differential entropy: almost all mass lies in a typical set where density is approximately , 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 and is orthogonal, has the same law as (the rotational invariance), so has a rotation-invariant law on sphere . That law is the uniform measure on the sphere, the unique probability on with that invariance.
What inner product do and a fixed unit vector have? By invariance, the same as and , namely coordinate . By symmetry, and all are equal; since they sum to ,
The typical inner product of two random directions is order : in , a cosine of , an angle of . The exact law is also accessible: with independent of , a ratio of independent gammas, so by the relationship between gamma and beta. Changing variable, has density proportional to on , and angle has density proportional to . For the angle is uniform; for large , is a very narrow bell centered at .
This is the near orthogonality of random vectors in high dimension: a deviation of with fixed cosine is exponentially unlikely in .
Proof
By invariance it suffices that , and with the event is . Either or :
The first bound is Gaussian tail (Chernoff), and the second is the previous theorem’s lower tail with . Since , and the sum is at most . If is also random and independent, condition on and apply the above.
∎Constant in the exponent is not optimal: the exact beta law gives in each tail (K. Ball, An elementary introduction to modern convex geometry, 1997, lemma 2.2), the tail of a . What matters is the form .
Exponentially many nearly orthogonal directions
Exactly orthogonal vectors fit in . Relax “orthogonal” to “with pairwise” and exponentially many fit. The argument is the probabilistic method: choose independent uniform vectors and apply the union bound to the pairs,
If failure probability is less than 1, some configuration does not fail: nearly orthogonal vectors exist. With the exact cosine law instead of the bound, the numbers are concrete. With , the guarantee exceeds the orthogonal ones from , and at , BERT base width, at least about 9500 vectors fit with pairwise: more than twelve times . 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.
The converse also holds: no more than exponentially many fit. If , then , so vectors are separated by at least , and the ε-net section’s volume argument gives . The number of nearly orthogonal directions is for each fixed .
High-dimensional volume: orange peel
Move from the Gaussian to unit ball with Lebesgue measure. Its volume has a closed formula obtained by calculating in two ways. As a product of one-dimensional integrals it equals . In polar coordinates the area of a sphere of radius is (the derivative of volume ), and the integral is . Equating them,
It increases until and then collapses: and . Compared with enclosing cube of volume , the inscribed ball is a negligible fraction: almost all cube volume lies in corners, up to distance from the center.
Two calculations describe where the ball’s volume lies, both using only that Lebesgue measure scales as .
The shell. The fraction of volume at distance less than from the boundary is
With and , of the volume is in the last hundredth of the radius.
The equator. For any unit direction , the fraction of volume with is at most . The proof fits in one line: if and , then , so that region lies inside a ball of radius , whose volume is .
These two facts are what we call high-dimensional volume: in the ball of , almost all volume is simultaneously near the surface and in band of any equator. There is no contradiction with many equators: for two directions , bands almost completely overlap because almost every point is nearly orthogonal to both.
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 is a special case of a function of 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 are of order , although may vary over a range of size on the sphere.
Proof
The idea is to write and compare with , a Lipschitz function of a Gaussian.
- Extension. extends to all of with the same constant (McShane extension): it is an infimum of -Lipschitz functions, and on equals because .
- Gaussian. is -Lipschitz. With and , Gaussian concentration gives .
- Comparison. With , .
- Union. with . The first term is at most . If , since , the second is at most , and the sum at most . If , then and the bound exceeds : there is nothing to prove.
For the mean, .
∎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 around the median. Three examples reappear shortly:
- is 1-Lipschitz: near orthogonality again.
- is 1-Lipschitz and concentrates near : no coordinate of a random direction is large.
- , with the orthogonal projection onto a fixed subspace of dimension , is 1-Lipschitz because projections do not stretch. Since , the projection norm is with fluctuations , that is, relative error . By invariance, projecting a fixed vector onto a randomly selected -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 , then and . By the norm concentration theorem and union bound over pairs of points, with probability at least all squared distances lie in . Taking of order , relative contrast between longest and shortest distance is
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 .
ε-nets: from one point to all
So far all bounds are pointwise: for a fixed vector , something random behaves well with high probability. Many questions ask the same for all at once. Operator norm 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 , so and a union bound over the net costs a factor . If the pointwise bound is , suffices to absorb it. The second ingredient says controlling the net is enough.
Proof
Let with (it exists by compactness; for a symmetric matrix the supremum of the quadratic form is the norm) and with . Then
and each summand is bounded by . Thus , 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 , 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 be an orthonormal basis of and symmetric. The conclusion is equivalent to . Take an -net of with at most points. For each of the net, because , so is a , and by the norm theorem . By the union bound, with probability at least all net points satisfy , and the approximation lemma with gives .
∎The result does not depend on or the number of points of , which is infinite: only on dimension . It underlies least-squares sketching: if is the column space of , solving with rows gives a nearly optimal solution to the original -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 : the extreme singular values of a rectangular Gaussian lie at , the topic of lesson 24. The same net argument gives with high probability.
The Johnson–Lindenstrauss lemma
Now the central result. You have points in and want to represent them in , with much smaller, so all pairwise distances change by at most a factor . Remarkably depends only on and , and a random matrix achieves this without inspecting the points.
This is the Johnson–Lindenstrauss lemma. Since in , suffices: the order is .
Proof
One fixed vector. For fixed , coordinates of are with row of ; they are independent and each is (a linear transformation of a Gaussian). Therefore and, by the norm concentration theorem in dimension ,
All pairs. is linear, so , and it suffices to apply the above to each of the difference vectors. By the union bound, probability that any pair fails is at most , which is at most with the statement’s .
∎Four observations before playing with it.
- does not appear. Projecting points from or with and asks for the same rows. If is already smaller, the lemma is useless.
- The order is optimal. Larsen and Nelson (2017) proved that there are sets of points for which any map, linear or not, with distortion needs dimensions, provided is not tiny (; below that, already exceeds and there is nothing to reduce).
- Distances or squares. The statement controls squared distances. For distances, and : distortion is even smaller.
- The union bound is pessimistic. The
sklearnformulajohnson_lindenstrauss_min_dimis : ours with . It is Dasgupta and Gupta’s (2003), whose success guarantee is only . 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.
Sign matrices and sparse matrices
Multiplication by a dense Gaussian matrix costs per vector and requires generating 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 entries, or with probabilities , the same 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 with probabilities and , the default used by sklearn SparseRandomProjection. The price shows up in variance. For a row with independent entries of mean 0, variance 1 and fourth moment ,
For the Gaussian ; for signs, , and variance is even smaller; for Achlioptas, again. For the very sparse one, , and term is small only if the mass of is spread across many coordinates. With , and variance per row is , or times the Gaussian: with , about 11 times, and the distortion standard deviation about 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: per vector.
Implementation from scratch
First, the soap bubble in numbers: norms of Gaussian vectors in dimensions from 1 to , and the exact probability of falling below half the typical radius.
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 sticks to 1, the range between smallest and largest sample narrows as , and the standard deviation of stays close to in all dimensions from 10 onward (between and with a thousand samples; the limit is ). The last-line Chernoff bound is valid but very loose compared to exact probability : 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.
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 , 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 , the largest cosine among 100 vectors and the frequency of versus the exact law and theorem bound.
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 in every dimension, as predicts, and the exact beta law matches simulated frequencies. The theorem bound is valid but pessimistic: with in the exponent instead of optimal , at it stays at when exact probability is . In , none of the 4950 pairs deviates from by more than cosine .
Distances: relative contrast among pairs of 200 points, for a Gaussian cloud, cube and an intrinsically 3-dimensional set embedded in with a little noise.
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 at rate , up to a factor between 2 and 3 once exceeds a few hundred: in the longest distance exceeds the shortest by only 8%. The intrinsically 3-dimensional set keeps contrasts of tens up to because its distances are those of 200 points in . But it also falls with , for an instructive reason: noise of per coordinate adds about to each squared distance, the same for all pairs, and in 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.
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: versus with and versus with (with the theorem guarantees no ). With the canonical basis, Gaussian and Achlioptas behave as before, signs somewhat better because of their , and the very sparse matrix with doubles or triples distortion.
Finally, the ε-net argument in both directions: a greedily constructed net on the sphere of versus the volume bound, and exact distortion of the worst vector in a subspace, read from singular values of .
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 , which aims only to capture order . In the subspace, the supremum over infinitely many vectors is calculated exactly because is the square of the largest singular value of . It is order , as given by extreme singular values (with fluctuations on both sides: is only the scale of extreme singular values, not their exact value), far from required by the proof: with and , the bound asks for , while with the worst vector is already around and with falls to .
The professional version
| Tool | What it does | Detail |
|---|---|---|
sklearn.random_projection.johnson_lindenstrauss_min_dim(n, eps=0.1) | Dasgupta and Gupta bound, without | |
GaussianRandomProjection(n_components) | with entries | 'auto' uses the preceding formula with eps=0.1 |
SparseRandomProjection(n_components, density='auto') | entries with probability each | 'auto' takes density (Li et al.) |
torch.randn(k, d) / k**0.5 | Gaussian on GPU for projecting batches | |
scipy.linalg.clarkson_woodruff_transform(A, k) | sketch with a single per column | least-squares sketching |
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 is removed, as explained above, and SparseRandomProjection chooses density : 98% of its matrix is zero. On the dense Gaussian cloud, both projections have similar distortion ( and with ).
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.
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}")npm run lab and open the connection link.The result refutes naive intuition. Unrelated sentences have mean cosine , not : e5 embeddings occupy a narrow cone around a common direction (the mean of 40 vectors has norm , versus about 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 (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
More than one answer may be correct.
Step 1 of 4. Which set do you take as a candidate net?
Step 1 of 4. What does the problem reduce to?
jl_dimension(n, eps, delta=0.01), returning the smallest integer , and jl_project(X, eps, delta=0.01, seed=0), projecting rows of X () to = 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))Summary
- with deviates from 1 by with probability (Chernoff with , or subexponential Bernstein), and has sub-Gaussian tails of size . The mode (origin) is not typical.
- for random directions has variance and tails ; by the probabilistic method directions with fit.
- ; the shell of thickness has fraction of volume, and band at least .
- Every -Lipschitz function on concentrates with fluctuations ; this follows from Gaussian concentration by writing .
- The sphere has ε-nets of size ; pointwise concentration, union over the net and approximation give uniform bounds such as subspace embedding.
- Johnson–Lindenstrauss: Gaussian, sign or Achlioptas rows preserve distances; does not depend on and order 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.