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.
- Implements
- Similarity index
- 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
- Model
- Real RAM
- Properties
- anytimedynamicnot exactexact when unboundedrandomized
- Evidence
- Proof sketchCode in 1 languages
- 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 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 and supports:
- BUILD(P): make the forest for a set of points.
- INSERT(x): add a point.
- SEARCH(q, k, C): return points close to , after at most about distance computations, and say whether the answer is proved exact.
With , SEARCH returns the exact k nearest neighbors. With a finite 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 and a split value . Points with go to the left child and points with go to the right child. A leaf holds the indices of at most points, or any number of equal points. FLANN uses . 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 , compute the mean and the variance of each dimension over . Take the dimensions of largest variance, draw one of them, , uniformly at random, and split at . Muja and Lowe use . 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
BUILD(P, T, D)- 1
for t = 1 to T do root_t ← MAKE(all indices of P) MAKE(S)- 2
if |S| ≤ ℓ or all points of S are equal then return a leaf holding S - 3
compute the mean m_t and the variance v_t of each dimension t over S - 4
K ← the D dimensions with the largest v_t > 0 - 5
j ← a dimension drawn uniformly at random from K - 6
L ← {i ∈ S : x_ij < m_j}; R ← S \ L - 7
return a node with dimension j, split m_j and children MAKE(L) and MAKE(R)
INSERT(x)- 1
store x with a new index i - 2
for each tree t do - 3
go down from root_t: left if x_j < s, else right, until a leaf - 4
add i to the leaf - 5
if the leaf has more than ℓ points then replace it by MAKE(its indices)
SEARCH(q, k, C)- 1
best ← empty list of at most k (distance, index) pairs; seen ← empty set; checked ← 0 - 2
Q ← min-priority queue holding (0, root_t, zero offsets) for each tree t - 3
while Q is not empty and checked < C do - 4
(b, node, o) ← remove the entry with the smallest key from Q - 5
if best has k items and b ≥ the largest distance in best then stop: the answer is exact - 6
while node is an internal node do - 7
j ← dimension of node; δ ← q_j - split of node - 8
if δ < 0 then near, far ← left, right else near, far ← right, left - 9
insert (b - o_j^2 + δ^2, far, o with o_j = δ) into Q - 10
node ← near - 11
for each index i in the leaf with i ∉ seen do - 12
add i to seen; checked ← checked + 1; put (‖x_i - q‖^2, i) in best if it is among the k closest - 13
return best
The key of a queue entry is the squared distance from to the bin of its subtree, with the offset vector as in best bin first search. Line L21 replaces the offset of dimension ; 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 , , , , , , , , with , , and seed 5 in our code. The variances are 7.36 for and 7.11 for , and the means are 5.125 and 4.875. Tree 1 drew at the root and splits at ; tree 2 drew and splits at . The query is . Its nearest neighbor is at squared distance 5.2, and the next one is or at 7.4.
The search with a budget of checks:
- The queue holds both roots with key 0. It pops the root of tree 1. At the query goes left, , and the right subtree gets key . At it goes right and pushes the left subtree with key . At it goes right to the leaf , at squared distance 8.2, and pushes with key . One check.
- The smallest key is now the root of tree 2, with 0. At the query goes right, , and pushes the left subtree with key . At it goes left and pushes the right subtree with key . At it goes right to the leaf , at squared distance 5.2. Two checks, and the search stops.
The forest returns , the true neighbor. Tree 1 alone with the same budget pops its key 0.0756 next, reaches the leaf at 11.6, and returns at 8.2; it needs a third check to reach . 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 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 | |||
|---|---|---|---|
| 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 .
- 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 nearest neighbors.
- More checks do not hurt. A larger budget never returns a worse -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 in and trees. A node is a leaf with a list of point indices, or an internal node with a dimension , a split value and two children. The cell of a node is the set of that satisfy for each ancestor where the path goes left and for each ancestor where it goes right. Distances are squared Euclidean distances to the query , .
Invariant. In each tree, every index is in exactly one leaf, and every point is in the cell of its leaf. Each leaf has at most points (the leaf size), or only equal points.
Lemma 1 (MAKE ends and keeps the invariant). Called on a nonempty list of indices whose points lie in the cell of the node, lines L2 to L7 end, and they produce a subtree whose leaves partition and in which every point is in the cell of its leaf.
Proof. By induction on . If line L2 makes a leaf, the claim holds, because the points of lie in the cell. Else some dimension has positive variance, so line L4 has a candidate and line L5 picks a dimension with variance and mean . 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 . A point goes left exactly when , which is the condition of the cell of the left child, and right exactly when . The two lists partition , and the induction hypothesis applies to each.
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 , so Lemma 1 gives the invariant. For INSERT of a point with new index : line L10 goes left exactly when , so the leaf it reaches has in its cell. Line L11 adds to that leaf only, so is in exactly one leaf. If the leaf now has more than 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.
Lemma 3 (the key is a lower bound). For each queue entry of SEARCH, and every point in the cell of has for each . Hence every point stored in the subtree of has .
Proof. Line L14 puts each root with and , and the claim holds. The walk of lines L18 to L22 from a popped entry keeps and , and the cells along the walk are subsets of the cell of . At a node with dimension and split , let . Line L21 pushes the far child with , the other offsets unchanged, and . If , the far child is the right child, whose cell has , so . If , the far child is the left child, whose cell has , so . For 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 .
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.
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 for a budget , where 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 by less than one leaf.
Theorem 1 (exact answer). If SEARCH ends because the queue is empty or because of line L17, it returns the smallest distances over all stored points, or all of them if .
Proof. The list keeps the smallest distances among the 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 be the popped key and the largest distance in the list. Take a point that has not been seen. Pick any tree. By the invariant, is in one leaf of that tree, and that leaf has not been reached, since reaching it would have marked 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 because the queue is a min-priority queue. By Lemma 3, . So no unseen point is closer than the -th item of the list.
Theorem 2 (more checks do not hurt). For budgets and the same forest and query, the -th distance returned with is at most the -th distance returned with .
Proof. The steps of SEARCH depend on the budget only through the test at line L15. So the run with is a prefix of the run with , and it sees a subset of the points. The -th smallest value of a superset is at most that of the subset.
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.
Complexity
The model is the real RAM. Let be the largest height of a tree. With mean splits the trees are not always balanced: for points with coordinates each mean split puts one point on the right, and . On typical descriptor data is close to .
- Build. Each level of a tree computes means and variances over at most points, so one tree costs and the forest . Sorting the variances adds per node. FLANN's sample of 100 points makes the statistics per node.
- Insert. One descent of length per tree, and a split of a leaf of points at , so for a constant .
- Search. With , 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 leaves. Each leaf costs one descent of at most pushes of , and each check costs . The total is . In practice most reached leaves are new, and the cost is close to that of leaves of one tree.
- Space. nodes and 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 for the precision you need; Muja and Lowe tune the number of trees and 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 , 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 -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 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 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.
# 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
- 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag GS7MJP Edit this page History Report an error Markdown