---
title: Random projections
heading: Shrinking high-dimensional data with a random matrix while keeping every distance nearly intact
eyebrow: S14 · Lesson 41 · Random projections
xp: 50
---

::: hook
Lesson 40's PCA reduces dimension by finding the directions of largest variance, which takes an eigen-decomposition of the data's covariance. A surprising alternative needs no look at the data at all: multiply every point by the same random matrix. The **Johnson–Lindenstrauss lemma** says that $n$ points in any number of dimensions can be mapped to about $\ln n/\varepsilon^2$ dimensions so that every pairwise distance changes by at most a factor $1 \pm \varepsilon$. The target dimension depends on how many points there are and the accuracy wanted, not on the original dimension. Random projections speed up nearest-neighbor search, sketch data streams, and are the measurement matrices of lesson S7's compressed sensing.
:::

::: play
- The target dimension $k$ that the Johnson–Lindenstrauss bound guarantees for $n$ points, $k \ge 4\ln n/(\varepsilon^2/2 - \varepsilon^3/3)$, against the allowed distortion ε.
- Halving ε roughly quadruples $k$; multiplying the number of points by a thousand only adds a constant to it. The original dimension appears nowhere.
:::

```sim plot
view: graph
x: e = 0.05..0.5
y: k = 10..1e6 log
slider: n = 100..1e9 = 10000 log
plot: 4*ln(n)/(e^2/2 - e^3/3) | label: dimensions guaranteed by JL
readout: dimensions for 10% distortion = 4*ln(n)/(0.005 - 0.001/3)
```

::: predict
## 10 000 points live in a million dimensions. To keep every pairwise distance within ±10%, about how many dimensions does the Johnson–Lindenstrauss bound need?

- [ ] 1 million
- [ ] 10 000
- [x] About 7900
- [ ] About 40

::: reveal
$4\ln(10^4)/(0.1^2/2 - 0.1^3/3) = 36.8/0.00467$ = 7895. The million original dimensions don't enter. The bound is conservative: in practice a few thousand random dimensions usually do, and a looser ε = 0.2 needs only 2125.
:::
:::

::: nameit
## The lemma

For any $n$ points in $\mathbb R^d$ and $0 < \varepsilon < 1$, there is a linear map to $\mathbb R^k$ with

$$k \ge \frac{4\ln n}{\varepsilon^2/2 - \varepsilon^3/3}$$

such that every squared distance is preserved within a factor $1 \pm \varepsilon$. A random matrix works with high probability: entries drawn independently from $N(0, 1/k)$, or even $\pm 1/\sqrt k$ with equal probability.

## Why it works

For a fixed vector $\mathbf v$, each of the $k$ projected coordinates is a Gaussian with variance $\|\mathbf v\|^2/k$, so the projected squared length is $\|\mathbf v\|^2$ times an average of $k$ independent $\chi^2_1$ variables: its mean is exactly $\|\mathbf v\|^2$ and its relative spread shrinks as $1/\sqrt k$. A Chernoff bound (lesson A11's tail bounds) makes the probability of distortion beyond ε exponentially small in $k\varepsilon^2$, and a union bound over all $\binom n2$ pairs gives the $\ln n$.

## Against PCA

PCA finds the best $k$-dimensional subspace for squared error on average, but needs the data and an eigen-decomposition, and can distort individual distances badly. Random projections are data-oblivious, cost one matrix multiply, work on streams, and guarantee every pairwise distance, but use more dimensions than PCA when the data really is near a low-dimensional subspace.

## Uses

Approximate nearest-neighbor search in high dimensions, sketching streams of data into small summaries, speeding up least squares and SVD with random sketches, and compressed sensing's measurement matrices, which need the related restricted isometry property for sparse vectors.
:::

::: example
## How many dimensions does the bound require for 10 000 points at ε = 0.1 and 0.2, and for a million points at ε = 0.1?

::: solution
1. **The bound.** With $\ln(10^4)$ = 9.21:
   $$k \ge \frac{4\ln n}{\varepsilon^2/2 - \varepsilon^3/3}$$
2. **10 000 points, ε = 0.1.**
   $$\begin{aligned} k &\ge \frac{4\ln 10^4}{0.1^2/2 - 0.1^3/3} \\ &= 7895 \end{aligned}$$
3. **10 000 points, ε = 0.2.**
   $$\begin{aligned} k &\ge \frac{4\ln 10^4}{0.2^2/2 - 0.2^3/3} \\ &= 2125 \end{aligned}$$
4. **A million points, ε = 0.1.**
   $$\begin{aligned} k &\ge \frac{4\ln 10^6}{0.1^2/2 - 0.1^3/3} \\ &= 11\,842 \end{aligned}$$
5. **Compare.** A hundred times more points costs only 50% more dimensions.

**Answer:** 7895 dimensions at ε = 0.1 and 2125 at ε = 0.2 for 10 000 points, and 11 842 for a million points at ε = 0.1.
:::
:::

::: example
## Projecting a unit vector with a $k \times d$ matrix of $N(0, 1/k)$ entries, what are the mean and standard deviation of its projected squared length, for $k$ = 100 and $k$ = 10 000?

::: solution
1. **Projected squared length.** It is
   $$\frac1k\sum_{i=1}^kZ_i^2$$
   with mean 1 and variance $2/k$ (each $Z_i^2$ has variance 2).
2. **k = 100.**
   $$\begin{aligned} \sigma &= \sqrt{0.02} \\ &= 0.141 \end{aligned}$$
   so lengths typically change by about 14%.
3. **k = 10 000.** It's 1.4%.
4. **The trend.** The spread falls as $1/\sqrt k$, as for any average.

**Answer:** the mean is 1 in both cases; the standard deviation is 0.141 for k = 100 and 0.014 for k = 10 000.
:::
:::

::: example
## A search engine stores 300-dimensional embeddings for 50 million items. Projecting to 64 dimensions with a random matrix: how much memory does it save, and what typical distortion results?

::: solution
1. **Memory.**
   $$300/64 = 4.7$$
   times less.
2. **Distortion.** The typical relative change in squared distance is about
   $$\sqrt{2/64} = 0.18$$
   so distances shift by roughly 9%.
3. **Using it.** That's too much to guarantee exact nearest neighbors, but enough to shortlist candidates, which are then re-ranked with the full vectors. That two-stage search is how large-scale similarity search works.

**Answer:** memory falls by a factor of 4.7, and distances shift by roughly 9%.
:::
:::

::: check
given: n = 1000 | 100000 | 1e8; e = 0.1 | 0.2 | 0.3
answer: 4*ln(n)/(e^2/2 - e^3/3)
tolerance: 0.5%

## How many dimensions does the Johnson–Lindenstrauss bound require for {n} points at distortion ε = {e}?

::: right
Right. $4\ln n/(\varepsilon^2/2 - \varepsilon^3/3)$ = {answer}.
:::

::: misses
- [4*log(n)/(e^2/2 - e^3/3)] Use the natural logarithm.
- [4*ln(n)/(e^2/2)] Include the $-\varepsilon^3/3$ term.
- [any] Not yet. Evaluate the bound.
:::
:::

::: check
given: k = 16 | 64 | 256 | 4096
answer: sqrt(2/k)
tolerance: 0.5%

## A unit vector is projected to {k} dimensions with $N(0, 1/k)$ entries. What is the standard deviation of its projected squared length?

::: right
Right. $\sqrt{2/k}$ = {answer}.
:::

::: misses
- [1/sqrt(k)] Each $Z^2$ has variance 2, not 1.
- [2/k] That's the variance; take its square root.
- [any] Not yet. Variance $2/k$.
:::
:::

::: check
given: n1 = 1e4 | 1e5; f = 10 | 100 | 1000
answer: 4*ln(f)/(0.1^2/2 - 0.1^3/3)
tolerance: 0.5%

## At ε = 0.1, how many more dimensions does the bound require for {f} times as many points (starting from {n1})?

::: right
Right. $k$ grows by $4\ln f/(\varepsilon^2/2 - \varepsilon^3/3)$ = {answer}, whatever the starting count.
:::

::: misses
- [4*ln(f*n1)/(0.1^2/2 - 0.1^3/3)] That's the total for the larger set; the question is the increase.
- [any] Not yet. $k \propto \ln n$, so the increase depends only on the ratio.
:::
:::

::: check
kind: parts
given: d = 300 | 1024 | 4096; k = 32 | 64 | 128; N = 1 | 50 | 1000

## {N} million vectors of {d} dimensions (4-byte floats) are randomly projected to {k} dimensions.

::: part
answer: N*1e6*d*4/1e9
unit: GB
tolerance: 0.5%

### How much memory do the original vectors take?

::: misses
- [N*1e6*d/1e9] Each float is 4 bytes.
- [any] Not yet. Count × dimensions × 4 bytes.
:::
:::

::: part
answer: d/k
tolerance: 0.5%

### By what factor does the projection shrink them?

::: misses
- [k/d] It's the ratio of old to new dimensions.
- [any] Not yet. $d/k$.
:::
:::

::: right
Right. Memory and distance computations both scale with dimension, so the saving applies to search time as well.
:::
:::

::: check
given: k = 50 | 200 | 1000; e = 0.1 | 0.2 | 0.3
answer: 2*exp(-k*(e^2/2 - e^3/3)/2)
tolerance: 1%

## For one fixed vector projected to {k} dimensions, the chance its squared length is off by more than ε = {e} is at most $2e^{-k(\varepsilon^2/2 - \varepsilon^3/3)/2}$. What is that bound?

::: right
Right. {answer}: exponentially small in $k\varepsilon^2$, which is why a union bound over all pairs only costs $\ln n$.
:::

::: misses
- [exp(-k*(e^2/2 - e^3/3)/2)] Two tails: too long or too short.
- [any] Not yet. Evaluate the stated bound.
:::
:::

::: check
kind: choice

## Why does the Johnson–Lindenstrauss dimension not depend on the data's original dimension $d$?

- [x] Each projected squared length concentrates around the original one with a spread set by $k$ alone; $d$ only affects the cost of the multiplication
- [ ] Random matrices ignore most of the original dimensions
- [ ] High-dimensional data always lies in a low-dimensional subspace
- [ ] The lemma only applies when $d$ is small

::: right
Right. For any fixed vector, the projection's statistics depend only on its length and on $k$; the union bound over pairs adds $\ln n$. No property of the data is used.
:::

::: misses
- [2] Every original coordinate contributes to every projected one.
- [3] The lemma holds for any point set, low-dimensional or not.
- [4] It holds for any $d$; it's most useful when $d$ is huge.
:::
:::

::: check
kind: python
given: n = 100 | 300; k = 200 | 800; seed = 1 | 2

## Test the lemma. With `rng = numpy.random.default_rng(seed)`, draw `n` = {n} points in 5000 dimensions from a standard Gaussian, then a projection matrix `R = rng.standard_normal((k, 5000))/sqrt(k)` with `k` = {k}. Compute all pairwise squared distances before and after projecting, and set `max_dist`, the largest |ratio − 1| over all pairs, and `rms_dist`, the RMS of (ratio − 1). Compare `rms_dist` with $\sqrt{2/k}$.

```python starter
import numpy as np
max_dist = rms_dist = 0.0
```

```python solution
import numpy as np
rng = np.random.default_rng(seed)
X = rng.standard_normal((n, 5000))
R = rng.standard_normal((k, 5000)) / np.sqrt(k)
Y = X @ R.T
def sqd(A):
    g = (A * A).sum(1)
    return g[:, None] + g[None, :] - 2 * A @ A.T
D0, D1 = sqd(X), sqd(Y)
iu = np.triu_indices(n, 1)
r = D1[iu] / D0[iu] - 1
max_dist = float(np.max(np.abs(r)))
rms_dist = float(np.sqrt(np.mean(r * r)))
```

```python tests
import numpy as np
rng = np.random.default_rng(seed)
X = rng.standard_normal((n, 5000)); R = rng.standard_normal((k, 5000)) / np.sqrt(k); Y = X @ R.T
sq = lambda A: (A * A).sum(1)[:, None] + (A * A).sum(1)[None, :] - 2 * A @ A.T
iu = np.triu_indices(n, 1); r = sq(Y)[iu] / sq(X)[iu] - 1
assert abs(max_dist - np.max(np.abs(r))) < 1e-9 and abs(rms_dist - np.sqrt(np.mean(r * r))) < 1e-9, "Compute both distortion measures over all pairs."
assert abs(rms_dist / np.sqrt(2 / k) - 1) < 0.1, "The RMS distortion should be close to √(2/k)."
```

::: right
Right. The RMS distortion lands on $\sqrt{2/k}$ and the worst pair a few times that, with 5000 original dimensions playing no part.
:::
:::

::: explain
## A team compresses sensor fingerprints from 4096 to 256 dimensions for a nearest-neighbor lookup, choosing between PCA and a random projection. Explain the trade-offs.

::: model
PCA finds the 256 directions that keep the most variance across the training data, so if the fingerprints really vary mainly along a few directions, it preserves distances better per dimension than a random projection. But it needs the training data and an eigen-decomposition, its quality depends on new fingerprints resembling the training set, and it guarantees only average error: some pairs can be badly distorted. A random projection needs no data, costs one matrix multiply, works the same for any future fingerprints, and by Johnson–Lindenstrauss distorts every pair by about $\sqrt{2/256}$ ≈ 9% in squared distance, typically 4 to 5% in distance, with exponentially rare worse cases. For a shortlist followed by exact re-ranking, the random projection's simplicity and guarantees often win; for the most compact faithful representation of data that really is low-dimensional, PCA does.
:::
:::

::: practice

::: check
given: n = 5000 | 1e7; e = 0.15 | 0.25
answer: 4*ln(n)/(e^2/2 - e^3/3)
tolerance: 0.5%

## What dimension does the JL bound give for {n} points at ε = {e}?

::: misses
- [4*log(n)/(e^2/2 - e^3/3)] Natural log.
- [any] $4\ln n/(\varepsilon^2/2 - \varepsilon^3/3)$.
:::
:::

::: check
given: k = 16 | 32 | 64 | 128 | 256 | 512 | 1024
answer: sqrt(2/k)
tolerance: 0.5%

## What's the typical relative spread in squared length after projecting to {k} dimensions?

::: misses
- [1/sqrt(k)] Each $\chi^2_1$ term has variance 2.
- [any] $\sqrt{2/k}$.
:::
:::
:::
