---
title: "Random Projections: Too Good to Be True?"
subtitle: "Math 123: Mathematical Aspects of Data Analysis — Fall 2026"
date: 2026-11-12
number-sections: false
jupyter: python3
format:
html:
toc: true
toc-depth: 2
code-line-numbers: true
code-tools: true
out-width: "100%"
column: page
execute:
echo: true
draft: false
---
Consider [classical MDS](../../lectures/lecture-18.qmd#alg-classical-mds), which turns a table of pairwise distances into coordinates.
That table is expensive to build and expensive to use.
Every one of the $\binom n2$ distances costs a pass over all $d$ coordinates, and then we still need an eigendecomposition of a dense $n\times n$ matrix.
When $d$ is in the tens of thousands, as with images or word counts, most of the cost comes before MDS even starts.
MDS only ever looks at the distances, though, and never at the coordinates themselves.
So if we could first shrink each point down to a few numbers *without changing the distances*, MDS would give essentially the same answer for a fraction of the cost.
The same goes for anything else built on distances: $k$-means, nearest-neighbour graphs, Isomap.
Suppose we have $n=300$ points $\bfx_1,\ldots,\bfx_n$ in $\Rbb^d$ with $d=10{,}000$, and we want to store each one with only $k$ numbers, while keeping *every one* of the $\binom{300}{2}=44{,}850$ pairwise distances roughly the same.
We will do something that sounds, absurd, ridiculous, and utterly delightful (because it works)!
Fill a $k\times d$ matrix $\bfG$ with independent standard Gaussian numbers, without ever looking at the data, and send
$$
\bfx
\;\longmapsto\;
f(\bfx)=\frac{1}{\sqrt k}\,\bfG\bfx\in\Rbb^k.
$$
For each pair we record the *distortion ratio*
$$
r_{ij}
=
\frac{\|f(\bfx_i)-f(\bfx_j)\|}{\|\bfx_i-\bfx_j\|},
$$
which is $1$ when the distance between $\bfx_i$ and $\bfx_j$ survives the projection exactly.
```{python}
import numpy as np
from scipy.spatial.distance import pdist
rng = np.random.default_rng(123)
def clustered_points(n, d, n_clusters=6, rng=rng):
"""n points in R^d, in clusters of different sizes, so pairwise distances vary a lot."""
labels = rng.integers(n_clusters, size=n)
centers = rng.uniform(0.5, 3.0, size=(n_clusters, 1)) * rng.standard_normal((n_clusters, d))
spread = rng.uniform(0.2, 1.0, size=n_clusters)
return centers[labels] + spread[labels, None] * rng.standard_normal((n, d))
def random_projection(X, k, rng=rng):
"""Apply f(x) = G x / sqrt(k) to every row of X, with G a k x d standard Gaussian matrix."""
G = rng.standard_normal((k, X.shape[1]))
return X @ G.T / np.sqrt(k)
def ratios(X, Y):
"""Distortion ratios ||y_i - y_j|| / ||x_i - x_j|| over all pairs i < j."""
return pdist(Y) / pdist(X)
n, d = 300, 10_000
X = clustered_points(n, d)
dist = pdist(X)
print(f"{n} points in R^{d}: {dist.size} pairs, distances from {dist.min():.1f} to {dist.max():.1f}")
```
```{python}
#| code-fold: true
#| code-summary: "Figure style"
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# The same muted palette as the other examples, which reads correctly against
# both the light and the dark version of this site.
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
```
## Turn the dial on $k$ {#sec-k}
**Move the slider.**
Each dot is one pair $(i,j)$, plotted at its original distance $\|\bfx_i-\bfx_j\|$ and its projected distance $\|f(\bfx_i)-f(\bfx_j)\|$.
For readability we draw $2000$ randomly chosen pairs, but the worst ratios in the title are over all $44{,}850$.
The dotted lines mark a $10\%$ error in either direction.
```{python}
#| label: fig-slider-k
#| fig-cap: "Projected against original distance for a Gaussian random projection from d = 10,000 to k dimensions. The cloud of pairs closes in on the diagonal as k grows, at the same rate for short and long distances."
#| fig-alt: "An interactive scatter plot with a slider for k from 2 to 1000. At k = 2 the dots are scattered widely above and below the diagonal. As k increases they collapse onto the diagonal line y = x, and by k = 500 almost all of them lie between two dotted lines marking 10 percent error."
#| code-fold: true
#| code-summary: "Project for many k and draw the slider"
ks = [2, 5, 10, 20, 50, 100, 200, 500, 1000]
shown = rng.choice(dist.size, size=2000, replace=False)
proj = {k: pdist(random_projection(X, k)) for k in ks}
top = 1.05 * max(p[shown].max() for p in proj.values())
def frame_data(k):
r = proj[k] / dist
return [go.Scatter(
x=dist[shown], y=proj[k][shown], mode="markers", name="pairs",
marker=dict(color=BLUE, size=5, opacity=0.45),
hovertemplate="original %{x:.1f}<br>projected %{y:.1f}<extra></extra>",
)], (f"<b>k = {k}</b> · worst pair shrinks to {r.min():.2f}×, "
f"stretches to {r.max():.2f}×")
start = ks.index(10)
traces, title = frame_data(ks[start])
fig = go.Figure(traces)
xs = np.array([0, dist.max() * 1.05])
for slope, dash in [(1, "solid"), (0.9, "dot"), (1.1, "dot")]:
fig.add_trace(go.Scatter(x=xs, y=slope * xs, mode="lines", hoverinfo="skip",
line=dict(color=INK, width=1.2, dash=dash)))
frames = []
for k in ks:
traces, t = frame_data(k)
frames.append(go.Frame(name=str(k), data=traces, traces=[0],
layout=dict(title=dict(text=t))))
fig.frames = frames
style(fig, height=560, title=title, showlegend=False)
fig.update_xaxes(title_text="original distance ‖x<sub>i</sub> − x<sub>j</sub>‖",
range=[0, xs[1]])
fig.update_yaxes(title_text="projected distance ‖f(x<sub>i</sub>) − f(x<sub>j</sub>)‖",
range=[0, top])
fig.update_layout(
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)
```
Two things stand out.
First, nothing systematically shrinks or grows: the cloud is centred on the diagonal for every $k$, even $k=2$.
Second, the cloud fans out *proportionally*: short and long distances suffer the same relative error, so the ratios $r_{ij}$ are what we should study.
How fast does the error shrink?
@fig-spread plots the standard deviation of $r_{ij}$ over all pairs against $k$, on log–log axes, averaged over ten draws of $\bfG$.
```{python}
#| label: fig-spread
#| fig-cap: "The spread of the distortion ratios against k, on log-log axes. The points lie on a line of slope −1/2: to halve the typical error, multiply k by four."
#| fig-alt: "A log-log plot with k from 2 to 1000 on the horizontal axis and the standard deviation of the distortion ratio on the vertical axis. The blue points fall on a straight dotted reference line of slope minus one half, going from about 0.45 at k = 2 to about 0.02 at k = 1000."
#| code-fold: true
#| code-summary: "Plot the spread against k"
# Pairs in the same two clusters move together, so one draw of G is noisy; average over 10.
spread = np.array([np.mean([np.std(ratios(X, random_projection(X, k))) for _ in range(10)])
for k in ks])
for k, s in zip(ks, spread):
print(f"k = {k:>4}: std of r = {s:.3f}, sqrt(k) * std = {np.sqrt(k) * s:.3f}")
fig = go.Figure([
go.Scatter(x=ks, y=np.sqrt(ks[-1]) * spread[-1] / np.sqrt(ks), mode="lines", name="slope −1/2",
line=dict(color=INK, width=1.2, dash="dot"), hoverinfo="skip"),
go.Scatter(x=ks, y=spread, mode="markers+lines", name="std of r<sub>ij</sub>",
marker=dict(color=BLUE, size=9), line=dict(color=BLUE, width=2),
hovertemplate="k = %{x}<br>std = %{y:.3f}<extra></extra>"),
])
style(fig, height=420, showlegend=True)
fig.update_xaxes(type="log", title_text="target dimension k")
fig.update_yaxes(type="log", title_text="standard deviation of r<sub>ij</sub>")
fig.update_layout(legend=dict(x=0.7, y=0.95))
fig.show(config=CONFIG)
```
The product $\sqrt k\cdot\mathrm{std}(r_{ij})$ is essentially constant, so the typical error is about $c/\sqrt k$.
Turning that around: to get relative error $\epsilon$ on a typical pair, take $k$ on the order of $1/\epsilon^2$.
## The original dimension does not matter {#sec-d}
Now fix $k=100$ and change $d$ instead.
Surely squeezing $\Rbb^{20{,}000}$ into $\Rbb^{100}$ is harder than squeezing $\Rbb^{200}$ into $\Rbb^{100}$?
To get many independent-looking pairs, we use $n=300$ standard Gaussian points in each dimension, and pool five draws of $\bfG$.
```{python}
#| label: fig-dimension
#| fig-cap: "Histograms of the distortion ratios r_ij for a random projection to k = 100 dimensions, starting from three very different dimensions d. The three histograms are indistinguishable."
#| fig-alt: "Three overlaid histograms of distortion ratios, for d = 200, 2,000, and 20,000, all projected to k = 100. All three are bell-shaped, centred at 1, run from about 0.7 to 1.3, and lie on top of each other."
#| code-fold: true
#| code-summary: "Repeat the experiment for d = 200, 2000, 20000"
k = 100
fig = go.Figure()
for d_, color in zip([200, 2_000, 20_000], [ORANGE, TEAL, BLUE]):
Xd = rng.standard_normal((n, d_))
r = np.concatenate([ratios(Xd, random_projection(Xd, k)) for _ in range(5)])
print(f"d = {d_:>6}: mean r = {r.mean():.3f}, std r = {r.std():.3f}, "
f"range [{r.min():.3f}, {r.max():.3f}]")
fig.add_trace(go.Histogram(
x=r, name=f"d = {d_:,}", histnorm="probability density",
xbins=dict(start=0.7, end=1.3, size=0.005),
marker=dict(color=color, line=dict(width=0)), opacity=0.45,
))
style(fig, height=420, showlegend=True)
fig.update_layout(barmode="overlay", legend=dict(x=0.78, y=0.95))
fig.update_xaxes(title_text="distortion ratio r<sub>ij</sub>", range=[0.7, 1.3])
fig.update_yaxes(title_text="density")
fig.show(config=CONFIG)
```
The answer depends on $k$ and not at all on $d$.
Compare this with PCA, where how far we can compress depends entirely on the singular values of the data.
## Why does it have to be random? {#sec-why-random}
If $d$ does not matter, maybe any cheap reduction works.
The simplest one keeps $k$ of the $d$ coordinates, chosen at random, and rescales by $\sqrt{d/k}$ so that squared distances are right on average.
To see why this is a bad idea, take *sparse* data, like word counts for documents: each point has only $20$ nonzero coordinates out of $10{,}000$, in random positions.
```{python}
#| label: fig-sparse
#| fig-cap: "Distortion ratios for sparse data, reduced to k = 200 dimensions in two ways. Keeping random coordinates (orange) sends almost half of the pairs to distance zero; the Gaussian random projection (blue) keeps every pair within about 25%."
#| fig-alt: "Two histograms of distortion ratios on a common horizontal axis from 0 to 3. The orange histogram for coordinate sampling has a tall spike at 0 and a long, flat spread out to almost 3. The blue histogram for the Gaussian projection is a narrow bump centred at 1."
#| code-fold: true
#| code-summary: "Make sparse data and compare the two reductions"
n_nonzero, k = 20, 200
S = np.zeros((n, d))
for i in range(n):
S[i, rng.choice(d, size=n_nonzero, replace=False)] = rng.uniform(1, 3, size=n_nonzero)
keep = rng.choice(d, size=k, replace=False)
reductions = {
"keep k random coordinates": (S[:, keep] * np.sqrt(d / k), ORANGE),
"Gaussian random projection": (random_projection(S, k), BLUE),
}
fig = go.Figure()
for name, (Y, color) in reductions.items():
r = ratios(S, Y)
print(f"{name:>27}: range [{r.min():.3f}, {r.max():.3f}], "
f"fraction of pairs sent to 0: {np.mean(r == 0):.1%}")
fig.add_trace(go.Histogram(
x=r, name=name, histnorm="probability",
xbins=dict(start=0, end=3, size=0.02),
marker=dict(color=color, line=dict(width=0)), opacity=0.6,
))
style(fig, height=420, showlegend=True)
fig.update_layout(barmode="overlay", legend=dict(x=0.55, y=0.95))
fig.update_xaxes(title_text="distortion ratio r<sub>ij</sub>", range=[-0.05, 3])
fig.update_yaxes(title_text="fraction of pairs", type="log")
fig.show(config=CONFIG)
```
Each sampled coordinate is a guess at where the information is, and for sparse data the guesses mostly miss.
Each row of $\bfG$, on the other hand, mixes *all* $d$ coordinates, so no direction in $\Rbb^d$ can hide from it.
The randomness is not there to save effort; it is what lets one fixed recipe work for every dataset, chosen before the data are seen.
## How many points can we afford? {#sec-n}
The typical pair is fine once $k\approx1/\epsilon^2$.
But we asked for *every* pair, and with $n$ points there are $\binom n2$ chances for something to go wrong.
@fig-worst-case tracks the worst ratio over all pairs as $n$ grows, for two fixed values of $k$.
```{python}
#| label: fig-worst-case
#| fig-cap: "The worst relative error max |r_ij − 1| over all pairs, for n Gaussian points in R^500 projected to k dimensions, averaged over 5 trials. As n grows 300-fold the number of pairs grows 90,000-fold, but the worst error only creeps up."
#| fig-alt: "A plot with the number of points n on a logarithmic horizontal axis from 10 to 3000 and the worst relative error on the vertical axis. Two increasing curves, orange for k = 50 and blue for k = 200, rise slowly: the orange from about 0.2 to about 0.55, the blue from about 0.12 to about 0.27."
#| code-fold: true
#| code-summary: "Measure the worst pair as n grows"
ns = [10, 30, 100, 300, 1000, 3000]
trials, d_small = 5, 500
worst = {50: [], 200: []}
for n_ in ns:
for k_ in worst:
errs = []
for _ in range(trials):
Z = rng.standard_normal((n_, d_small))
errs.append(np.max(np.abs(ratios(Z, random_projection(Z, k_)) - 1)))
worst[k_].append(np.mean(errs))
for k_, w in worst.items():
print(f"k = {k_:>3}: worst error", " ".join(f"{e:.3f}" for e in w))
fig = go.Figure()
for (k_, w), color in zip(worst.items(), [ORANGE, BLUE]):
fig.add_trace(go.Scatter(
x=ns, y=w, mode="markers+lines", name=f"k = {k_}",
marker=dict(color=color, size=9), line=dict(color=color, width=2),
customdata=[n_ * (n_ - 1) // 2 for n_ in ns],
hovertemplate="n = %{x}<br>%{customdata:,} pairs<br>worst error %{y:.3f}<extra></extra>",
))
style(fig, height=420, showlegend=True)
fig.update_xaxes(type="log", title_text="number of points n")
fig.update_yaxes(title_text="worst relative error max |r<sub>ij</sub> − 1|", rangemode="tozero")
fig.update_layout(legend=dict(x=0.05, y=0.95))
fig.show(config=CONFIG)
```
Each tenfold increase in $n$ adds roughly the same small amount to the worst error, which is what growth like $\sqrt{\log n}$ looks like.
So $k$ only needs to grow logarithmically with the number of points.
## Questions for the lecture
Everything above is an experiment; none of it is proved.
Here is what we will need to explain.
1. *Why is there no bias?* Show that $\Ebb\,\|f(\bfx)\|^2=\|\bfx\|^2$ for every fixed $\bfx\in\Rbb^d$. (Each coordinate of $\bfG\bfx$ is a sum of $d$ independent Gaussians; what is its variance?)
2. *Why does $d$ disappear?* For a fixed unit vector $\bfx$, what is the distribution of $\bfG\bfx$? Why does it not depend on which unit vector, or on $d$?
3. *Why $1/\sqrt k$?* $\|f(\bfx)\|^2$ is an average of $k$ independent quantities. Which [tail bound](../../lectures/lecture-19.qmd#a-table-of-tail-bounds) controls how far it is from its mean?
4. *Why $\log n$?* How do the [union bound and the master tail bound](../../lectures/lecture-19.qmd#toward-random-projections) together turn a guarantee for one pair into a guarantee for all $\binom n2$ pairs?
The answers add up to the *Johnson–Lindenstrauss lemma*: $k$ on the order of $\log(n)/\epsilon^2$ dimensions suffice to keep every pairwise distance within a factor $1\pm\epsilon$, for any $n$ points in any dimension.