Algorithm Search⌘K

Data structureadvanced

Vocabulary tree

Also called hierarchical k-means vocabulary, Nister-Stewenius tree.

A tree from hierarchical k-means on descriptors that quantizes a feature in logarithmic time to one of millions of visual words.

Time
O(n k L D I) buildO(m k L D) insertO(k L D) quantizeO(m k L D + P) query
Space
O(k^L D + S) total
Where
D = the descriptor dimension; I = the number of k-means iterations; L = the depth; P = the total length of the inverted files read by a query; S = the number of postings in all the inverted files; k = the branch factor; m = the number of descriptors of one image; n = the number of training descriptors
Properties
deterministicnot exactstatic
Origin
David Nister, Henrik Stewenius, 2006

A vocabulary tree is a tree of cluster centers that turns a local descriptor into a visual word. It is built by hierarchical k-means: k-means splits the training descriptors into kk groups, then each group is split again, down to depth LL. The leaves are the visual words of a bag of visual words, so there can be kLk^L of them, for example 10610^6 with k=10k = 10 and L=6L = 6. To quantize a descriptor, start at the root and go to the child with the nearest center, LL times. This costs kLk L distance computations instead of kLk^L. The price is that the leaf found is not always the nearest leaf center. The tree also carries the inverted files and the weights for image search.

In plain words

Sorting a huge number of patch types one by one is slow. A vocabulary tree sorts them like a library. First it decides between ten broad groups, then between ten smaller groups inside the chosen one, and so on. After six such choices it has picked one type out of a million, but it has made only sixty comparisons.

Each type keeps a list of the pictures that contain it. To search, the tree sorts the patches of the new picture and reads the lists of the types it reaches. Pictures that share many rare types with the new picture get the best scores.

The abstract type

The tree implements a similarity index for images, through two parts.

  • Quantizer. A map from a descriptor x∈RDx \in \mathbb{R}^D to a leaf, and to the path of nodes from the root to that leaf.
  • Image index. A set of database images, each given by its descriptors. The query takes the descriptors of an image and returns the database images ranked by a score.

The tree is built once from training descriptors and then stays fixed. Images can be added to the index at any time, but the weights depend on the number of images, so they are usually computed after the database is complete.

Representation

Each node ii has a center ci∈RDc_i \in \mathbb{R}^D and at most kk children. Leaves are at depth at most LL. A database image dd with mim_i descriptors whose path passes through node ii has the entry di=miwid_i = m_i w_i, where

wi=ln⁡NNi,w_i = \ln \frac{N}{N_i},

NN is the number of database images and NiN_i is the number of images with at least one descriptor through node ii. This is the tf-idf weight on every node, not only on the leaves. The vector dd is divided by its L1 norm. Each node keeps an inverted file: the list of the images dd with di>0d_i > 0 and their values did_i. Nister and Stewenius store the files at the leaves only; the file of an inner node is the union of the files of its leaves.

Operations

  1. BUILD(X, k, L, depth) ▷ X: training descriptors, depth 0 at the root
  2. 1c ← the mean of X
  3. 2if depth = L or X has fewer than k distinct points then return a leaf with center c
  4. 3split X into groups X_1, ..., X_k by k-means with k centers
  5. 4children ← BUILD(X_j, k, L, depth + 1) for each nonempty X_j
  6. 5return a node with center c and these children
  7. QUANTIZE(x)
  8. 6node ← the root
  9. 7while node has children do
  10. 8node ← the child whose center is nearest to x, ties to the smaller index
  11. 9return the path of nodes from the root to node

Insert an image. Quantize each of its mm descriptors and count, for each node ii, the number mim_i of paths through it.

Query. Compute the vector qq of the query image the same way, with the database weights, and normalize it. For a database image dd, the score is the L1 distance, and for nonnegative vectors of L1 norm 1,

∥q−d∥1=2+∑i: qi>0, di>0(∣qi−di∣−qi−di)=2−2∑imin⁡(qi,di).\lVert q - d \rVert_1 = 2 + \sum_{i:\ q_i > 0,\ d_i > 0} \big( |q_i - d_i| - q_i - d_i \big) = 2 - 2 \sum_i \min(q_i, d_i).

So only the nodes that both images use change the score, and the inverted files of the nodes of the query give all of them. Smaller is better.

Example

Take D=1D = 1, k=2k = 2, L=2L = 2, with the inner nodes AA (center −1-1, leaves −6-6 and 44) and BB (center 1010, leaves 88 and 1212). These are the k-means centers of the training points {−6,4}\{-6, 4\} and {8,12}\{8, 12\}.

Greedy descent. The descriptor 4.64.6 is at distance 5.65.6 from AA and 5.45.4 from BB, so it goes to BB, then to the leaf 88, at distance 3.43.4. The nearest leaf is 44, at distance 0.60.6. The tree does not give the nearest word.

Scoring. The database has three images: a={−6,4}a = \{-6, 4\}, b={8,12,12}b = \{8, 12, 12\} and c={4,9}c = \{4, 9\}. The root is in all three images, so its weight is ln⁡1=0\ln 1 = 0. The nodes AA, BB, 44 and 88 are each in two images and get ln⁡1.5=0.4055\ln 1.5 = 0.4055. The leaves −6-6 and 1212 are each in one image and get ln⁡3=1.0986\ln 3 = 1.0986. Image aa has (A,−6,4)=(2⋅0.4055,1.0986,0.4055)(A, -6, 4) = (2 \cdot 0.4055, 1.0986, 0.4055), which is (0.3503,0.4746,0.1751)(0.3503, 0.4746, 0.1751) after L1 normalization. The query {3,5}\{3, 5\} goes to A,4A, 4 and to B,8B, 8, so q=(0.25,0.25,0.25,0.25)q = (0.25, 0.25, 0.25, 0.25) on (A,4,B,8)(A, 4, B, 8). Image cc has the same paths, so its score is 0. For aa, the shared nodes are AA and 44, and the score is 2−2(0.25+0.1751)=1.14972 - 2(0.25 + 0.1751) = 1.1497. For bb, it is 2−2(0.25+0.1062)=1.28772 - 2(0.25 + 0.1062) = 1.2877. The ranking is cc, aa, bb. The tests check these numbers.

Correctness

The proof in the correctness file shows four facts.

  1. Shape. BUILD stops, every leaf has depth at most LL, every node has at most kk children, so there are at most kLk^L leaves. QUANTIZE ends at a leaf after at most LL steps.
  2. Nested cells. Each descriptor reaches exactly one leaf, so the leaves split RD\mathbb{R}^D into cells. The cell of a leaf is the set of points that pass the nearest-child test at each node of its path. It is not the Voronoi cell of the leaf center among all the leaves, as the example shows. So the tree is an approximate quantizer: a heuristic for nearest center search, with no bound on the error.
  3. Counts nest. For an inner node, mim_i is the sum of mjm_j over its children, since each path through ii continues to exactly one child. A node used by every image has weight 0.
  4. The scoring formula. The identity above holds for all nonnegative vectors of L1 norm 1, and the query loop that adds ∣qi−di∣−qi−di|q_i - d_i| - q_i - d_i over the inverted files of the query nodes computes it exactly.
Proof: The vocabulary tree has depth at most L and branch factor at most k, quantizes to exactly one leaf, and its inverted file score is the L1 distancefull

We use the notation of the page. Distances are Euclidean, and "nearest child" uses the tie rule of line L8 (the smaller index wins).

Theorem 1 (shape). BUILD stops. In the tree it returns, every leaf has depth at most LL and every inner node has at most kk children, so there are at most kLk^L leaves. QUANTIZE stops at a leaf after at most LL steps of line L8.

Proof. A call at depth LL returns a leaf in line L2, and each recursive call in line L4 has depth one more than its caller, so no call has depth more than LL. Each call makes at most kk recursive calls, since line L3 makes kk groups and line L4 keeps only the nonempty ones; each k-means run stops after a bounded number of iterations. So the recursion tree is finite, and BUILD stops. A tree of depth at most LL with at most kk children per node has at most kLk^L leaves, by induction on LL. Every inner node has at least one child, so line L8 always finds a child, the depth grows by one at each step, and the loop stops at a leaf after at most LL steps. □\square

Theorem 2 (nested cells). For every x∈RDx \in \mathbb{R}^D, QUANTIZE returns one leaf ℓ(x)\ell(x). For a node ii, let SiS_i be the set of xx whose path passes through ii. Then Sroot=RDS_{\text{root}} = \mathbb{R}^D, and for each inner node ii the sets SjS_j of its children jj are disjoint and their union is SiS_i. So the leaf cells SℓS_\ell split RD\mathbb{R}^D.

Proof. QUANTIZE is deterministic, so each xx has one path and one leaf. Every path starts at the root. If the path of xx passes through an inner node ii, line L8 picks exactly one child of ii (the tie rule makes the choice unique), so xx is in exactly one SjS_j. Conversely, Sj⊆SiS_j \subseteq S_i for every child jj of ii, since a path reaches jj only from ii. □\square

Remark (the cell is not the Voronoi cell). With the tree of the example of the page, x=4.6x = 4.6 is in S8S_8, but its nearest leaf center is 44. So SℓS_\ell is not in general the set of points nearest to the center of ℓ\ell among all leaf centers, and the error of greedy descent has no bound in terms of the distance to the nearest leaf center. Greedy descent is a heuristic for nearest center search.

Theorem 3 (counts nest). For an image with descriptors x1,…,xmx_1, \ldots, x_m, let mi=#{t:xt∈Si}m_i = \#\{t : x_t \in S_i\}. Then mroot=mm_{\text{root}} = m, and mi=∑jmjm_i = \sum_j m_j over the children jj of each inner node ii. If every database image has a descriptor in SiS_i, then wi=0w_i = 0.

Proof. The first two claims follow from Theorem 2, since the SjS_j split SiS_i. If all NN images use node ii, then Ni=NN_i = N and wi=ln⁡1=0w_i = \ln 1 = 0. □\square

Theorem 4 (the scoring formula). Let q,d∈Rnq, d \in \mathbb{R}^n with qi,di≥0q_i, d_i \ge 0 and ∑iqi=∑idi=1\sum_i q_i = \sum_i d_i = 1. Then

∥q−d∥1=2+∑i∈C(∣qi−di∣−qi−di)=2−2∑imin⁡(qi,di),\lVert q - d \rVert_1 = 2 + \sum_{i \in C} \big( |q_i - d_i| - q_i - d_i \big) = 2 - 2 \sum_i \min(q_i, d_i),

where C={i:qi>0 and di>0}C = \{i : q_i > 0 \text{ and } d_i > 0\}.

Proof. Split the indices into CC, the set QQ where only qi>0q_i > 0, the set PP where only di>0d_i > 0, and the rest, where both are 0. Then

∥q−d∥1=∑C∣qi−di∣+∑Qqi+∑Pdi.\lVert q - d \rVert_1 = \sum_{C} |q_i - d_i| + \sum_{Q} q_i + \sum_{P} d_i.

Since ∑Qqi=1−∑Cqi\sum_Q q_i = 1 - \sum_C q_i and ∑Pdi=1−∑Cdi\sum_P d_i = 1 - \sum_C d_i, this is 2+∑C(∣qi−di∣−qi−di)2 + \sum_C (|q_i - d_i| - q_i - d_i). For a,b≥0a, b \ge 0, ∣a−b∣−a−b=−2min⁡(a,b)|a - b| - a - b = -2 \min(a, b), and min⁡(qi,di)=0\min(q_i, d_i) = 0 outside CC, which gives the last form. □\square

Corollary (the inverted files compute the score). Let the inverted file of node ii list each database image dd with di>0d_i > 0, with the value did_i. The query loop sets acc(d)=0\mathrm{acc}(d) = 0 for all dd, and for each node ii with qi>0q_i > 0 and each (d,di)(d, d_i) in the file of ii adds ∣qi−di∣−qi−di|q_i - d_i| - q_i - d_i. For each dd, the pairs it visits are exactly the indices i∈Ci \in C, each once, so acc(d)=∑i∈C(∣qi−di∣−qi−di)\mathrm{acc}(d) = \sum_{i \in C} (|q_i - d_i| - q_i - d_i), and 2+acc(d)=∥q−d∥12 + \mathrm{acc}(d) = \lVert q - d \rVert_1 by Theorem 4. If q=0q = 0 or d=0d = 0 (all its nodes have weight 0), the code returns ∥q∥1+∥d∥1+acc(d)\lVert q \rVert_1 + \lVert d \rVert_1 + \mathrm{acc}(d), with acc(d)=0\mathrm{acc}(d) = 0, which is again ∥q−d∥1\lVert q - d \rVert_1. □\square

What is not claimed. Nothing here says that the leaf of a descriptor is its nearest leaf center, that the k-means splits are good, or that a small L1 distance means that two images show the same object. Those are heuristics, and the ranking quality is a benchmark result.

Complexity

In the real RAM, with nn training descriptors, each level of BUILD runs k-means on groups whose sizes add up to at most nn, so with II Lloyd iterations the build costs O(nkLDI)O(n k L D I). QUANTIZE compares xx with at most kk centers at each of at most LL levels, so it costs O(kLD)O(k L D). A flat vocabulary of kLk^L words would need O(kLD)O(k^L D) per descriptor without an index. Inserting an image with mm descriptors costs O(mkLD)O(m k L D). A query costs O(mkLD)O(m k L D) for its own vector plus the total length PP of the inverted files it reads. The tree takes O(kLD)O(k^L D) space for the centers, and the index takes one posting for each pair of an image and a node it uses.

For k=10k = 10, L=6L = 6 and SIFT with D=128D = 128, the tree has a million leaves and quantizes with 60 distance computations.

Variants

  • Scoring choices. Nister and Stewenius compared the L1 and L2 norms and scoring with all nodes or with the leaves only. They report that the L1 norm and larger vocabularies gave better results on their data. That is a benchmark result, not a theorem.
  • Flat approximate k-means. Philbin et al. (2007) assign descriptors to a flat vocabulary of a million centers with a randomized k-d forest. On Oxford 5K, their 1M word flat vocabulary gave a mean average precision of 0.618 against 0.439 for the best hierarchical vocabulary. That is a benchmark result: the greedy descent loses matches at the upper levels.
  • Search with backtracking. Visiting several children at each level, best first, reduces the error of the greedy descent, at a higher cost.
  • Binary descriptors. DBoW2 (Galvez-Lopez and Tardos 2012) builds the tree on binary descriptors with the Hamming distance and uses it for loop detection in SLAM.
  • Direct index. DBoW2 also stores, for each image, its features grouped by a node at a chosen level, to restrict feature matching to the same node.

When to use it

Use a vocabulary tree when the vocabulary must be very large and quantization must be fast, as in image retrieval on millions of images or in place recognition on a robot. The tree is easy to build and needs no other index. If the accuracy of the assignment matters more than the build time, a flat vocabulary with approximate search usually ranks better. If each image must be one dense vector, use VLAD or a Fisher vector instead.

Pitfalls

  • Errors at the top. A wrong choice at the first level cannot be corrected later. Two close descriptors near a boundary at the top can end in leaves that are far apart.
  • Unbalanced trees. Dense regions of descriptor space get deep, small cells, and sparse regions get large ones. Leaves with very few training points are noisy words.
  • Weights from a small database. The weights ln⁡(N/Ni)\ln(N / N_i) change with NN. Weights computed on a small database, or on images of another kind, give poor rankings on the real one.
  • Ties to the root. The root, and any node that all images use, has weight 0. Images whose descriptors all lie in such nodes get the zero vector and cannot be ranked.
  • Using the score as a probability. The L1 distance ranks images. It is not calibrated, and a fixed threshold on it does not work across queries. Use spatial verification to decide matches.

Implementations

The Python code builds the tree by hierarchical k-means with Lloyd iterations from random distinct points and a fixed seed, quantizes by greedy descent with the tie rule of this page, computes the weights, keeps the inverted files on all nodes, and scores queries with the formula above. The tests check the example of this page, the greedy descent counterexample, the shape bounds, the nearest-child rule on each step, a zero score for an image queried with its own descriptors, and the equality of the inverted file score with the brute-force L1 distance and with 2−2∑imin⁡(qi,di)2 - 2 \sum_i \min(q_i, d_i) on random data.

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.

vocabulary_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vocabulary-tree/. The authors are listed in prov/3BRV2P.jsonl.
"""The vocabulary tree of Nister and Stewenius (2006).

A tree with branch factor k and depth L, built by hierarchical k-means.
A descriptor is quantized by greedy descent: at each node, go to the child
with the nearest center (ties to the smaller index). Each node i has the
weight w_i = ln(N / N_i), where N is the number of database images and N_i
the number of images with at least one descriptor through node i. An image
is the vector of n_i w_i over the nodes (n_i descriptors through node i),
normalized to L1 norm 1. The score of a database image d for a query q is
||q - d||_1 = 2 + sum over the nodes in both of (|q_i - d_i| - q_i - d_i),
which the inverted files compute from the nodes the query uses.
Standard library only.
"""

import math
import random


def sq_dist(a, b):
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def mean(points):
    n = len(points)
    return [sum(p[j] for p in points) / n for j in range(len(points[0]))]


def nearest(x, centers):
    """Index of the nearest center, ties to the smaller index."""
    best, best_d = 0, sq_dist(x, centers[0])
    for j in range(1, len(centers)):
        d = sq_dist(x, centers[j])
        if d < best_d:
            best, best_d = j, d
    return best


def kmeans(points, k, rng, iters=50):
    """Lloyd iterations from k distinct points chosen at random; an empty cluster keeps its center."""
    distinct = sorted(set(tuple(p) for p in points))
    centers = [list(c) for c in rng.sample(distinct, k)]
    for _ in range(iters):
        groups = [[] for _ in range(k)]
        for p in points:
            groups[nearest(p, centers)].append(p)
        new = [mean(g) if g else centers[j] for j, g in enumerate(groups)]
        if new == centers:
            break
        centers = new
    groups = [[] for _ in range(k)]
    for p in points:
        groups[nearest(p, centers)].append(p)
    return centers, groups


def node(center, children=()):
    return {"center": list(center), "children": list(children)}


def build(points, k, L, seed=0):
    """Hierarchical k-means: a tree of depth at most L and branch factor at most k."""
    rng = random.Random(seed)

    def rec(pts, depth):
        center = mean(pts)  # @line L1
        if depth == L or len(set(tuple(p) for p in pts)) < k:  # @line L2
            return node(center)
        _, groups = kmeans(pts, k, rng)  # @line L3
        kids = [rec(g, depth + 1) for g in groups if g]  # @line L4
        return node(center, kids)  # @line L5

    return rec(points, 0)


class VocabularyTree:
    def __init__(self, root):
        self.root = root
        self.nodes = []
        self.leaves = []
        stack = [root]
        while stack:
            nd = stack.pop()
            nd["id"] = len(self.nodes)
            self.nodes.append(nd)
            if nd["children"]:
                stack.extend(reversed(nd["children"]))
            else:
                nd["word"] = len(self.leaves)
                self.leaves.append(nd)
        self.inverted = {}
        self.weights = {}
        self.N = 0
        self.norms = {}

    def path(self, x):
        """Node ids from the root to the leaf that greedy descent reaches."""
        nd = self.root  # @line L6
        out = [nd["id"]]
        while nd["children"]:  # @line L7
            kids = nd["children"]
            nd = kids[nearest(x, [c["center"] for c in kids])]  # @line L8
            out.append(nd["id"])
        return out  # @line L9

    def quantize(self, x):
        return self.nodes[self.path(x)[-1]]["word"]

    def counts(self, descriptors):
        n = {}
        for x in descriptors:
            for i in self.path(x):
                n[i] = n.get(i, 0) + 1
        return n

    def index(self, images):
        """images: dict id -> list of descriptors. Builds the weights and the inverted files."""
        self.N = len(images)
        raw = {d: self.counts(xs) for d, xs in images.items()}
        df = {}
        for n in raw.values():
            for i in n:
                df[i] = df.get(i, 0) + 1
        self.weights = {i: math.log(self.N / df[i]) for i in df}
        self.inverted = {}
        self.nonzero = set()
        for d, n in raw.items():
            vec = self.normalize({i: c * self.weights[i] for i, c in n.items()})
            if vec:
                self.nonzero.add(d)
            for i, val in vec.items():
                self.inverted.setdefault(i, {})[d] = val
        self.ids = list(images)

    def normalize(self, vec):
        s = sum(abs(t) for t in vec.values())
        return {i: t / s for i, t in vec.items() if t != 0} if s > 0 else {}

    def vector(self, descriptors):
        n = self.counts(descriptors)
        return self.normalize({i: c * self.weights.get(i, 0.0) for i, c in n.items()})

    def scores(self, descriptors):
        """L1 distance of the query vector to each database vector, by the inverted files."""
        q = self.vector(descriptors)
        acc = {d: 0.0 for d in self.ids}
        for i, qi in q.items():
            for d, di in self.inverted.get(i, {}).items():
                acc[d] += abs(qi - di) - qi - di
        has_q = 1.0 if q else 0.0
        out = {}
        for d in self.ids:
            out[d] = has_q + (1.0 if d in self.nonzero else 0.0) + acc[d]
        return out

    def query(self, descriptors, top=None):
        s = self.scores(descriptors)
        ranked = sorted(self.ids, key=lambda d: (s[d], str(d)))
        return [(s[d], d) for d in (ranked if top is None else ranked[:top])]
test_vocabulary_tree.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vocabulary-tree/. The authors are listed in prov/3BRV2P.jsonl.

import math
import random

from vocabulary_tree import VocabularyTree, build, nearest, node, sq_dist


def example_tree():
    leaf = lambda c: node([c])
    root = node([3.5], [node([-1], [leaf(-6), leaf(4)]), node([10], [leaf(8), leaf(12)])])
    return VocabularyTree(root)


IMAGES = {"a": [[-6], [4]], "b": [[8], [12], [12]], "c": [[4], [9]]}


def depth_and_branching(nd, depth=0):
    if not nd["children"]:
        return depth, 0
    sub = [depth_and_branching(c, depth + 1) for c in nd["children"]]
    return max(s[0] for s in sub), max([len(nd["children"])] + [s[1] for s in sub])


def brute_vector(T, descriptors):
    n = {}
    for x in descriptors:
        for i in T.path(x):
            n[i] = n.get(i, 0) + 1
    v = [n.get(i, 0) * T.weights.get(i, 0.0) for i in range(len(T.nodes))]
    s = sum(v)
    return [t / s for t in v] if s > 0 else v


def test_greedy_descent_misses_the_nearest_leaf():
    T = example_tree()
    assert T.path([4.6]) == [0, 4, 5]
    assert T.leaves[T.quantize([4.6])]["center"] == [8]
    leaf_centers = [lf["center"] for lf in T.leaves]
    assert leaf_centers[nearest([4.6], leaf_centers)] == [4]


def test_example_of_the_page():
    T = example_tree()
    T.index(IMAGES)
    assert T.weights[0] == 0.0
    assert abs(T.weights[1] - math.log(1.5)) < 1e-12 and abs(T.weights[2] - math.log(3)) < 1e-12
    assert abs(T.inverted[2]["a"] - math.log(3) / (3 * math.log(1.5) + math.log(3))) < 1e-12
    ranked = T.query([[3], [5]])
    assert [d for _, d in ranked] == ["c", "a", "b"]
    assert abs(ranked[0][0]) < 1e-12
    assert abs(ranked[1][0] - 1.1497) < 1e-4 and abs(ranked[2][0] - 1.2877) < 1e-4


def test_inverted_files_equal_brute_force_l1():
    rng = random.Random(1)
    train = [[rng.uniform(0, 10), rng.uniform(0, 10)] for _ in range(300)]
    T = VocabularyTree(build(train, 3, 3, seed=1))
    images = {d: [[rng.uniform(0, 10), rng.uniform(0, 10)] for _ in range(rng.randint(1, 15))] for d in range(12)}
    T.index(images)
    for _ in range(5):
        q = [[rng.uniform(0, 10), rng.uniform(0, 10)] for _ in range(rng.randint(1, 15))]
        qv = brute_vector(T, q)
        s = T.scores(q)
        for d, xs in images.items():
            dv = brute_vector(T, xs)
            l1 = sum(abs(a - b) for a, b in zip(qv, dv))
            inter = sum(min(a, b) for a, b in zip(qv, dv))
            assert abs(s[d] - l1) < 1e-9
            assert abs(s[d] - (2 - 2 * inter)) < 1e-9 or sum(qv) == 0 or sum(dv) == 0


def test_build_respects_k_and_L_and_partitions():
    rng = random.Random(2)
    train = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(400)]
    for k, L in ((2, 4), (3, 3), (5, 2)):
        T = VocabularyTree(build(train, k, L, seed=3))
        depth, branch = depth_and_branching(T.root)
        assert depth <= L and branch <= k
        assert len(T.leaves) <= k ** L
        for x in train[:50]:
            p = T.path(x)
            assert len(p) <= L + 1 and not T.nodes[p[-1]]["children"]


def test_query_with_own_descriptors_scores_zero():
    rng = random.Random(4)
    train = [[rng.uniform(0, 5)] for _ in range(200)]
    T = VocabularyTree(build(train, 4, 3, seed=5))
    images = {d: [[rng.uniform(0, 5)] for _ in range(8)] for d in range(10)}
    T.index(images)
    for d in (0, 3, 7):
        assert abs(T.scores(images[d])[d]) < 1e-12


def test_greedy_leaf_is_nearest_child_at_each_step():
    rng = random.Random(6)
    train = [[rng.uniform(0, 1), rng.uniform(0, 1)] for _ in range(200)]
    T = VocabularyTree(build(train, 3, 3, seed=7))
    for _ in range(100):
        x = [rng.uniform(0, 1), rng.uniform(0, 1)]
        p = T.path(x)
        for a, b in zip(p, p[1:]):
            kids = T.nodes[a]["children"]
            assert min(sq_dist(x, c["center"]) for c in kids) == sq_dist(x, T.nodes[b]["center"])

History

Tree-structured codebooks were known earlier in vector quantization for signal coding. Nister and Stewenius (CVPR 2006) applied hierarchical k-means to local image descriptors, scored images with entropy weights on all the nodes, and showed search in a database of a million images. Philbin et al. (2007) showed that a flat vocabulary with approximate nearest neighbor assignment gives better rankings. Galvez-Lopez and Tardos (2012) adapted the tree to binary descriptors in DBoW2, which ORB-SLAM uses for place recognition and loop closure.

References

  1. David Nister and Henrik Stewenius, Scalable recognition with a vocabulary tree, CVPR 2006, volume 2, 2161-2168, The hierarchical k-means tree, the quantization by greedy descent, the weights ln(N/N_i), and the L1 scoring with inverted files
  2. Esteban Uriza, Francisco Gomez Fernandez and Martin Rais, Efficient large-scale image search with a vocabulary tree, Image Processing On Line 8, 2018, 71-98, A full description and open implementation of the method of Nister and Stewenius, with the scoring formula and experiments
  3. James Philbin, Ondrej Chum, Michael Isard, Josef Sivic and Andrew Zisserman, Object retrieval with large vocabularies and fast spatial matching, CVPR 2007, The comparison of approximate flat k-means with hierarchical k-means on the Oxford 5K data set
  4. Dorian Galvez-Lopez and Juan D. Tardos, Bags of binary words for fast place recognition in image sequences, IEEE Transactions on Robotics 28(5), 2012, 1188-1197, The vocabulary tree on binary descriptors with the Hamming distance, used for loop detection

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.quantize
  • a full proof of time.query
  • 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/3BRV2P/text.yaml