Sub topic 11
Making neighbour search fast: KD-trees and ball trees
This chapter assumes you know how k-NN predicts from the k closest training points, how Euclidean, Manhattan and Minkowski distances work, and why high dimensions hurt neighbour quality. It covers how scikit-learn answers neighbour queries quickly, when the speedup works, and when it doesn't.
Why brute force becomes the bottleneck
k-NN has no fitting step, so all the cost lands at prediction time. The brute-force search from earlier in this tutorial computes the distance from the query to every stored point. With n training points and d features, one query costs about O(n·d) operations, plus selecting the k smallest. Predicting for m queries costs O(m·n·d).
For a few thousand points this is fine. At a million points with 20 features, each query touches 20 million numbers. A service that must answer in milliseconds can't afford that.
Tree-based search avoids most of that work. It organises the training points once, then uses that structure to rule out whole groups of points without computing their distances. The answer is still exact: you get the same neighbours as brute force.
KD-trees
A KD-tree (k-dimensional tree) is a binary tree that recursively cuts the feature space with axis-aligned planes.
Building the tree
- Pick a feature (axis). A common rule is the axis with the largest spread in the current subset.
- Split the points at the median value of that axis. Half go left, half go right.
- Repeat on each half until a subset has at most
leaf_sizepoints. That subset becomes a leaf.
Because each split uses the median, the tree is balanced. Its depth is about log₂(n / leaf_size). Building costs roughly O(n log n).
Querying the tree
To find the k nearest neighbours of a query point q, the search keeps a list of the best k candidates found so far. The distance to the worst of them, call it r, is the current search radius.
- Descend from the root to the leaf whose region contains q. Compute distances to the points in that leaf and fill the candidate list.
- Walk back up the tree. At each node, measure the distance from q to the splitting plane.
- If that distance is larger than r, the other side of the plane can't contain a closer point, so skip that whole subtree. Otherwise, search it too.
In low dimensions, pruning removes most of the tree. A typical query then costs about O(log n) instead of O(n). In high dimensions the pruning test almost never succeeds, and the search degrades toward brute force.
Ball trees
A ball tree groups points into nested hyperspheres ("balls") instead of axis-aligned boxes. Each node stores a centre c and a radius ρ, chosen so that every point in the node lies within ρ of c.
Building splits the points into two groups, usually around two far-apart points, and wraps each group in its own ball. This is more work than a KD-tree build, but the structure adapts better to how the data is spread.
Pruning uses the triangle inequality. For any point p inside a ball, the distance from q to p is at least dist(q, c) - ρ. If that lower bound is already larger than the current k-th best distance r, the whole ball is skipped.
Two consequences matter in practice:
- Balls follow the data's shape. When points cluster along a lower-dimensional surface inside a high-dimensional space, ball trees often prune better than KD-trees.
- The pruning argument needs only a true metric (non-negative, symmetric, satisfying the triangle inequality). A ball tree therefore works with many more metrics than a KD-tree, such as Haversine distance for latitude and longitude.
Comparing the three strategies
| Property | Brute force | KD-tree | Ball tree |
|---|---|---|---|
| Build cost | None | About O(n log n) | About O(n log n), higher constant |
| Query cost, low d | O(n·d) | About O(log n) | About O(log n) |
| Query cost, high d | O(n·d) | Approaches O(n·d) or worse | Approaches O(n·d) or worse |
| Extra memory | None | Tree over the data | Tree over the data |
| Metrics | Any, including sparse input and custom functions | Minkowski family (Euclidean, Manhattan, Chebyshev) | Many metrics, including Haversine |
| Exact results | Yes | Yes | Yes |
A common rule of thumb is that trees pay off up to roughly 15 to 20 features. Beyond that, the overhead of walking the tree often makes it slower than a vectorised brute-force scan.
Using the structures in scikit-learn
NearestNeighbors exposes the search without any classification on top. KNeighborsClassifier and KNeighborsRegressor accept the same algorithm argument.
import numpy as np
from sklearn.neighbors import NearestNeighbors
rng = np.random.default_rng(0)
X = rng.random((1000, 3))
queries = rng.random((2, 3))
nn = NearestNeighbors(n_neighbors=3, algorithm="kd_tree").fit(X)
distances, indices = nn.kneighbors(queries)
print(distances.shape, indices.shape) # (2, 3) (2, 3)fit builds the tree once. Each row of distances holds the distances to that query's three closest training points, sorted ascending. The matching row of indices holds the row numbers of those points in X.
The algorithm parameter accepts "auto", "brute", "kd_tree" and "ball_tree". With "auto", scikit-learn picks brute force for sparse input, for many features (about 15 or more), or when k is a large fraction of n. Otherwise it picks a tree. The exact rule has changed between versions, so check the documentation for your installed release.
The leaf_size parameter (default 30) sets where tree splitting stops. A small value gives a deeper tree with finer pruning but more memory and more node-visiting overhead. A large value gives a shallower tree that falls back to brute force inside bigger leaves. The best value depends on your data, and it only affects speed and memory, never the results.
Measuring the speedup yourself
The following script times all three algorithms at three dimensionalities, and checks that every algorithm returns the same neighbours as brute force.
import time
import numpy as np
from sklearn.neighbors import NearestNeighbors
def run(d, n=20_000, n_queries=500, k=5):
rng = np.random.default_rng(0)
X = rng.random((n, d))
queries = rng.random((n_queries, d))
reference = None
for algo in ("brute", "kd_tree", "ball_tree"):
t0 = time.perf_counter()
nn = NearestNeighbors(n_neighbors=k, algorithm=algo).fit(X)
t1 = time.perf_counter()
_, idx = nn.kneighbors(queries)
t2 = time.perf_counter()
if reference is None:
reference = idx
same = np.array_equal(idx, reference)
print(
f"d={d:>3} {algo:<9} build={t1 - t0:.3f}s "
f"query={t2 - t1:.3f}s same_as_brute={same}"
)
for d in (3, 10, 50):
run(d)Expect the trees to win clearly at d=3, to show a smaller gap at d=10, and to lose their advantage at d=50. Exact timings depend on your machine and library version, so run it rather than trusting a fixed number. The same_as_brute column should read True throughout. Uniform random floats make exact distance ties very unlikely, so the index arrays match.
Edge cases and failure modes
- High dimensions. As covered in the curse of dimensionality chapter, distances to the nearest and farthest points become similar. The pruning test then rarely rejects anything. Trees give no benefit, and their build time and memory are wasted.
- Intrinsic versus ambient dimension. What matters is how many dimensions the data effectively occupies. 100 features that are mostly correlated can behave like 5, and trees may still help. Pixel data or one-hot features often behave worse than their raw count suggests.
- Unsupported metrics. KD-trees need axis-aligned bounds, so they only support the Minkowski family. Cosine distance does not satisfy the triangle inequality, so tree pruning is not valid for it. For cosine similarity, either use
algorithm="brute", or L2-normalise the vectors and use Euclidean distance. For unit vectors, Euclidean distance orders points the same way as cosine distance. - Static structure. The tree is built for the data present at
fittime. Adding a point means refitting, so trees suit read-heavy workloads over fixed datasets. - Small query batches on small data. Brute force uses highly optimised vectorised code. For a few thousand points, it can beat a tree even in 3 dimensions.
- Many duplicate points. If a large cluster of identical points exceeds
leaf_size, the tree cannot separate them with a split. The result is deep chains or oversized leaves. Deduplicating the data first can help.
Decision criteria
- If you have fewer than a few thousand points, or sparse input, use brute force.
- If you have fewer than about 15 to 20 effective dimensions and use a Minkowski metric, try a KD-tree.
- If you have a non-Minkowski metric such as Haversine, or data lying on a low-dimensional structure, try a ball tree.
- If you have high-dimensional data and millions of points, exact trees won't scale. Approximate nearest-neighbour search, covered in the next chapter, trades a small chance of missing a true neighbour for large speedups.
Exercise
A dataset has 200,000 points with 60 features and you use Euclidean distance. A colleague proposes switching algorithm from "brute" to "kd_tree" to speed up queries. What do you expect to happen, and what two things would you check before deciding?
Show answer
With 60 features, distances concentrate and the pruning test rarely rejects subtrees, so the KD-tree will probably visit most of the data and may be slower than brute force, while also costing build time and memory. First, estimate the data's effective (intrinsic) dimension, for example by checking how much variance a few principal components capture. If it is low, trees may still help. Second, benchmark both algorithms on realistic query batches and compare query time, confirming the neighbours are the same. If neither is fast enough, consider approximate nearest-neighbour search.
Exercise
Why can a ball tree use the Haversine metric, while a KD-tree cannot?
Show answer
A ball tree prunes with the triangle inequality, using the lower bound dist(q, centre) minus radius, so it only needs a valid metric. Haversine distance is a valid metric. A KD-tree prunes by comparing the distance to an axis-aligned splitting plane, which only makes sense for Minkowski-family distances computed coordinate by coordinate.