---
title: Nearest neighbors and the curse of dimensionality
heading: Classifying by the nearest training examples, the Cover–Hart bound on their error, k-nearest-neighbor density estimates, why neighborhoods stop being local in many dimensions, and what searching a large reference set costs
eyebrow: S14 · Lesson 18 · Nearest neighbors
xp: 50
---

::: hook
The simplest classifier there is needs no training at all: store every example, and label a new input like the stored example nearest to it. With enough data its error is never worse than twice the best possible. Yet the same idea fails badly on inputs with hundreds of features, because in many dimensions almost nothing is near anything. Both facts shape how real systems handle high-dimensional data.
:::

::: play
- The axis across is the number of dimensions D of data spread uniformly through a unit cube.
- The solid curve is the edge length of a smaller cube that holds a fraction r of the data: it approaches the whole cube's edge as D grows, so a "neighborhood" that holds 1% of the data spans nearly the full range of every feature.
- The dashed curve is the fraction of the cube's volume within a distance e of its surface: in many dimensions nearly all of it.
:::

```sim plot
view: graph
x: D = 1..1000 log
y: f = 0..1
slider: r = 0.001..0.5 = 0.01 log
slider: e = 0.01..0.2 = 0.05
plot: r^(1/D) | label: edge holding a fraction r
plot: 1 - (1 - 2*e)^D | dashed | label: volume within e of the surface
```

::: predict
## Data fill a 100-dimensional unit cube uniformly. How long must the edges of a smaller cube be to hold 1% of the data?

- [ ] 0.01
- [ ] 0.1
- [ ] 0.5
- [x] 0.95

::: reveal
The smaller cube's volume must be 0.01, so its edge is $0.01^{1/100}$ = 0.955. To gather even 1% of the data, a neighborhood must cover 95% of each feature's range: nothing in it is local. In 2 dimensions the same edge is 0.1.
:::
:::

::: nameit
## Nearest neighbors

The **k-nearest-neighbor** classifier finds the k stored examples closest to the input and takes a majority vote; for regression it averages their targets. Small k follows the data closely and is noisy; large k is smooth and biased. k is chosen by cross-validation (lesson 12), and features must be scaled comparably, since the distance treats them alike.

## The Cover–Hart bound

As the number of stored examples grows, the nearest neighbor's label becomes a sample from the posterior at the input. For two classes, the 1-NN error rate R then satisfies
$$R^* \le R \le 2R^*(1 - R^*)$$
where $R^*$ is the Bayes error of lesson 3. Half the information needed for the best possible decision is in the single nearest example.

## Density estimates

If the K nearest of N points lie within a region of volume V around x,
$$p(\mathbf x) \approx \frac{K}{NV}$$
Applied to each class with Bayes' theorem, this gives the k-NN classifier's posterior $K_k/K$.

## The curse of dimensionality

In D dimensions, a cube holding a fraction r of uniform data has edge $r^{1/D}$, and the shell within ε of the surface of a unit cube holds $1 - (1 - 2\epsilon)^D$ of its volume. Distances concentrate: for points uniform in a unit cube, the squared distance between two of them has mean D/6 and relative spread $1.18/\sqrt D$, so the nearest and farthest neighbors become almost equally far. Methods that rely on locality need data that grow exponentially with D, unless the data really lie near a low-dimensional surface, which is what makes PCA (lesson 40) and learned features worthwhile.

## Search cost

Brute-force search costs N × D operations per query. Tree structures (k-d trees) prune well in a few dimensions but degrade to brute force in many; large systems use approximate searches that trade a few missed neighbors for orders of magnitude in speed.
:::

::: example
## A problem's Bayes error is 5%. What error can a 1-nearest-neighbor classifier reach with unlimited data, and how does that compare with 3-NN?

::: solution
1. **Cover and Hart's bound.**
   $$\begin{aligned} P_e &\le 2 \times 0.05 \times 0.95 \\ &= 9.5\% \end{aligned}$$
   and at least 5%.
2. **More neighbors.** Voting among k neighbors moves the asymptotic error toward the Bayes error as k grows (while k/N shrinks): 3-NN's limit is already noticeably closer than 1-NN's.
3. **Finite data.** With finite data the gap depends on how densely the examples cover the input space, which is where dimension enters.

**Answer:** with unlimited data 1-NN's error lies between 5% and 9.5%, and 3-NN's limit is noticeably closer to the Bayes error.
:::
:::

::: example
## Among 1000 points in a plane, the 10 nearest to x lie within a radius of 0.2. Estimate the density at x. And how long does a brute-force search of a million 128-dimensional reference vectors take at 10¹⁰ multiply-adds per second?

::: solution
1. **Disk area.**
   $$\pi \times 0.2^2 = 0.126$$
2. **Density.**
   $$\begin{aligned} p &\approx \frac{10}{1000 \times \pi \times 0.2^2} \\ &= 0.080\ \text{per unit area} \end{aligned}$$
3. **Search cost.**
   $$10^6 \times 128 = 1.28 \times 10^8$$
   multiply-adds, 12.8 ms per query.
4. **Is it fast enough?** It's fine for occasional lookups, too slow for a service answering thousands of queries a second, which is why approximate indexes exist.

**Answer:** the density is about 0.080 per unit area, and a brute-force search takes 12.8 ms per query.
:::
:::

::: example
## For points uniform in a unit cube, how much do pairwise distances vary in 2, 10 and 1000 dimensions?

::: solution
1. **One coordinate.** A coordinate difference squared, $(u - v)^2$, has mean 1/6 and variance 7/180.
2. **The whole distance.** The squared distance has mean D/6 and standard deviation $\sqrt{7D/180}$, a relative spread of
   $$\frac{\sqrt{7D/180}}{D/6} = \frac{1.18}{\sqrt D}$$
3. **Put in the dimensions.** That's 0.84 in 2 dimensions, 0.37 in 10 and 0.037 in 1000.
4. **What it means.** In 1000 dimensions every pair of points is about the same distance apart, within a few percent, so "nearest" carries little information about similarity unless the data have structure that random points lack.

**Answer:** the relative spread of squared distances is 0.84 in 2 dimensions, 0.37 in 10 and 0.037 in 1000.
:::
:::

::: check
kind: parts
given: r = 0.001 | 0.01 | 0.1; D = 2 | 10 | 50 | 500

## Data are uniform in a {D}-dimensional unit cube.

::: part
answer: r^(1/D)
tolerance: 0.5%

### What edge length must a smaller cube have to hold a fraction {r} of them?

::: misses
- [r/D] The volume is the edge to the power D.
- [any] $r^{1/D}$.
:::
:::
:::

::: check
kind: parts
given: e = 0.01 | 0.05 | 0.1; D = 3 | 10 | 30

## A unit cube in {D} dimensions.

::: part
answer: 1 - (1 - 2*e)^D
tolerance: 0.5%

### What fraction of its volume lies within {e} of its surface?

::: misses
- [1 - (1 - e)^D] The shell is on both sides of each dimension: the inner cube's edge is 1 − 2ε.
- [any] $1 - (1 - 2\epsilon)^D$.
:::
:::
:::

::: check
kind: parts
given: R = 0.01 | 0.05 | 0.1 | 0.25

## A two-class problem has Bayes error {R}.

::: part
answer: 2*R*(1 - R)
tolerance: 0.5%

### What is the most error a 1-nearest-neighbor classifier can have with unlimited data?

::: misses
- [2*R] The bound is $2R^*(1 - R^*)$.
- [any] $2R^*(1 - R^*)$.
:::
:::
:::

::: check
kind: parts
given: K = 5 | 10 | 30; N = 500 | 5000; r = 0.05 | 0.3

## Among {N} points, the {K} nearest to x lie within radius {r}.

::: part
answer: K/(N*pi*r^2)
tolerance: 0.5%

### Estimate the density at x if the points lie in a plane.

::: misses
- [K/(N*r^2)] The area is $\pi r^2$.
- [any] $K/(NV)$ with V the disk's area.
:::
:::

::: part
answer: K/(N*4/3*pi*r^3)
tolerance: 0.5%

### And if they lie in three dimensions?

::: misses
- [any] V is the sphere's volume, $\frac43\pi r^3$.
:::
:::
:::

::: check
kind: parts
given: D = 2 | 10 | 100 | 1000

## Pairs of points are drawn uniformly from a {D}-dimensional unit cube.

::: part
answer: D/6
tolerance: 0.5%

### What is the mean squared distance between them?

::: misses
- [D/12] That's the variance of one coordinate; the difference of two has twice it.
- [any] Each coordinate contributes $E[(u - v)^2] = 1/6$.
:::
:::

::: part
answer: sqrt(7*D/180)/(D/6)
tolerance: 0.5%

### What is the squared distance's standard deviation relative to its mean?

::: misses
- [any] $\sqrt{7D/180}/(D/6)$.
:::
:::
:::

::: check
kind: parts
given: N = 10000 | 1000000; D = 64 | 512; Q = 100 | 5000; M = 1 | 50

## A service searches {N} reference vectors of dimension {D} by brute force, answering {Q} queries a second.

::: part
answer: N*D*Q/1e9
unit: GMAC/s
tolerance: 0.5%

### How many multiply-adds per second does it need, in billions?

::: misses
- [any] N × D per query.
:::
:::

::: part
answer: N*D*4/1e6*M
unit: MB
tolerance: 0.5%

### How much memory do the references take in 32-bit floats, for {M} copies?

::: misses
- [any] 4 bytes per value.
:::
:::
:::

::: check
kind: choice

## Why should features be standardized before using a nearest-neighbor classifier?

- [ ] Standardizing makes the classes separable
- [x] The distance adds up squared differences in every feature alike, so a feature measured in large units would dominate it regardless of how informative it is
- [ ] Nearest-neighbor search requires features between 0 and 1
- [ ] Standardizing reduces the number of dimensions

::: misses
- [1] It changes no class boundaries in the data, only the distance.
- [3] Any range works; the issue is relative scale.
- [4] The dimension is unchanged.
:::
:::

::: check
kind: derivation
vars: r = 0.0001..0.5, D = 1..1000, e = 0.001..0.2

## Data are uniform in a D-dimensional unit cube.

::: step
answer: r^(1/D)

### What edge does a cube holding a fraction r of them need?
:::

::: step
answer: 1 - (1 - 2*e)^D

### What fraction of the volume lies within e of the surface?
:::

::: right
Right. Both say the same thing: in many dimensions, almost everything is near the boundary and far from everything else.
:::
:::

::: check
kind: python

## Write `edge(r, D)` and `distance_spread(D, n, seed)`: draw n pairs of points uniformly in the D-dimensional unit cube with `random.Random(seed)`, and return the standard deviation of their squared distances divided by the mean.

```python starter
import random

def edge(r, D):
    return r / D

def distance_spread(D, n, seed):
    return 1.0
```

```python solution
import math, random

def edge(r, D):
    return r ** (1 / D)

def distance_spread(D, n, seed):
    rnd = random.Random(seed)
    v = [sum((rnd.random() - rnd.random()) ** 2 for _ in range(D)) for _ in range(n)]
    m = sum(v) / n
    return math.sqrt(sum((x - m) ** 2 for x in v) / n) / m
```

```python tests
import math
assert abs(edge(0.01, 100) - 0.955) < 0.001 and abs(edge(0.01, 2) - 0.1) < 1e-12, "1% of the data: edges 0.1 in 2-D and 0.955 in 100-D."
assert abs(distance_spread(2, 20000, 1) - 6 * math.sqrt(7 / 180) / math.sqrt(2)) < 0.03, "In 2-D, distances vary by 84% of their mean."
assert abs(distance_spread(200, 4000, 2) - 6 * math.sqrt(7 / 180) / math.sqrt(200)) < 0.006, "In 200-D, by only 8%."
```

::: right
Right. The simulation follows $1.18/\sqrt D$: in high dimensions every pair of random points is about equally far apart.
:::
:::

::: explain
## Why do nearest-neighbor methods need so much more data as the number of features grows?

::: model
A nearest-neighbor prediction is only as good as the neighbors are similar to the input, which needs training examples close to every input it will see. To keep a neighborhood the same size in each feature while adding dimensions, the number of examples must multiply by a constant factor per dimension: data must grow exponentially. Otherwise the neighborhoods stretch until they span most of every feature's range, and distances to all points become nearly equal, so the nearest neighbor is barely more similar than a random one. Real data escape this only when they lie near a low-dimensional surface, which is why reducing dimension or learning features usually comes first.
:::
:::

::: practice
::: check
given: r = 0.01 | 0.1; D = 5 | 100
answer: r^(1/D)
tolerance: 0.5%

## Edge for a fraction {r} in {D} dimensions?

::: misses
- [any] $r^{1/D}$.
:::
:::

::: check
given: R = 0.01 | 0.02 | 0.05 | 0.1 | 0.15 | 0.25
answer: 2*R*(1 - R)
tolerance: 0.5%

## 1-NN limit for Bayes error {R}?

::: misses
- [any] $2R(1 - R)$.
:::
:::

::: check
given: K = 8 | 20; N = 1000 | 20000; r = 0.1 | 0.02
answer: K/(N*pi*r^2)
tolerance: 0.5%

## Planar density: K = {K}, N = {N}, radius {r}?

::: misses
- [any] $K/(N\pi r^2)$.
:::
:::
:::
