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.
- Implements
- Similarity index
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactstatic
- Evidence
- Proof sketchCode in 1 languages
- 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 groups, then each group is split again, down to depth . The leaves are the visual words of a bag of visual words, so there can be of them, for example with and . To quantize a descriptor, start at the root and go to the child with the nearest center, times. This costs distance computations instead of . 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 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 has a center and at most children. Leaves are at depth at most . A database image with descriptors whose path passes through node has the entry , where
is the number of database images and is the number of images with at least one descriptor through node . This is the tf-idf weight on every node, not only on the leaves. The vector is divided by its L1 norm. Each node keeps an inverted file: the list of the images with and their values . 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
BUILD(X, k, L, depth) ▷ X: training descriptors, depth 0 at the root- 1
c ← the mean of X - 2
if depth = L or X has fewer than k distinct points then return a leaf with center c - 3
split X into groups X_1, ..., X_k by k-means with k centers - 4
children ← BUILD(X_j, k, L, depth + 1) for each nonempty X_j - 5
return a node with center c and these children QUANTIZE(x)- 6
node ← the root - 7
while node has children do - 8
node ← the child whose center is nearest to x, ties to the smaller index - 9
return the path of nodes from the root to node
Insert an image. Quantize each of its descriptors and count, for each node , the number of paths through it.
Query. Compute the vector of the query image the same way, with the database weights, and normalize it. For a database image , the score is the L1 distance, and for nonnegative vectors of L1 norm 1,
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 , , , with the inner nodes (center , leaves and ) and (center , leaves and ). These are the k-means centers of the training points and .
Greedy descent. The descriptor is at distance from and from , so it goes to , then to the leaf , at distance . The nearest leaf is , at distance . The tree does not give the nearest word.
Scoring. The database has three images: , and . The root is in all three images, so its weight is . The nodes , , and are each in two images and get . The leaves and are each in one image and get . Image has , which is after L1 normalization. The query goes to and to , so on . Image has the same paths, so its score is 0. For , the shared nodes are and , and the score is . For , it is . The ranking is , , . The tests check these numbers.
Correctness
The proof in the correctness file shows four facts.
- Shape. BUILD stops, every leaf has depth at most , every node has at most children, so there are at most leaves. QUANTIZE ends at a leaf after at most steps.
- Nested cells. Each descriptor reaches exactly one leaf, so the leaves split 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.
- Counts nest. For an inner node, is the sum of over its children, since each path through continues to exactly one child. A node used by every image has weight 0.
- The scoring formula. The identity above holds for all nonnegative vectors of L1 norm 1, and the query loop that adds 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 and every inner node has at most children, so there are at most leaves. QUANTIZE stops at a leaf after at most steps of line L8.
Proof. A call at depth 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 . Each call makes at most recursive calls, since line L3 makes 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 with at most children per node has at most leaves, by induction on . 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 steps.
Theorem 2 (nested cells). For every , QUANTIZE returns one leaf . For a node , let be the set of whose path passes through . Then , and for each inner node the sets of its children are disjoint and their union is . So the leaf cells split .
Proof. QUANTIZE is deterministic, so each has one path and one leaf. Every path starts at the root. If the path of passes through an inner node , line L8 picks exactly one child of (the tie rule makes the choice unique), so is in exactly one . Conversely, for every child of , since a path reaches only from .
Remark (the cell is not the Voronoi cell). With the tree of the example of the page, is in , but its nearest leaf center is . So is not in general the set of points nearest to the center of 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 , let . Then , and over the children of each inner node . If every database image has a descriptor in , then .
Proof. The first two claims follow from Theorem 2, since the split . If all images use node , then and .
Theorem 4 (the scoring formula). Let with and . Then
where .
Proof. Split the indices into , the set where only , the set where only , and the rest, where both are 0. Then
Since and , this is . For , , and outside , which gives the last form.
Corollary (the inverted files compute the score). Let the inverted file of node list each database image with , with the value . The query loop sets for all , and for each node with and each in the file of adds . For each , the pairs it visits are exactly the indices , each once, so , and by Theorem 4. If or (all its nodes have weight 0), the code returns , with , which is again .
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 training descriptors, each level of BUILD runs k-means on groups whose sizes add up to at most , so with Lloyd iterations the build costs . QUANTIZE compares with at most centers at each of at most levels, so it costs . A flat vocabulary of words would need per descriptor without an index. Inserting an image with descriptors costs . A query costs for its own vector plus the total length of the inverted files it reads. The tree takes space for the centers, and the index takes one posting for each pair of an image and a node it uses.
For , and SIFT with , 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 change with . 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 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.
# 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
- 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
- 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
- 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
- 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.
| 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 3BRV2P Edit this page History Report an error Markdown