Algorithm Search⌘K

Data structureadvanced

Randomized k-d forest

Also called randomized kd-trees, FLANN kd-forest.

Several k-d trees that split on dimensions chosen at random among those of highest variance, searched together through one priority queue for approximate neighbors.

Time
O(T d n h) buildO(T (h + d)) insertO(T C h (d + log(T C h)) + C log k) search
Space
O(T n + n d) total
Where
C = the number of points to check; T = the number of trees; d = the dimension; h = the height of a tree; k = the number of neighbors; n = the number of points
Properties
anytimedynamicnot exactexact when unboundedrandomized
Origin
Chanop Silpa Anan, Richard Hartley, Marius Muja, David G. Lowe, 2008

A randomized k-d forest is an index for approximate nearest neighbor search that holds TT k-d trees over the same points. Each tree splits a node on a dimension drawn at random from the few dimensions where its points vary most, so the trees cut space in different ways. A search runs best bin first on all trees at once with one priority queue and checks each point at most once. A point that one tree puts in a far bin is often in a near bin of another tree, so with the same number of checks the forest finds the true neighbor more often than one tree. Silpa-Anan and Hartley (2008) and Muja and Lowe (2009) built it for matching SIFT descriptors, and it is the default index of the FLANN library.

In plain words

One k-d tree cuts space into boxes. If the true nearest point sits just over the edge of the box of the query, the search may have to look at many boxes before it finds it. Now build four trees, each with its own random choice of cuts. The edges are in different places in each tree, so the true neighbor is likely close to the query box in at least one of them. The search keeps one list of boxes from all four trees, sorted by distance from the query, and always opens the closest box. It remembers which points it has already measured, so no point is measured twice. It stops after a fixed number of points.

The abstract type

The forest stores a set of points in Rd\mathbb{R}^d and supports:

  • BUILD(P): make the forest for a set of points.
  • INSERT(x): add a point.
  • SEARCH(q, k, C): return kk points close to qq, after at most about CC distance computations, and say whether the answer is proved exact.

With C=∞C = \infty, SEARCH returns the exact k nearest neighbors. With a finite CC it is an approximate nearest neighbor search with no bound on the error. Distances are Euclidean.

Representation

Each tree is a binary tree. An internal node holds a dimension jj and a split value ss. Points with xj<sx_j < s go to the left child and points with xj≥sx_j \ge s go to the right child. A leaf holds the indices of at most ℓ\ell points, or any number of equal points. FLANN uses ℓ=1\ell = 1. The points themselves are stored once, in an array that all trees share.

The split rule is the random part. At a node with point set SS, compute the mean mtm_t and the variance of each dimension tt over SS. Take the DD dimensions of largest variance, draw one of them, jj, uniformly at random, and split at s=mjs = m_j. Muja and Lowe use D=5D = 5. FLANN estimates the mean and the variance from a sample of the first 100 points of the node and uses 4 trees by default; our code uses all points of the node.

Operations

  1. BUILD(P, T, D)
  2. 1for t = 1 to T do root_t ← MAKE(all indices of P)
  3. MAKE(S)
  4. 2if |S| ≤ ℓ or all points of S are equal then return a leaf holding S
  5. 3compute the mean m_t and the variance v_t of each dimension t over S
  6. 4K ← the D dimensions with the largest v_t > 0
  7. 5j ← a dimension drawn uniformly at random from K
  8. 6L ← {i ∈ S : x_ij < m_j}; R ← S \ L
  9. 7return a node with dimension j, split m_j and children MAKE(L) and MAKE(R)
  1. INSERT(x)
  2. 1store x with a new index i
  3. 2for each tree t do
  4. 3go down from root_t: left if x_j < s, else right, until a leaf
  5. 4add i to the leaf
  6. 5if the leaf has more than ℓ points then replace it by MAKE(its indices)
  1. SEARCH(q, k, C)
  2. 1best ← empty list of at most k (distance, index) pairs; seen ← empty set; checked ← 0
  3. 2Q ← min-priority queue holding (0, root_t, zero offsets) for each tree t
  4. 3while Q is not empty and checked < C do
  5. 4(b, node, o) ← remove the entry with the smallest key from Q
  6. 5if best has k items and b ≥ the largest distance in best then stop: the answer is exact
  7. 6while node is an internal node do
  8. 7j ← dimension of node; δ ← q_j - split of node
  9. 8if δ < 0 then near, far ← left, right else near, far ← right, left
  10. 9insert (b - o_j^2 + δ^2, far, o with o_j = δ) into Q
  11. 10node ← near
  12. 11for each index i in the leaf with i ∉ seen do
  13. 12add i to seen; checked ← checked + 1; put (‖x_i - q‖^2, i) in best if it is among the k closest
  14. 13return best

The key bb of a queue entry is the squared distance from qq to the bin of its subtree, with the offset vector oo as in best bin first search. Line L21 replaces the offset of dimension jj; it does not add to it. The shared queue of line L14 is what makes the trees work together: the next bin is the closest one in any tree. The set of line L23 keeps a point that sits in near bins of several trees from being counted several times.

Example

Take the eight points (1,1)(1,1), (2,6)(2,6), (3,3)(3,3), (5,8)(5,8), (6,2)(6,2), (7,6)(7,6), (8,4)(8,4), (9,9)(9,9), with T=2T = 2, D=2D = 2, ℓ=1\ell = 1 and seed 5 in our code. The variances are 7.36 for xx and 7.11 for yy, and the means are 5.125 and 4.875. Tree 1 drew yy at the root and splits at y=4.875y = 4.875; tree 2 drew xx and splits at x=5.125x = 5.125. The query is q=(5.2,4.6)q = (5.2, 4.6). Its nearest neighbor is (7,6)(7, 6) at squared distance 5.2, and the next one is (3,3)(3,3) or (6,2)(6, 2) at 7.4.

The search with a budget of C=2C = 2 checks:

  1. The queue holds both roots with key 0. It pops the root of tree 1. At y<4.875y < 4.875 the query goes left, δ=−0.275\delta = -0.275, and the right subtree gets key 0.07560.0756. At y<2.5y < 2.5 it goes right and pushes the left subtree with key 2.12=4.412.1^2 = 4.41. At y<3.5y < 3.5 it goes right to the leaf (8,4)(8, 4), at squared distance 8.2, and pushes (3,3)(3,3) with key 1.12=1.211.1^2 = 1.21. One check.
  2. The smallest key is now the root of tree 2, with 0. At x<5.125x < 5.125 the query goes right, δ=0.075\delta = 0.075, and pushes the left subtree with key 0.00560.0056. At x<7.5x < 7.5 it goes left and pushes the right subtree with key 2.32=5.292.3^2 = 5.29. At y<4y < 4 it goes right to the leaf (7,6)(7, 6), at squared distance 5.2. Two checks, and the search stops.

The forest returns (7,6)(7, 6), the true neighbor. Tree 1 alone with the same budget pops its key 0.0756 next, reaches the leaf (5,8)(5, 8) at 11.6, and returns (8,4)(8, 4) at 8.2; it needs a third check to reach (7,6)(7, 6). The answer of the forest is not yet proved exact: the queue still holds a key of 0.0056, which is less than 5.2.

A measured example: we built the forest in our code on 5000 points uniform in [0,1]16[0, 1]^{16} with seed 11 and ran 100 uniform queries. The table gives the number of queries, out of 100, whose true nearest neighbor was returned.

trees C=50C = 50 C=200C = 200 C=800C = 800
1 65 89 100
4 71 92 100
8 76 92 100

On this uniform data the gain from more trees is small. Silpa-Anan and Hartley and Muja and Lowe report larger gains on real SIFT descriptors. These are measurements, and they depend on the data.

Correctness

The proof in proofs/correctness.md shows these facts:

  • Every tree indexes every point. After BUILD and after each INSERT, each index is in exactly one leaf of each tree, and each point lies in the cell of its leaf. MAKE ends because a dimension with positive variance always has points on both sides of its mean.
  • The key is a lower bound. Every point in the subtree of a queue entry is at squared distance at least its key from qq.
  • One check per point. No distance is computed twice in one search.
  • Exact when it stops by itself. If the queue empties or line L17 stops the loop, the answer is the exact kk nearest neighbors.
  • More checks do not hurt. A larger budget never returns a worse ii-th neighbor.

That several random trees beat one tree at the same budget is a measured result, not a theorem.

Proof: Correctness of the randomized k-d forestfull

The forest holds a list of points x(1),…,x(n)x^{(1)}, \dots, x^{(n)} in Rd\mathbb{R}^d and TT trees. A node is a leaf with a list of point indices, or an internal node with a dimension jj, a split value ss and two children. The cell of a node is the set of x∈Rdx \in \mathbb{R}^d that satisfy xj<sx_j < s for each ancestor where the path goes left and xj≥sx_j \ge s for each ancestor where it goes right. Distances are squared Euclidean distances to the query qq, D(x)=∥x−q∥2D(x) = \lVert x - q \rVert^2.

Invariant. In each tree, every index 1,…,n1, \dots, n is in exactly one leaf, and every point is in the cell of its leaf. Each leaf has at most ℓ\ell points (the leaf size), or only equal points.

Lemma 1 (MAKE ends and keeps the invariant). Called on a nonempty list SS of indices whose points lie in the cell of the node, lines L2 to L7 end, and they produce a subtree whose leaves partition SS and in which every point is in the cell of its leaf.

Proof. By induction on ∣S∣|S|. If line L2 makes a leaf, the claim holds, because the points of SS lie in the cell. Else some dimension has positive variance, so line L4 has a candidate and line L5 picks a dimension jj with variance >0> 0 and mean mm. A dimension with positive variance has a value below its mean and a value at least its mean, so both lists of line L6 are nonempty in exact arithmetic. If rounding makes one empty, the code splits below the largest value, and since the values are not all equal, both sides are again nonempty. So both lists are smaller than SS. A point ii goes left exactly when xj(i)<sx^{(i)}_j < s, which is the condition of the cell of the left child, and right exactly when xj(i)≥sx^{(i)}_j \ge s. The two lists partition SS, and the induction hypothesis applies to each. □\square

Lemma 2 (BUILD and INSERT keep the invariant). After line L1, and after each call of INSERT, the invariant holds for each tree.

Proof. Line L1 calls MAKE on all indices at the root, whose cell is Rd\mathbb{R}^d, so Lemma 1 gives the invariant. For INSERT of a point xx with new index ii: line L10 goes left exactly when xj<sx_j < s, so the leaf it reaches has xx in its cell. Line L11 adds ii to that leaf only, so ii is in exactly one leaf. If the leaf now has more than ℓ\ell points, line L12 calls MAKE on its indices, whose points all lie in its cell, and Lemma 1 replaces the leaf by a subtree whose leaves partition the same indices and respect the cells. Other leaves do not change. □\square

Lemma 3 (the key is a lower bound). For each queue entry (b,v,o)(b, v, o) of SEARCH, b=∑tot2b = \sum_t o_t^2 and every point xx in the cell of vv has ∣xt−qt∣≥∣ot∣|x_t - q_t| \ge |o_t| for each tt. Hence every point stored in the subtree of vv has D(x)≥bD(x) \ge b.

Proof. Line L14 puts each root with b=0b = 0 and o=0o = 0, and the claim holds. The walk of lines L18 to L22 from a popped entry keeps bb and oo, and the cells along the walk are subsets of the cell of vv. At a node with dimension jj and split ss, let δ=qj−s\delta = q_j - s. Line L21 pushes the far child with oj′=δo'_j = \delta, the other offsets unchanged, and b′=b−oj2+δ2=∑tot′2b' = b - o_j^2 + \delta^2 = \sum_t o_t'^2. If δ<0\delta < 0, the far child is the right child, whose cell has xj≥s>qjx_j \ge s > q_j, so ∣xj−qj∣≥s−qj=∣δ∣|x_j - q_j| \ge s - q_j = |\delta|. If δ≥0\delta \ge 0, the far child is the left child, whose cell has xj<s≤qjx_j < s \le q_j, so ∣xj−qj∣>qj−s=δ|x_j - q_j| > q_j - s = \delta. For t≠jt \ne j the bound is inherited. By the invariant, each stored point of a subtree lies in the cell of its leaf, which is inside the cell of vv. □\square

Lemma 4 (the partition of each tree). At each test of line L15, for each tree, every leaf of the tree is either a leaf that line L23 has reached or a leaf in the subtree of exactly one queue entry.

Proof. The same as for a single tree: line L14 covers each tree by its root, and each pop at line L16 removes one subtree, which the walk splits into the pushed far subtrees and one reached leaf. □\square

Lemma 5 (one check per point). Line L24 computes the distance of each point at most once per search, so the number of distance computations is at most min⁡(n,C+ℓ′)\min(n, C + \ell') for a budget CC, where ℓ′\ell' is the size of the largest leaf.

Proof. Line L23 skips an index that is in the set of seen points, and line L24 adds an index to the set before it computes its distance. The test of line L15 is made before each leaf, so the count passes CC by less than one leaf. □\square

Theorem 1 (exact answer). If SEARCH ends because the queue is empty or because of line L17, it returns the kk smallest distances over all stored points, or all of them if n<kn < k.

Proof. The list keeps the min⁡(k,m)\min(k, m) smallest distances among the mm seen points, by the standard bounded selection with a max-heap. If the queue is empty, Lemma 4 says that each tree has reached all its leaves, so all points are seen. If line L17 stops the loop, let bb be the popped key and r≤br \le b the largest distance in the list. Take a point xx that has not been seen. Pick any tree. By the invariant, xx is in one leaf of that tree, and that leaf has not been reached, since reaching it would have marked xx as seen. By Lemma 4 that leaf is in the subtree of a queue entry or of the popped entry, whose key is at least bb because the queue is a min-priority queue. By Lemma 3, D(x)≥b≥rD(x) \ge b \ge r. So no unseen point is closer than the kk-th item of the list. □\square

Theorem 2 (more checks do not hurt). For budgets C<C′C < C' and the same forest and query, the ii-th distance returned with C′C' is at most the ii-th distance returned with CC.

Proof. The steps of SEARCH depend on the budget only through the test at line L15. So the run with CC is a prefix of the run with C′C', and it sees a subset of the points. The ii-th smallest value of a superset is at most that of the subset. □\square

What is not proved. Nothing above bounds the error when the budget stops the search. The claim that several randomized trees find the true neighbor more often than one tree at the same number of checks is a measured result of Silpa-Anan and Hartley and of Muja and Lowe, and the example on the main page is also a measurement. ■\blacksquare

Complexity

The model is the real RAM. Let hh be the largest height of a tree. With mean splits the trees are not always balanced: for points with coordinates 1,2,4,8,…1, 2, 4, 8, \dots each mean split puts one point on the right, and h=n−1h = n - 1. On typical descriptor data hh is close to log⁡2n\log_2 n.

  • Build. Each level of a tree computes dd means and variances over at most nn points, so one tree costs O(dnh)O(d n h) and the forest O(Tdnh)O(T d n h). Sorting the variances adds O(dlog⁡d)O(d \log d) per node. FLANN's sample of 100 points makes the statistics O(d)O(d) per node.
  • Insert. One descent of length hh per tree, and a split of a leaf of ℓ+1\ell + 1 points at O(dℓ)O(d \ell), so O(T(h+d))O(T (h + d)) for a constant ℓ\ell.
  • Search. With ℓ=1\ell = 1, each tree reaches each leaf at most once, and a leaf whose point was already seen does not count as a check. So the search reaches at most T(C+1)T (C + 1) leaves. Each leaf costs one descent of at most hh pushes of O(d+log⁡(queue size))O(d + \log(\text{queue size})), and each check costs O(d+log⁡k)O(d + \log k). The total is O(TCh(d+log⁡(TCh))+Clog⁡k)O(T C h (d + \log(T C h)) + C \log k). In practice most reached leaves are new, and the cost is close to that of CC leaves of one tree.
  • Space. O(Tn)O(T n) nodes and O(nd)O(n d) for the points, which all trees share.

Variants

  • Rotated data. Silpa-Anan and Hartley also studied trees built on rotated copies of the data, so that the trees differ by their axes and not only by the random split.
  • Priority search k-means tree. Muja and Lowe (2009, 2014) offer a tree that splits by k-means clustering, and an automatic choice between the two indexes and their parameters for a given data set and target precision.
  • Random projection trees. The RP tree splits on a random direction instead of a coordinate axis.
  • Other indexes. Locality-sensitive hashing and graph indexes such as HNSW are the common alternatives in high dimension.
  • Random forests. The name is shared with the random forest classifier, which also builds trees with random splits, but for a different task.

When to use it

Use a randomized k-d forest to match many descriptors of moderate dimension, such as 128-value SIFT vectors, when an approximate answer is acceptable and a later step such as the ratio test or RANSAC removes wrong matches. Set the budget CC for the precision you need; Muja and Lowe tune the number of trees and CC on a sample of the data. For binary descriptors use Hamming distance and an index made for it, such as multi-probe LSH. For very large sets, graph indexes or product quantization often give a better trade of memory and speed.

Pitfalls

  • An overestimated key. The key must not exceed the distance to the bin. In the FLANN code the key of a far child is the parent key plus δ2\delta^2, and a comment there says that it does not correct for an earlier split on the same dimension. Such a key can be too large, and a rule that prunes a bin when its key exceeds the current kk-th distance can then skip a bin that holds a closer point. Line L21 replaces the old offset to avoid this.
  • Counting checks. A budget in checked points and a budget in reached leaves differ when leaves hold several points or when points are reached in several trees. Report which one you use.
  • Equal points. A set of equal points has zero variance in every dimension. Keep it in one leaf, or MAKE does not end.
  • Unbalanced trees. Mean splits on skewed data can give deep trees. A median split keeps the height at ⌈log⁡2n⌉\lceil \log_2 n \rceil but changes the trees.
  • Seeds. The trees depend on the random generator. Fix the seed to make the index and the results repeatable.
  • Distance. The bin distance is for Euclidean distance. Another metric needs another lower bound.

Implementations

The Python code in impl/python/randomized_kd_forest.py is a class with BUILD, INSERT, SEARCH and a check of the invariant. SEARCH uses the replaced offset of line L21, a set of seen points, a budget in checked points and the exact stop rule of line L17. The tests compare searches with no budget against a brute force scan after random sequences of inserts and queries, check the invariant, check that each point is measured at most once, check that a larger budget never gives a worse answer, and check that the split dimension is among the top DD by variance.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

randomized_kd_forest.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-kd-forest/. The authors are listed in prov/GS7MJP.jsonl.

"""A randomized k-d forest (Silpa-Anan and Hartley 2008, Muja and Lowe 2009).

Points are tuples of floats of the same dimension d. The forest holds T k-d
trees over the same points. Each internal node splits at the mean of one
dimension, drawn uniformly at random from the D dimensions of largest
variance of its points (D = 5 in FLANN). Points with x[j] < mean go left,
the others go right. A leaf holds at most `leaf_size` points, or any number
of equal points.

FLANN estimates the mean and the variance from the first 100 points of a
node; this code uses all the points of the node, which changes the trees but
not the method.

The search keeps one min-priority queue for all trees, keyed by the squared
distance from the query to the bin of each subtree. A set of seen points
makes sure that each point is checked once, even if it is reached in several
trees. The search stops after `checks` points, or when the next bin is not
closer than the current k-th neighbor; in the second case the answer is
exact. The bin distance replaces the offset of a dimension when the path
crosses a second split on it, so it is a true lower bound.
"""

import heapq
import math
import random
from typing import List, Optional, Sequence, Tuple

Point = Tuple[float, ...]


class Node:
    __slots__ = ("dim", "split", "left", "right", "ids")

    def __init__(self):
        self.dim = -1  # -1 for a leaf
        self.split = 0.0
        self.left: Optional["Node"] = None
        self.right: Optional["Node"] = None
        self.ids: List[int] = []


def sqdist(p: Sequence[float], q: Sequence[float]) -> float:
    return sum((a - b) * (a - b) for a, b in zip(p, q))


class RandomizedKDForest:
    def __init__(self, points: Sequence[Point] = (), trees: int = 4, top_dims: int = 5,
                 leaf_size: int = 1, seed: int = 0, dim: Optional[int] = None):
        if trees < 1 or top_dims < 1 or leaf_size < 1:
            raise ValueError("trees, top_dims and leaf_size must be at least 1")
        self.points: List[Point] = [tuple(p) for p in points]
        self.dim = dim if dim is not None else (len(self.points[0]) if self.points else 0)
        self.top_dims = top_dims
        self.leaf_size = leaf_size
        self.rng = random.Random(seed)
        ids = list(range(len(self.points)))
        self.roots = [self._make(ids) for _ in range(trees)]  # @line L1

    def _make(self, ids: List[int]) -> Node:
        node = Node()
        self._fill(node, ids)
        return node

    def _fill(self, node: Node, ids: List[int]) -> None:
        pts = self.points
        if len(ids) <= self.leaf_size:  # @line L2
            node.dim, node.ids = -1, list(ids)
            return
        n = len(ids)
        mean = [sum(pts[i][j] for i in ids) / n for j in range(self.dim)]  # @line L3
        var = [sum((pts[i][j] - mean[j]) ** 2 for i in ids) / n for j in range(self.dim)]
        order = sorted((j for j in range(self.dim) if var[j] > 0.0), key=lambda j: (-var[j], j))
        if not order:  # all points equal: one leaf
            node.dim, node.ids = -1, list(ids)
            return
        cand = order[: self.top_dims]  # @line L4
        j = cand[self.rng.randrange(len(cand))]  # @line L5
        s = mean[j]
        left = [i for i in ids if pts[i][j] < s]  # @line L6
        right = [i for i in ids if pts[i][j] >= s]
        if not left or not right:  # rounding of the mean; split below the largest value instead
            s = max(pts[i][j] for i in ids)
            left = [i for i in ids if pts[i][j] < s]
            right = [i for i in ids if pts[i][j] >= s]
        node.dim, node.split, node.ids = j, s, []  # @line L7
        node.left, node.right = self._make(left), self._make(right)

    def insert(self, p: Sequence[float]) -> int:
        """Add a point to every tree and return its index."""
        p = tuple(p)
        if not self.points and self.dim == 0:
            self.dim = len(p)
        i = len(self.points)
        self.points.append(p)  # @line L8
        for root in self.roots:  # @line L9
            node = root
            while node.dim >= 0:  # @line L10
                node = node.left if p[node.dim] < node.split else node.right
            node.ids.append(i)  # @line L11
            if len(node.ids) > self.leaf_size:  # @line L12
                self._fill(node, node.ids)
        return i

    def search(self, q: Sequence[float], k: int = 1, checks: float = math.inf
               ) -> Tuple[List[Tuple[float, int]], bool, int]:
        """Return (neighbors, exact, evaluations).

        neighbors: up to k pairs (squared distance, index), sorted.
        exact: True when the search proved that these are the k nearest.
        evaluations: the number of distance computations, at most one per point.
        """
        best: List[Tuple[float, int]] = []  # @line L13
        seen = set()
        checked = 0
        d = self.dim
        count = 0
        queue = []
        for root in self.roots:  # @line L14
            queue.append((0.0, count, root, (0.0,) * d))
            count += 1
        heapq.heapify(queue)
        exact = True
        while queue:  # @line L15
            if checked >= checks:
                exact = False
                break
            b, _, node, off = heapq.heappop(queue)  # @line L16
            if len(best) == k and b >= -best[0][0]:  # @line L17
                break
            while node.dim >= 0:  # @line L18
                delta = q[node.dim] - node.split  # @line L19
                if delta < 0:  # @line L20
                    near, far = node.left, node.right
                else:
                    near, far = node.right, node.left
                old = off[node.dim]  # @line L21
                count += 1
                heapq.heappush(queue, (b - old * old + delta * delta, count, far,
                                       off[: node.dim] + (delta,) + off[node.dim + 1:]))
                node = near  # @line L22
            for i in node.ids:  # @line L23
                if i in seen:
                    continue
                seen.add(i)  # @line L24
                checked += 1
                item = (-sqdist(self.points[i], q), -i)
                if len(best) < k:
                    heapq.heappush(best, item)
                elif item > best[0]:
                    heapq.heapreplace(best, item)
        return sorted((-a, -b) for a, b in best), exact, checked  # @line L25

    def check_invariant(self) -> None:
        """Raise AssertionError if a tree misses a point or breaks a split."""
        n = len(self.points)
        for root in self.roots:
            found: List[int] = []
            stack = [(root, [-math.inf] * self.dim, [math.inf] * self.dim)]
            while stack:
                node, lo, hi = stack.pop()
                if node.dim < 0:
                    assert len(node.ids) <= self.leaf_size or len(set(self.points[i] for i in node.ids)) == 1
                    for i in node.ids:
                        p = self.points[i]
                        assert all(lo[t] <= p[t] < hi[t] for t in range(self.dim))
                    found.extend(node.ids)
                    continue
                j, s = node.dim, node.split
                hl = list(hi)
                hl[j] = min(hi[j], s)
                ll = list(lo)
                ll[j] = max(lo[j], s)
                stack.append((node.left, lo, hl))
                stack.append((node.right, ll, hi))
            assert sorted(found) == list(range(n))


def brute_force(points: Sequence[Point], q: Sequence[float], k: int = 1) -> List[Tuple[float, int]]:
    return sorted((sqdist(p, q), i) for i, p in enumerate(points))[:k]
test_randomized_kd_forest.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-kd-forest/. The authors are listed in prov/GS7MJP.jsonl.

import math
import random

import pytest

from randomized_kd_forest import RandomizedKDForest, brute_force


def cloud(rng, n, d):
    return [tuple(rng.random() for _ in range(d)) for _ in range(n)]


def test_build_holds_every_point_in_every_tree():
    rng = random.Random(1)
    for trees, leaf in ((1, 1), (4, 1), (3, 4)):
        f = RandomizedKDForest(cloud(rng, 200, 7), trees=trees, leaf_size=leaf, seed=trees)
        f.check_invariant()


def test_trees_differ_with_random_split_dimensions():
    rng = random.Random(2)
    f = RandomizedKDForest(cloud(rng, 300, 10), trees=4, seed=3)
    assert len({r.dim for r in f.roots}) > 1


def test_split_dimension_is_among_the_top_variances():
    rng = random.Random(3)
    pts = [tuple(rng.random() * (j + 1) for j in range(10)) for _ in range(400)]
    f = RandomizedKDForest(pts, trees=20, top_dims=3, seed=4)
    for r in f.roots:
        assert r.dim in (7, 8, 9)


def test_random_inserts_and_queries_against_brute_force():
    rng = random.Random(4)
    for d in (2, 5, 9):
        f = RandomizedKDForest(cloud(rng, 40, d), trees=3, leaf_size=2, seed=d)
        for step in range(150):
            if rng.random() < 0.6:
                f.insert(tuple(rng.random() for _ in range(d)))
            else:
                q = tuple(rng.uniform(-0.2, 1.2) for _ in range(d))
                k = rng.choice((1, 2, 3))
                got, exact, evals = f.search(q, k)
                assert exact and evals <= len(f.points)
                assert [g[0] for g in got] == [w[0] for w in brute_force(f.points, q, k)]
        f.check_invariant()


def test_many_small_forests_with_ties_against_brute_force():
    rng = random.Random(12)
    for trial in range(600):
        d = rng.randint(1, 3)
        pts = [tuple(float(rng.randint(0, 4)) for _ in range(d)) for _ in range(rng.randint(1, 12))]
        f = RandomizedKDForest(pts, trees=rng.randint(1, 3), top_dims=rng.randint(1, 3),
                               leaf_size=rng.randint(1, 3), seed=trial)
        q = tuple(rng.randint(-1, 5) + rng.choice((0.0, 0.5)) for _ in range(d))
        k = rng.randint(1, 3)
        got, exact, _ = f.search(q, k)
        assert exact
        assert [g[0] for g in got] == [w[0] for w in brute_force(f.points, q, k)]


def test_insert_into_an_empty_forest():
    f = RandomizedKDForest([], trees=2, seed=0, dim=3)
    rng = random.Random(5)
    for _ in range(60):
        f.insert(tuple(rng.random() for _ in range(3)))
    f.check_invariant()
    q = (0.5, 0.5, 0.5)
    assert [g[0] for g in f.search(q, 4)[0]] == [w[0] for w in brute_force(f.points, q, 4)]


def test_each_point_is_checked_at_most_once():
    rng = random.Random(6)
    pts = cloud(rng, 150, 6)
    f = RandomizedKDForest(pts, trees=8, seed=7)
    for _ in range(20):
        q = tuple(rng.random() for _ in range(6))
        _, _, evals = f.search(q, 1)
        assert evals <= len(pts)
        _, _, evals = f.search(q, 1, checks=30)
        assert evals <= 30 + f.leaf_size


def test_more_checks_never_give_a_worse_answer_and_exact_flag_is_right():
    rng = random.Random(8)
    pts = cloud(rng, 500, 12)
    f = RandomizedKDForest(pts, trees=4, seed=9)
    for _ in range(15):
        q = tuple(rng.random() for _ in range(12))
        truth = brute_force(pts, q, 2)
        last = math.inf
        for c in (1, 5, 20, 80, 320):
            got, exact, _ = f.search(q, 2, checks=c)
            assert got[0][0] <= last
            last = got[0][0]
            if exact:
                assert [g[0] for g in got] == [w[0] for w in truth]


def test_duplicate_points_stay_in_one_leaf():
    f = RandomizedKDForest([(1.0, 2.0)] * 10 + [(3.0, 4.0)], trees=2, seed=1)
    f.check_invariant()
    got, exact, _ = f.search((1.0, 2.1), 3)
    assert exact and [round(g[0], 12) for g in got] == [0.01, 0.01, 0.01]


def test_bad_parameters():
    with pytest.raises(ValueError):
        RandomizedKDForest([(0.0,)], trees=0)

History

Beis and Lowe (1997) introduced best bin first search in one k-d tree. Silpa-Anan and Hartley (2008) built several k-d trees with random choices and searched them at the same time with one priority queue, for matching image descriptors. Muja and Lowe (2009) chose the split dimension at random among the 5 dimensions of greatest variance, compared the forest with a hierarchical k-means tree, and released both in the FLANN library with an automatic choice of the index and its parameters. Their 2014 journal paper extended this work to larger data sets and to search on a cluster of machines.

References

  1. Chanop Silpa-Anan and Richard Hartley, Optimised KD-trees for fast image descriptor matching, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2008, the multiple randomized trees searched at the same time with one priority queue, and the experiments on SIFT descriptors
  2. Marius Muja and David G. Lowe, Fast approximate nearest neighbors with automatic algorithm configuration, International Conference on Computer Vision Theory and Applications (VISAPP), 2009, volume 1, 331-340, Section 3.1 (the split dimension drawn at random from the 5 dimensions of greatest variance, one priority queue across all trees, a fixed number of leaves)
  3. Marius Muja and David G. Lowe, Scalable nearest neighbor algorithms for high dimensional data, IEEE Transactions on Pattern Analysis and Machine Intelligence 36(11), 2014, 2227-2240, the section on the randomized k-d tree algorithm and the comparison with the priority search k-means tree
  4. Jeffrey S. Beis and David G. Lowe, Shape indexing using approximate nearest-neighbour search in high-dimensional spaces, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 1997, 1000-1006, Section 4 (the single k-d tree and the best bin first search that the forest extends)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.insert
  • a full proof of time.search
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/GS7MJP/text.yaml