Random Projections: The Distortion Is a Sum of Squared Gaussians

Math 123: Mathematical Aspects of Data Analysis — Fall 2026

Published

November 18, 2026

The previous example established the concentration tool: for independent standard Gaussians, \(Z_k=\frac1k\sum_{r=1}^kg_r^2\) is within \(\epsilon\) of \(1\) except with probability at most \(2e^{-k\epsilon^2/8}\), for \(0<\epsilon<1\). We now connect this probability statement to the random map in the Johnson–Lindenstrauss lemma. Fill a \(k\times d\) matrix \(\bfG\) with independent \(N(0,1)\) entries, and set \[ f(\bfx)=\frac{1}{\sqrt k}\,\bfG\bfx\in\Rbb^k. \] For a pair of distinct data points we measure the squared distortion ratio \[ R_{ij} = \frac{\|f(\bfx_i)-f(\bfx_j)\|^2}{\|\bfx_i-\bfx_j\|^2}, \] which is \(1\) when the distance survives exactly. (The teaser used the unsquared ratio \(r_{ij}=\sqrt{R_{ij}}\); squares are easier to compute with.)

This page supplies the connection and finishes the proof.

  1. Show that for each fixed pair of distinct points, \(R_{ij}\) has exactly the distribution of \(Z_k\).
  2. Apply the concentration bound and the union bound over all \(\binom n2\) pairs.

The randomness throughout is in \(\bfG\) only. The data points are fixed before \(\bfG\) is drawn.

import numpy as np
from scipy.spatial.distance import pdist
from scipy.stats import chi2, norm

rng = np.random.default_rng(2026)


def project_many(u, k, M, batch=200):
    """Draw M independent k x d Gaussian matrices G and return the M x k array of products G u."""
    out = []
    for start in range(0, M, batch):
        G = rng.standard_normal((min(batch, M - start), k, u.size))
        out.append(G @ u)
    return np.concatenate(out)


def Zk_density(z, k):
    """Density of Z_k = (chi-squared with k degrees of freedom) / k."""
    return chi2.pdf(z, df=k, scale=1 / k)
Figure style
import plotly.graph_objects as go

INK = "#7c7c78"
GRID = "rgba(128, 128, 128, 0.28)"
BLUE, ORANGE, TEAL = "#2a78d6", "#eb6834", "#27a9a0"
CONFIG = dict(displayModeBar=False, responsive=True)


def style(fig, height=460, title=None, showlegend=None):
    """Apply the shared layout to a plot with axes."""
    fig.update_layout(
        template="simple_white",
        paper_bgcolor="rgba(0,0,0,0)",
        plot_bgcolor="rgba(0,0,0,0)",
        font=dict(color=INK, size=13),
        title=dict(text=title, x=0, xanchor="left", font=dict(size=15)),
        margin=dict(l=60, r=30, t=60 if title else 40, b=50),
        height=height,
        showlegend=showlegend,
        hovermode="closest",
    )
    fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    return fig


def step_histogram(samples, bins, total=None):
    """Bin edges' midpoints and density heights, normalised by `total` samples (default: all of them)."""
    counts, edges = np.histogram(samples, bins=bins)
    total = samples.size if total is None else total
    return 0.5 * (edges[:-1] + edges[1:]), counts / (total * np.diff(edges))

From pairs to one fixed vector

The map \(f\) is linear, so \(f(\bfx_i)-f(\bfx_j)=f(\bfx_i-\bfx_j)\). Writing \(\bfu=\bfx_i-\bfx_j\), which we assume is nonzero, \[ R_{ij} = \frac{\|f(\bfu)\|^2}{\|\bfu\|^2} = \frac{1}{k\|\bfu\|^2}\sum_{r=1}^k(\bfG\bfu)_r^2 = \frac1k\sum_{r=1}^k\left(\frac{(\bfG\bfu)_r}{\|\bfu\|}\right)^2. \] So the question really is: what is the distribution of the \(k\) numbers \((\bfG\bfu)_r/\|\bfu\|\)? We answer it in three steps.

Theorem 1 (The distortion is a sum of squared Gaussians) Let \(\bfu\in\Rbb^d\) be fixed and nonzero, and let \(\bfG\in\Rbb^{k\times d}\) have independent \(N(0,1)\) entries. Then the numbers \[ g_r=\frac{(\bfG\bfu)_r}{\|\bfu\|},\qquad r=1,\ldots,k, \] are independent \(N(0,1)\) random variables, and therefore \[ \frac{\|f(\bfu)\|^2}{\|\bfu\|^2}=\frac1k\sum_{r=1}^kg_r^2=Z_k. \] In particular, the distribution of the distortion depends on \(k\), but on neither \(\bfu\) nor \(d\).

This notebook is an illustrated guide to the proof! Part of the beauty of data science is that many proofs admit such explainations.

Suppose we have three very different vectors,

  • a single coordinate direction \(\bfu=\bfe_1\) in \(\Rbb^{20}\), so that only the first column of \(\bfG\) matters;
  • the all-ones vector in \(\Rbb^{500}\), spread evenly over every coordinate;
  • a deliberately lopsided vector in \(\Rbb^{5000}\): a few large spikes on top of a slow oscillation;

and for each one draw \(20{,}000\) independent matrices \(\bfG\) with \(k=5\) rows.

k, M = 5, 20_000
l = np.arange(5000)
vectors = {
    "e1": np.eye(20)[0],                                                   # in R^20
    "ones": np.ones(500),                                                  # in R^500
    "spiky": np.sin(l / 40) + 8.0 * np.isin(l, [17, 400, 401, 902]),       # in R^5000
}
COLORS = [ORANGE, TEAL, BLUE]

# For each vector u, an M x k array whose m-th row is G u / ||u|| for the m-th draw of G.
g = {name: project_many(u, k, M) / np.linalg.norm(u) for name, u in vectors.items()}

Step 1: one coordinate of \(\bfG\bfu\) is Gaussian

Row \(r\) of \(\bfG\) gives \[ (\bfG\bfu)_r=\sum_{l=1}^dG_{rl}\,u_l, \] a fixed weighted sum of \(d\) independent standard Gaussians. Figure 1 shows the histogram of the first normalised coordinate \(g_1=(\bfG\bfu)_1/\|\bfu\|\) for each of the three vectors.

for name, gu in g.items():
    g1 = gu[:, 0]  # first normalised coordinate, one value per draw of G
    print(f"{name:>5}:  mean of g_1 = {g1.mean():+.3f},  variance of g_1 = {g1.var():.3f}")
   e1:  mean of g_1 = +0.001,  variance of g_1 = 0.999
 ones:  mean of g_1 = -0.003,  variance of g_1 = 0.997
spiky:  mean of g_1 = +0.012,  variance of g_1 = 0.987
Plot the histograms
LABELS = {"e1": "e₁ in ℝ²⁰", "ones": "all ones in ℝ⁵⁰⁰", "spiky": "spiky in ℝ⁵⁰⁰⁰"}
x_g = np.linspace(-4, 4, 400)
fig = go.Figure()
for (name, gu), color in zip(g.items(), COLORS):
    mid, h = step_histogram(gu[:, 0], np.linspace(-4, 4, 81))
    fig.add_trace(go.Scatter(x=mid, y=h, mode="lines", name=LABELS[name],
                             line=dict(color=color, width=2, shape="hvh")))
fig.add_trace(go.Scatter(x=x_g, y=norm.pdf(x_g), mode="lines", name="N(0,1) density",
                         line=dict(color=INK, width=2, dash="dash")))
style(fig, height=420, showlegend=True)
fig.update_layout(legend=dict(x=0.75, y=0.95))
fig.update_xaxes(title_text="g<sub>1</sub> = (Gu)<sub>1</sub> / ‖u‖", range=[-4, 4])
fig.update_yaxes(title_text="density")
fig.show(config=CONFIG)
Figure 1: Histograms of the first normalised coordinate g₁ = (Gu)₁ / ‖u‖ over 20,000 draws of G, for three very different vectors u. All three match the N(0,1) density.

In every case the histogram is the standard Gaussian bell, even for \(\bfu=\bfe_1\), where the sum has a single term, and for the spiky vector, where a few terms dominate. The reason is a standard fact about Gaussians, which we use without proof.

Proposition 1 (Sums of independent Gaussians) If \(X_1,\ldots,X_d\) are independent with \(X_l\sim N(\mu_l,\sigma_l^2)\), then \[ \sum_{l=1}^dX_l\sim N\!\left(\sum_{l=1}^d\mu_l,\;\sum_{l=1}^d\sigma_l^2\right). \]

If you are curious why, Wikipedia has several proofs under sum of normally distributed random variables. We also need to know what happens when a Gaussian is multiplied by a constant.

Lemma 1 (Scaling a Gaussian) If \(X\sim N(\mu,\sigma^2)\) and \(c\in\Rbb\) is a constant, then \(cX\sim N(c\mu,c^2\sigma^2)\).

By Lemma 1, each term \(G_{rl}u_l\) is a Gaussian with mean \(0\) and variance \(u_l^2\), and the terms are independent. By Proposition 1, \[ (\bfG\bfu)_r\sim N\!\left(0,\;\sum_{l=1}^du_l^2\right)=N\!\left(0,\|\bfu\|^2\right), \qquad\text{so}\qquad g_r=\frac{(\bfG\bfu)_r}{\|\bfu\|}\sim N(0,1). \]

Step 2: the coordinates are independent

Figure 2 plots the first two normalised coordinates \((g_1,g_2)\) against each other, one dot per draw of \(\bfG\), for the spiky vector.

gu = g["spiky"]
print(f"correlation of g_1 and g_2:      {np.corrcoef(gu[:, 0], gu[:, 1])[0, 1]:+.3f}")
print(f"correlation of g_1^2 and g_2^2:  {np.corrcoef(gu[:, 0]**2, gu[:, 1]**2)[0, 1]:+.3f}")
correlation of g_1 and g_2:      -0.005
correlation of g_1^2 and g_2^2:  +0.002
Plot the scatter
fig = go.Figure(go.Scatter(x=gu[:3000, 0], y=gu[:3000, 1], mode="markers",
                           marker=dict(color=BLUE, size=4, opacity=0.4),
                           hovertemplate="g₁ = %{x:.2f}<br>g₂ = %{y:.2f}<extra></extra>"))
style(fig, height=480, showlegend=False)
fig.update_xaxes(title_text="g<sub>1</sub>", range=[-4, 4], constrain="domain")
fig.update_yaxes(title_text="g<sub>2</sub>", range=[-4, 4], scaleanchor="x", scaleratio=1)
fig.show(config=CONFIG)
Figure 2: The first two normalised coordinates (g₁, g₂) of Gu for the spiky vector, for 3,000 draws of G. The cloud is round, with no tilt or other structure: knowing g₁ tells you nothing about g₂.

The cloud is round and has no tilt; this is what a pair of independent \(N(0,1)\) variables looks like.

This is because each coordinate \((\bfG\bfu)_r\) is computed from row \(r\) of \(\bfG\) alone, and different rows of \(\bfG\) consist of different, independent entries. Quantities computed from independent ingredients are independent, so \(g_1,\ldots,g_k\) are independent.

Together with Step 1, \(g_1,\ldots,g_k\) are independent \(N(0,1)\).

Step 3: the distortion is \(Z_k\)

Substituting Steps 1 and 2 into the formula for \(R_{ij}\) from Section 1, \[ \boxed{\; \frac{\|f(\bfu)\|^2}{\|\bfu\|^2} = \frac1k\sum_{r=1}^kg_r^2 = Z_k, \;} \] which proves Theorem 1.

We can see this by averaging the square of the five example coordinates we have. Figure 3 shows the resulting squared distortion \(R=\|f(\bfu)\|^2/\|\bfu\|^2\) for all three vectors, against the density of \(Z_5\).

# Average the k squared coordinates: ||G u||^2 / (k ||u||^2), one value per draw of G.
R_by_vector = {name: np.mean(gu**2, axis=1) for name, gu in g.items()}
Plot the histograms
x_R = np.linspace(0.001, 3.5, 400)
fig = go.Figure()
for (name, R), color in zip(R_by_vector.items(), COLORS):
    mid, h = step_histogram(R, np.linspace(0, 3.5, 71))
    fig.add_trace(go.Scatter(x=mid, y=h, mode="lines", name=LABELS[name],
                             line=dict(color=color, width=2, shape="hvh")))
fig.add_trace(go.Scatter(x=x_R, y=Zk_density(x_R, k), mode="lines", name=f"density of Z<sub>{k}</sub>",
                         line=dict(color=INK, width=2, dash="dash")))
fig.add_vline(x=1, line=dict(color=INK, width=1, dash="dot"))
style(fig, height=420, showlegend=True)
fig.update_layout(legend=dict(x=0.7, y=0.95))
fig.update_xaxes(title_text="squared distortion R", range=[0, 3.5])
fig.update_yaxes(title_text="density")
fig.show(config=CONFIG)
Figure 3: Histograms of the squared distortion R = ‖f(u)‖² / ‖u‖² over 20,000 draws of G with k = 5, for three very different vectors in three different dimensions. All three agree with the density of Z_5, which is skewed and not Gaussian.

Notice that the distortion is not Gaussian, even though each \(g_r\) is.

The mean and variance from the previous example now describe the squared distortion: its mean is \(1\) and its standard deviation is \(\sqrt{2/k}\).

Now, behavior over all pairs

So far we fixed one vector and redrew \(\bfG\) many times. In practice we do the opposite: draw \(\bfG\) once, and apply it to all \(\binom n2\) pairs. Theorem 1 says every single pair has distortion distributed like \(Z_k\), so we should expect the histogram over pairs to look like \(Z_k\) too.

Move the slider. We take \(n=500\) standard Gaussian points in \(\Rbb^{5000}\), draw one \(\bfG\) for each \(k\), and histogram \(R_{ij}\) over all \(124{,}750\) pairs.

n, d_pairs = 500, 5000
X = rng.standard_normal((n, d_pairs))  # row i is the data point x_i
D = pdist(X, "sqeuclidean")            # ||x_i - x_j||^2 for every pair i < j
ks = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000]


def pair_distortions(k):
    """Draw one k x d Gaussian G and return R_ij for every pair i < j."""
    G = rng.standard_normal((k, d_pairs))
    Y = X @ G.T / np.sqrt(k)  # row i is f(x_i) = G x_i / sqrt(k)
    return pdist(Y, "sqeuclidean") / D


R_pairs = {k: pair_distortions(k) for k in ks}
Plot the slider
bins = np.linspace(0, 3, 601)  # width 0.005, fine enough for sd √(2/2000) ≈ 0.03
z = np.linspace(0.002, 3, 1500)


def pairs_frame(k):
    Rp = R_pairs[k]
    mid, h = step_histogram(Rp, bins)
    dens = Zk_density(z, k)
    title = (f"<b>k = {k}</b> · over all pairs: mean {Rp.mean():.3f}, "
             f"sd {Rp.std():.3f}  (theory: 1 and √(2/k) = {np.sqrt(2 / k):.3f})")
    traces = [
        go.Scatter(x=mid, y=h, mode="lines", name="Histogram of $R_{ij}$",
                   line=dict(color=BLUE, width=0, shape="hvh"),
                   fill="tozeroy", fillcolor="rgba(42, 120, 214, 0.35)", hoverinfo="skip"),
        go.Scatter(x=z, y=dens, mode="lines", name="density of Z<sub>k</sub>",
                   line=dict(color=ORANGE, width=2, dash="dash"), hoverinfo="skip"),
    ]
    ymax = 1.15 * max(min(h.max(), 3.5), dens[z > 0.05].max())
    return traces, title, ymax


frames_data = {k: pairs_frame(k) for k in ks}
start = ks.index(5)
traces, title, ymax = frames_data[ks[start]]
fig = go.Figure(traces)
fig.frames = [go.Frame(name=str(k), data=t, traces=[0, 1],
                       layout=dict(title=dict(text=tt), yaxis=dict(range=[0, ym])))
              for k, (t, tt, ym) in frames_data.items()]
style(fig, height=520, title=title, showlegend=True)
fig.update_xaxes(title_text="squared distortion R<sub>ij</sub>", range=[0, 3])
fig.update_yaxes(title_text="density", range=[0, ymax])
fig.update_layout(
    legend=dict(x=0.72, y=0.95),
    margin=dict(l=70, r=30, t=60, b=130),
    sliders=[dict(
        active=start, x=0.05, len=0.9, y=-0.14,
        currentvalue=dict(prefix="k = ", font=dict(size=15)),
        pad=dict(t=25), tickcolor=GRID,
        steps=[dict(label=str(k), method="animate",
                    args=[[str(k)], dict(mode="immediate", frame=dict(duration=0, redraw=True),
                                         transition=dict(duration=0))])
               for k in ks],
    )],
)
fig.show(config=CONFIG)
Figure 4: The squared distortion ratios of all 124,750 pairs of 500 Gaussian points in R^5000, for a single draw of G per k. The histogram over pairs follows the density of Z_k, which narrows around 1 like the square root of 2/k.

\(k\) grows like \(\log n\)

We now know that each fixed pair’s squared distortion has the distribution of \(Z_k\), a chi-squared variable divided by \(k\). For a fixed tolerance \(0<\epsilon<1\), define the failure probability for one fixed pair by \[ p(k)=\Pr(|Z_k-1|\geq\epsilon). \] The notation suppresses the dependence on the fixed tolerance \(\epsilon\). The concentration theorem from the previous example gives \[ p(k)\leq2e^{-k\epsilon^2/8}. \] With at most \(N=\binom n2\) pairs of distinct points, the union bound says the projection preserves every squared distance within a factor \(1\pm\epsilon\) with probability at least \(1-Np(k)\). Pairs may have dependent distortions because they share the same \(\bfG\); the union bound does not require independence. Coincident points are preserved automatically. Thus the total failure probability is at most \[ Np(k)\leq2N e^{-k\epsilon^2/8}\leq n^2 e^{-k\epsilon^2/8}\leq\delta \] when \[ k\geq\frac8{\epsilon^2}\left(2\log n+\log\frac1\delta\right). \] This proves the Johnson–Lindenstrauss guarantee, independently of the original dimension \(d\).

Figure 5 shows, for each \(n\), the smallest \(k\) with \(Np(k)\leq\delta\), using three different estimates of \(p(k)\).

def exact_upper(k, eps):
    """P(Z_k >= 1 + eps), from the chi-squared distribution."""
    return chi2.sf(k * (1 + eps), df=k)


def exact_lower(k, eps):
    """P(Z_k <= 1 - eps), from the chi-squared distribution."""
    return chi2.cdf(k * (1 - eps), df=k)


eps, delta = 0.25, 0.05
ns = np.unique(np.round(np.logspace(1, 6, 41)).astype(int))


def smallest_k(fails):
    """Smallest k >= 1 with fails(k) <= 0, by bisection; fails must be decreasing in k."""
    lo, hi = 1, 2
    while fails(hi) > 0:
        hi *= 2
    while lo < hi:
        mid = (lo + hi) // 2
        lo, hi = (mid + 1, hi) if fails(mid) > 0 else (lo, mid)
    return lo


req = {"Chebyshev": [], "theorem": [], "exact": []}
for n_ in ns:
    N = n_ * (n_ - 1) / 2
    req["Chebyshev"].append(2 * N / (eps**2 * delta))
    req["theorem"].append(8 / eps**2 * np.log(2 * N / delta))
    req["exact"].append(smallest_k(
        lambda k: N * (exact_upper(k, eps) + exact_lower(k, eps)) - delta))

for n_ in [100, 1_000, 10_000, 1_000_000]:
    i = np.searchsorted(ns, n_)
    print(f"n = {ns[i]:>9,}:  " + ",  ".join(f"{name} k = {v[i]:,.0f}" for name, v in req.items()))
n =       100:  Chebyshev k = 3,168,000,  theorem k = 1,561,  exact k = 673
n =     1,000:  Chebyshev k = 319,680,000,  theorem k = 2,152,  exact k = 1,002
n =    10,000:  Chebyshev k = 31,996,800,000,  theorem k = 2,741,  exact k = 1,334
n = 1,000,000:  Chebyshev k = 319,999,680,000,000,  theorem k = 3,920,  exact k = 2,006
Plot the required dimensions
fig = go.Figure()
for (name, v), color, dash in zip(req.items(), [INK, ORANGE, BLUE],
                                  ["dash", "dash", "solid"]):
    fig.add_trace(go.Scatter(x=ns, y=v, mode="lines", name=name,
                             line=dict(color=color, width=2.2, dash=dash),
                             hovertemplate="n = %{x:,}<br>k = %{y:,.0f}<extra></extra>"))
style(fig, height=440, showlegend=True)
fig.update_xaxes(title_text="number of points n", type="log", exponentformat="power")
fig.update_yaxes(title_text="required target dimension k", type="log", exponentformat="power")
fig.update_layout(legend=dict(x=0.05, y=0.95))
fig.show(config=CONFIG)
Figure 5: The smallest target dimension k for which the union bound guarantees every pairwise squared distance within a factor 1 ± 0.25 with probability at least 0.95, against the number of points n. Chebyshev’s requirement grows like n²; the exponential bounds grow like log n.

The three curves come from three estimates of \(p(k)\).

  • Chebyshev, \(p(k)\leq2/(k\epsilon^2)\), needs \(k\geq2N/(\epsilon^2\delta)\), which grows like \(n^2\).
  • The theorem, \(p(k)\leq2e^{-k\epsilon^2/8}\), needs \(k\geq\frac8{\epsilon^2}\log\frac{2N}\delta\), which grows like \(\log n\).
  • The exact probability \(p(k)\) also gives a required \(k\) that grows like \(\log n\), with a smaller constant.

Going from \(100\) points to a million multiplies the number of pairs by about \(10^8\), but only multiplies the required \(k\) by less than \(3\). At \(n=1000\) the exact curve asks for \(k\approx1000\), about what the simulation in lecture needed, while the theorem asks for \(2152\). The gap between these two curves comes from the conservative concentration bound; both curves use the same union bound.

The two ingredients now fit together: every fixed pair has squared distortion distributed as \(Z_k\), and the exponential tail bound makes simultaneous control of all \(\binom n2\) pairs possible with \(k\) growing like \(\log n\). None of these curves depends on the original dimension \(d\).