Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Nearest Neighbors

Open in Colab

Given a point cloud, or data set XX, and a distance dd, a common computation is to find the nearest neighbors of a target point xx, meaning points xi∈Xx_i \in X which are closest to xx as measured by the distance dd.

Nearest neighbor queries typically come in two flavors:

  1. Find the k nearest neighbors to a point x in a data set X

  2. Find all points within distance r from a point x in a data set X

There is an easy solution to both these problems, which is to do a brute-force computation

Brute Force Solution

<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>

Exercise

What is the time complexity of both the above functions?


show your work

KD-trees

One of the issues with a brute force solution is that performing a nearest-neighbor query takes O(n)O(n) time, where nn is the number of points in the data set. This can become a big computational bottleneck for applications where many nearest neighbor queries are necessary (e.g. building a nearest neighbor graph), or speed is important (e.g. database retrieval)

A kd-tree, or k-dimensional tree is a data structure that can speed up nearest neighbor queries considerably. They work by recursively partitioning dd-dimensional data using hyperplanes.

scipy.spatial provides both KDTree (native Python) and cKDTree (C++). Note that these are for computing Euclidean nearest neighbors

<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>

cKDTrees have the same methods

<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>

Performance Comparision

brute force: 0.0029163360595703125 sec
KDTree: 0.4510629177093506 sec
  extra query: 0.002267599105834961 sec
cKDTree: 0.05318927764892578 sec
  extra query: 0.0001647472381591797 sec

Ball trees

If you want to do nearest neighbor queries using a metric other than Euclidean, you can use a ball tree. Scikit learn has an implementation in sklearn.neighbors.BallTree.

KDTrees take advantage of some special structure of Euclidean space. Ball Trees just rely on the triangle inequality, and can be used with any metric.

The list of built-in metrics you can use with BallTree are listed under sklearn.neighbors.DistanceMetric

for a k-nearest neighbors query, you can use the query method:

<Figure size 432x288 with 1 Axes>

for r-nearest neighbors, you use query_radius instead of query_ball_point.

<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>

Exercises

  1. Compare the performance of KDTree, cKDTree, and BallTree for doing nearest neighbors queries in the Euclidean metric

  2. Scikit learn also has a KDTree implementation: sklearn.neighbors.KDTree - how does this compare to the KDTree implementations in scipy?