S14 · Lesson 18 · Nearest neighbors
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
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.
- 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.
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?
The smaller cube's volume must be 0.01, so its edge is = 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.
Name it
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
where 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,
Applied to each class with Bayes' theorem, this gives the k-NN classifier's posterior .
The curse of dimensionality
In D dimensions, a cube holding a fraction r of uniform data has edge , and the shell within ε of the surface of a unit cube holds 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 , 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.
Worked 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?
Show the solution
- Cover and Hart's bound. and at least 5%.
- 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.
- 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.
Worked 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?
Show the solution
- Disk area.
- Density.
- Search cost. multiply-adds, 12.8 ms per query.
- 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.
Worked example
For points uniform in a unit cube, how much do pairwise distances vary in 2, 10 and 1000 dimensions?
Show the solution
- One coordinate. A coordinate difference squared, , has mean 1/6 and variance 7/180.
- The whole distance. The squared distance has mean D/6 and standard deviation , a relative spread of
- Put in the dimensions. That's 0.84 in 2 dimensions, 0.37 in 10 and 0.037 in 1000.
- 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
Data are uniform in a 2-dimensional unit cube.
(a)
What edge length must a smaller cube have to hold a fraction 0.01 of them?
Check
A unit cube in 3 dimensions.
(a)
What fraction of its volume lies within 0.05 of its surface?
Check
A two-class problem has Bayes error 0.05.
(a)
What is the most error a 1-nearest-neighbor classifier can have with unlimited data?
Check
Among 500 points, the 10 nearest to x lie within radius 0.3.
(a)
Estimate the density at x if the points lie in a plane.
(b)
And if they lie in three dimensions?
Check
Pairs of points are drawn uniformly from a 10-dimensional unit cube.
(a)
What is the mean squared distance between them?
(b)
What is the squared distance's standard deviation relative to its mean?
Check
A service searches 10000 reference vectors of dimension 64 by brute force, answering 5000 queries a second.
(a)
How many multiply-adds per second does it need, in billions?
(b)
How much memory do the references take in 32-bit floats, for 50 copies?
Check
Why should features be standardized before using a nearest-neighbor classifier?
Check
Data are uniform in a D-dimensional unit cube.
Step 1
What edge does a cube holding a fraction r of them need?
Type it the way you would write it, like 3sin(2πft) or 3*sin(2*pi*f*t). Angles can be in radians or carry a degree sign, like 45°.
Step 2
What fraction of the volume lies within e of the surface?
Check
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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
Why do nearest-neighbor methods need so much more data as the number of features grows?
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
Keep practicing
9 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.