Sub topic 11
Making neighbour search fast: KD-trees and ball trees
This chapter assumes you know how k-NN predicts from distances and why high dimensions hurt neighbour quality. Here we look at how to find the neighbours quickly.
Why brute force gets slow
k-NN has no fitting step, so all the work happens at query time. The from-scratch classifier computes the distance from the query to every training point. With n points and d features, one query costs about O(n·d) operations. Predicting for m queries costs O(m·n·d).
That is fine for thousands of points. It is too slow for millions of points, or for a service that must answer each query in milliseconds. Tree structures reduce the cost by letting a search skip whole regions of space that cannot hold a nearest neighbour.
KD-trees
A KD-tree (k-dimensional tree) splits the data recursively with axis-aligned cuts.
- Pick a feature, usually the one with the widest spread.
- Split the points at the median value of that feature.
- Repeat on each half until a node holds only a few points (the leaf size).
To answer a query, the search walks down to the leaf containing the query and treats the points there as the current best. It then backtracks. A branch is visited only if the splitting plane is closer to the query than the current k-th best distance. Otherwise nothing in that branch can beat the current neighbours, so it is pruned.
In low dimensions a query costs roughly O(log n). Pruning works because the search ball around the query is small compared with the data.
Ball trees
A ball tree groups points into nested hyperspheres (balls). Each node stores a centre and a radius that covers all its points. If the distance from the query to a ball's centre, minus the radius, is larger than the current k-th best distance, the whole ball is skipped.
Balls adapt to the shape of the data and are not tied to the coordinate axes. Ball trees usually hold up better than KD-trees as dimensionality grows, and they support more distance metrics. Building them costs more.
Using the trees in scikit-learn
NearestNeighbors builds the index once and then answers queries.
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)Both outputs have one row per query and one column per neighbour. distances holds the distances. indices holds positions in the training set, so you can look up labels with y_train[indices].
The algorithm parameter accepts "brute", "kd_tree", "ball_tree" and "auto". The default "auto" picks a method from the data, and it is a sensible starting point. KNeighborsClassifier and KNeighborsRegressor take the same parameter, and they have a leaf_size option that sets how many points a leaf holds.
Choosing a search method
| Method | Build cost | Works best when | Weakness |
|---|---|---|---|
| Brute force | None | Small n, high d, or few queries | Cost grows linearly with n for every query |
| KD-tree | Low | Low d (roughly under 20), many queries | Pruning fails in high d |
| Ball tree | Higher | Moderate d, structured data, other metrics | Slower to build than a KD-tree |
Common errors
- Expecting a speedup on a single query. Building the tree costs time. It pays off when you answer many queries against the same data.
- Using trees on sparse or very wide data. Brute force is often faster in these cases.
- Forgetting that the index is static. Adding training points means rebuilding the tree.
- Skipping the benchmark. The best choice depends on n, d and your data's structure. Time
kneighborson a sample of your own data.
Exercise
You have 2 million training points with 300 features and need neighbours for a few queries per day. Would you build a KD-tree? Why or why not?
Show answer
Probably not. With 300 features, a KD-tree can prune very few branches, so it behaves close to brute force and still costs time to build. With only a few queries per day, the build cost is not repaid. Use brute force, or approximate search if query volume grows.