Sub topic 13
Why k-d trees degrade in high dimensions
This chapter assumes you can read the k-d tree build and nearest-neighbor code from earlier chapters. It also assumes you know Big-O notation and Euclidean distance.
The symptom
A k-d tree answers nearest-neighbor queries in about O(log n) time on average when the dimension k is small, such as 2 or 3. As k grows, queries visit more and more of the tree. At some point they visit nearly every node, and the tree costs more than a linear scan because of the recursion overhead.
A common rule of thumb is that a k-d tree helps only when n is much larger than 2^k. With k = 20, that means far more than a million points.
Cause 1: the tree runs out of depth
A balanced tree over n points has about log2(n) levels. Axes rotate with depth, so each axis gets about log2(n) / k splits.
With n = 1,000,000, the depth is about 20. In 2 dimensions, each axis is split about 10 times. In 20 dimensions, each axis is split about once. Most coordinates are therefore barely used to separate points, and the cells stay long and thin.
Cause 2: pruning stops working
The search visits the far child only when diff * diff < best[0]. Here diff is the distance from the query to the splitting plane, and best[0] is the squared distance to the best match so far.
In high dimensions, distances concentrate. For random points, the nearest neighbor is not much closer than a typical point. So the best distance stays large, and a ball of that radius around the query crosses many splitting planes. Each crossing forces a visit to the far side.
Measuring it
This script builds trees over uniform random points and reports the average share of nodes a nearest-neighbor query visits.
import random
def build(points, depth=0):
if not points:
return None
axis = depth % len(points[0])
points = sorted(points, key=lambda p: p[axis])
mid = len(points) // 2
return (points[mid], axis,
build(points[:mid], depth + 1),
build(points[mid + 1:], depth + 1))
def nearest(node, target, best, visited):
if node is None:
return best
point, axis, left, right = node
visited[0] += 1
d2 = sum((a - b) ** 2 for a, b in zip(point, target))
if d2 < best[0]:
best = (d2, point)
diff = target[axis] - point[axis]
near, far = (left, right) if diff < 0 else (right, left)
best = nearest(near, target, best, visited)
if diff * diff < best[0]:
best = nearest(far, target, best, visited)
return best
random.seed(1)
n = 5000
for k in (2, 8, 16):
pts = [tuple(random.random() for _ in range(k)) for _ in range(n)]
tree = build(pts)
total = 0
for _ in range(20):
q = tuple(random.random() for _ in range(k))
visited = [0]
nearest(tree, q, (float("inf"), None), visited)
total += visited[0]
print(k, round(total / 20 / n * 100), "% of nodes visited")For k = 2, the share is tiny. For k = 16 with only 5,000 points, it climbs toward 100%. The exact numbers depend on the random seed, but the trend does not.
What to do instead
- Reduce the dimension first, for example with PCA, if the data is correlated.
- Use approximate nearest-neighbor search, which accepts a result within a small factor of the true nearest distance in exchange for much less work. Libraries such as FAISS, Annoy, and HNSW-based tools do this.
- Use a ball tree or a vantage-point tree. They split by distance rather than by coordinate axis, so they handle moderate dimensions somewhat better. They still degrade eventually.
- Fall back to a vectorized linear scan when n is small or k is large. It is simple and often faster.
Exercise
A k-d tree holds 1,000,000 points in 30 dimensions. Roughly how many times is each axis split along a root-to-leaf path, and what does this imply for nearest-neighbor queries?
Show answer
The depth is about log2(1,000,000), roughly 20, and 20 / 30 is less than 1. Many axes are never split at all, so the cells are not tight in those directions. Together with distance concentration, the search ball crosses many splitting planes, and queries visit a large share of the nodes. Expect little or no gain over a linear scan.