Algorithmadvanced
VLAD
Also called vector of locally aggregated descriptors.
Represent an image by summing, for each visual word, the residuals of the descriptors assigned to it, then normalizing the concatenated vector.
- Time
- O(n K D) worst · best
- Space
- O(K D) extra
- Where
- D = the descriptor dimension; K = the number of centers; n = the number of local descriptors of the image
- Model
- Real RAM
- Properties
- deterministicexactorder invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Herve Jegou, Matthijs Douze, Cordelia Schmid, Patrick Perez, 2010
VLAD (vector of locally aggregated descriptors) turns the set of local descriptors of an image into one vector of fixed length. Each descriptor is assigned to its nearest center of a small codebook, as in the bag of visual words, but instead of counting, VLAD adds up the residuals , the vectors from the center to the descriptors. The sums of dimension are concatenated and normalized, so two images can be compared by one inner product. VLAD is a simplified Fisher vector: hard assignment and the first-order statistics only.
In plain words
Pick a small set of typical patch descriptors, the centers. For each patch of an image, find its closest center and write down the difference between the patch and that center. Add up the differences that belong to the same center. The result is one short list of numbers for each center, and together these lists describe the image.
A count only says how many patches are near a center. The sum of differences also says in which direction they lie from it. So a few dozen centers already give a detailed description, and the whole image fits in one vector that a computer can compare fast and compress.
The problem
Input. A codebook of centers in , usually from k-means on training descriptors, and the local descriptors of one image (for example SIFT with , or RootSIFT). Optional parameters: the power and a flag for intra-normalization.
Output. A vector . The nearest center is with ties to the smaller index. Before normalization, block of is
Images are compared by , or by the Euclidean distance, which gives the same ranking for unit vectors.
The algorithm
VLAD(X, C, alpha, intra) ▷ K = |C|, each c_k in R^D- 1
v_k ← 0 in R^D for k = 1..K - 2
for each descriptor x in X do - 3
k ← index of the nearest center to x, ties to the smaller index - 4
v_k ← v_k + (x - c_k) - 5
if intra then v_k ← v_k / ||v_k|| for each k with v_k ≠ 0 - 6
z ← (v_1, ..., v_K), the concatenation of the blocks - 7
if alpha < 1 then z_i ← sign(z_i) |z_i|^alpha for each i - 8
if z ≠ 0 then z ← z / ||z|| - 9
return z
Lines L1 to L4 are the aggregation of Jegou et al. (2010). Line L7 is the power normalization of the journal version, with as the usual choice (the signed square root). Line L5 is the intra-normalization of Arandjelovic and Zisserman (2013), which they use against bursty features. Line L8 is always applied.
Example
Take , , , , and five descriptors , , , , .
| squared distance to , | cell | residual | |
|---|---|---|---|
| 2, 10 | 1 | ||
| 5, 29 | 1 | ||
| 10, 2 | 2 | ||
| 26, 2 | 2 | ||
| 36, 4 | 2 |
The blocks are and , so before line L8, and after it. With , line L7 gives and line L8 gives . With intra-normalization, line L5 gives and , and the result is : both cells now weigh the same, whatever their counts.
The residuals and in cell 2 cancel. Two descriptors on opposite sides of a center leave no trace in its block. The tests check all these numbers.
Correctness
The proof in the correctness file shows four facts. First, each descriptor adds its residual to exactly one block in line L4, so the result does not depend on the order of , and , where is the number of descriptors in cell and is their mean. Second, for two images without normalization,
so VLAD is the explicit feature map of a match kernel that compares only descriptors in the same cell, and the inner product costs instead of for descriptors in the second image. Third, this kernel is positive semidefinite, since it is an inner product of feature vectors. Fourth, if a Fisher vector uses a mixture with weights , unit variances, means and hard assignment, its gradient with respect to the means is , so after L2 normalization the two vectors are equal (Sanchez et al. 2013, Section 2.5).
Proof: VLAD is an order-invariant feature map of the same-cell residual match kernel and a scaled hard-assignment Fisher vectorfull
We use the notation of the page. The codebook is . For a descriptor , is the smallest index that minimizes . For a finite multiset of descriptors, , , and is block after lines L1 to L4 of VLAD. We write for the concatenation of the blocks, before lines L5 to L8.
Lemma 1 (what the loop computes). After lines L1 to L4, for every .
Proof. Line L1 sets every block to 0. Each pass of the loop of line L2 handles one descriptor . Line L3 computes , and line L4 adds to block and to no other block. By induction on the number of passes, after the descriptors have been handled, block is the sum of over the with . With this is the claim.
Corollary 1 (order invariance and the mean form). The output does not depend on the order in which line L2 visits . If and is the mean of , then ; if , then .
Proof. The right side of Lemma 1 is a sum over a set that is defined without an order, and addition in is commutative and associative. Lines L5 to L8 are functions of the blocks only. For the mean form, .
In floating point the sum can differ in the last bits for another order. The claim is about the exact values.
Lemma 2 (additivity). If and are multisets and is their union with multiplicities, then .
Proof. depends only on the descriptor, so , and the sum of Lemma 1 splits.
Theorem 1 (match kernel). For two multisets and ,
Hence the function on finite multisets is a positive semidefinite kernel.
Proof. The inner product of two concatenations is the sum of the inner products of the blocks: . By Lemma 1 and the bilinearity of the inner product,
Summing over gives the identity. For the second claim, take multisets and reals . Then .
The normalized versions are also positive semidefinite: if for any map into , then is again an inner product of feature vectors, and the same argument applies. This covers lines L5, L7 and L8.
Lemma 3 (normalization). If the output of line L9 is not zero, then . If line L5 runs, every block of the vector before line L7 has norm 1 or is zero. Line L7 keeps the sign of each entry and keeps zero entries at zero, so it does not change which entries are zero.
Proof. Line L8 divides a nonzero vector by its norm. Line L5 divides each nonzero block by its norm and leaves zero blocks. For line L7, is zero exactly when and has the sign of otherwise, since for . So if before line L7, it is still nonzero after it, and line L8 applies.
Theorem 2 (VLAD as a Fisher vector). Take a Gaussian mixture with components, weights , means and identity covariances, and replace its posteriors by the hard assignment if and 0 otherwise. The normalized gradient with respect to the means of the Fisher vector of a set of descriptors, (Sanchez et al. 2013, Eq. 17, divided by the number of descriptors), satisfies . So, when , the L2-normalized Fisher mean gradient equals the VLAD vector of lines L1 to L4 and L8.
Proof. With and , , and the sum over with the hard is the sum over of , which is by Lemma 1. The factor is positive and the same for all blocks, so L2 normalization removes it.
With the true soft posteriors the two vectors differ. The difference goes to zero as the components move apart, because then each posterior goes to 0 or 1 for almost every descriptor.
What is not claimed. None of these facts says that VLAD ranks images well. The retrieval quality of VLAD, and the gain of power and intra-normalization, are benchmark results.
Complexity
In the real RAM, line L3 costs with a linear scan over the centers, so lines L2 to L4 cost . Lines L5 to L8 cost . Extra space is the entries of the output. With an approximate nearest center search (a k-d tree or a randomized k-d forest), line L3 costs less, but then the assignment is approximate.
The output size is fixed: centers and SIFT with give 8,192 values, whatever is. Comparing two images costs . For large collections the vector is reduced with principal component analysis and coded with product quantization, so that one image takes a few dozen bytes.
Properties
- Order invariant and additive. The unnormalized blocks of (disjoint sets) are the sums of the blocks of and of . This is useful when descriptors arrive in batches, for example over the frames of a video.
- Dense. Almost every entry is nonzero, unlike the sparse bag of words histogram. An inverted file does not help, and search is nearest neighbor search on dense vectors.
- First order only. VLAD keeps the offset of the cell mean from the center, weighted by the count. It does not keep the spread of the cell (the Fisher vector keeps a second order term for that), and it keeps the count only through the length of the offset.
- Not invariant to the codebook. A different k-means run gives different centers and a different vector space. Vectors made with different codebooks cannot be compared.
- Exact. The code computes the definition exactly up to floating point rounding; the tests compare it with a direct evaluation of the match kernel.
Variants and improvements
- Power normalization (Jegou et al. 2012). Line L7 with reduces the weight of large components, which come from many similar descriptors (bursts such as repeated windows on a facade).
- Intra-normalization (Arandjelovic and Zisserman 2013). Line L5 makes each cell contribute a unit vector, so one bursty cell cannot dominate. They also adapt the centers to a new data set without recomputing the whole vocabulary, and pool VLADs over several regions of the image.
- Soft assignment. Each descriptor adds weighted residuals to several near centers. NetVLAD (Arandjelovic et al. 2016) uses a softmax of with trainable , and on top of a convolutional network, and is trained for place recognition. The network is outside this page.
- Fisher vector. Soft assignment by a Gaussian mixture, with gradients for the means and the variances, gives the Fisher vector.
- Residual normalization. Some systems scale each residual to unit length before line L4, so that each descriptor counts equally.
When to use it
Use VLAD when each image must be one vector of fixed size: for search in very large collections with compressed codes, for place recognition, or as input to a linear classifier. It needs only a small codebook (tens to hundreds of centers), so training is cheap. For the best accuracy with a few hundred thousand images, a bag of words with a large vocabulary and spatial verification can rank better, because VLAD keeps no geometry. Today, VLAD on learned features (NetVLAD) is common for place recognition.
Pitfalls
- Forgetting the normalization. Without line L8, images with more descriptors get longer vectors and higher scores. Without line L7 or L5, bursts dominate. These steps are not optional details: they change the ranking.
- Cancellation. Residuals on opposite sides of a center cancel, as in the example. A cell with many descriptors can have a short block. This is part of the method, but it means that the length of is not a count.
- Empty cells. An image with no descriptor in cell has . Intra-normalization must skip such blocks, or it divides by zero.
- Codebook from other data. Centers learned on one kind of image fit another kind poorly, and the residuals become large and similar for all images. Adapt the centers or learn them on similar data.
- Signs of the power step. Line L7 must keep the sign. Taking alone loses half of the information.
Implementations
The Python code computes the blocks, the optional intra-normalization, the signed power and the final L2 normalization, with a linear scan for the nearest center and the tie rule of this page. It also has a direct match-kernel function for the tests. The tests check the example of this page, the cancellation, the invariance to the order of the descriptors, the identity , the equality of the inner product with the match kernel on random sets, and the equality with the hard-assignment Fisher vector mean gradient after normalization.
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/vlad/. The authors are listed in prov/D9847P.jsonl.
"""VLAD: the vector of locally aggregated descriptors.
Each local descriptor x (a list of D floats) is assigned to its nearest center
c_k of a fixed codebook C of K centers, ties going to the smaller index. For
each center the residuals x - c_k of its descriptors are summed, and the K
sums are concatenated into one vector of K D values. Optional steps: intra
normalization (each block of D values scaled to unit L2 norm), power
normalization z -> sign(z) |z|^alpha, and a final L2 normalization.
Standard library only. Cost: O(n K D) for n descriptors with a linear scan
for the nearest center, and O(K D) extra space.
"""
import math
def sq_dist(a, b):
"""Squared Euclidean distance of two vectors."""
return sum((x - y) * (x - y) for x, y in zip(a, b))
def nearest_center(x, centers):
"""Index of the nearest center; ties go to the smaller index."""
best, best_d = 0, sq_dist(x, centers[0])
for k in range(1, len(centers)):
d = sq_dist(x, centers[k])
if d < best_d:
best, best_d = k, d
return best
def l2_normalize(z):
"""Scale z to unit L2 norm; the zero vector stays zero."""
s = math.sqrt(sum(t * t for t in z))
if s == 0.0:
return list(z)
return [t / s for t in z]
def power_normalize(z, alpha):
"""Signed power: sign(t) |t|^alpha for each entry. alpha = 0.5 is the signed square root."""
return [math.copysign(abs(t) ** alpha, t) if t != 0 else 0.0 for t in z]
def vlad_blocks(descriptors, centers):
"""The K residual sums v_k (lists of D floats), before any normalization."""
K, D = len(centers), len(centers[0])
v = [[0.0] * D for _ in range(K)] # @line L1
for x in descriptors: # @line L2
k = nearest_center(x, centers) # @line L3
ck = centers[k]
vk = v[k]
for i in range(D): # @line L4
vk[i] += x[i] - ck[i]
return v
def vlad(descriptors, centers, alpha=1.0, intra=False, l2=True):
"""The VLAD vector of a set of descriptors, as a flat list of K D floats.
alpha = 1.0 means no power normalization; Jegou et al. use alpha = 0.5.
intra = True scales each block to unit norm first (Arandjelovic and Zisserman).
"""
v = vlad_blocks(descriptors, centers)
if intra: # @line L5
v = [l2_normalize(block) for block in v]
z = [t for block in v for t in block] # @line L6
if alpha != 1.0: # @line L7
z = power_normalize(z, alpha)
if l2: # @line L8
z = l2_normalize(z)
return z # @line L9
def sum_match_kernel(xs, ys, centers):
"""Brute force: the sum over pairs (x, y) in the same cell k of <x - c_k, y - c_k>."""
total = 0.0
for x in xs:
kx = nearest_center(x, centers)
for y in ys:
if nearest_center(y, centers) == kx:
c = centers[kx]
total += sum((a - ci) * (b - ci) for a, b, ci in zip(x, y, c))
return total
def cell_means(descriptors, centers):
"""For each center: the count n_k and the mean of its descriptors (None if empty)."""
K, D = len(centers), len(centers[0])
sums = [[0.0] * D for _ in range(K)]
counts = [0] * K
for x in descriptors:
k = nearest_center(x, centers)
counts[k] += 1
for i in range(D):
sums[k][i] += x[i]
means = [None if counts[k] == 0 else [s / counts[k] for s in sums[k]] for k in range(K)]
return counts, means
test_vlad.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vlad/. The authors are listed in prov/D9847P.jsonl.
import math
import random
from vlad import (cell_means, l2_normalize, nearest_center, power_normalize,
sum_match_kernel, vlad, vlad_blocks)
CENTERS = [[0.0, 0.0], [4.0, 0.0]]
X = [[1.0, 1.0], [-1.0, 2.0], [3.0, 1.0], [5.0, -1.0], [6.0, 0.0]]
TOL = 1e-12
def close(a, b, tol=TOL):
return len(a) == len(b) and all(abs(x - y) <= tol for x, y in zip(a, b))
def random_set(rng, n, D):
return [[rng.uniform(-3.0, 3.0) for _ in range(D)] for _ in range(n)]
def test_example_of_the_page():
assert vlad_blocks(X, CENTERS) == [[0.0, 3.0], [2.0, 0.0]]
assert close(vlad(X, CENTERS), [0.0, 3 / math.sqrt(13), 2 / math.sqrt(13), 0.0])
assert close(vlad(X, CENTERS, alpha=0.5), [0.0, math.sqrt(3 / 5), math.sqrt(2 / 5), 0.0])
h = 1 / math.sqrt(2)
assert close(vlad(X, CENTERS, intra=True), [0.0, h, h, 0.0])
def test_residuals_cancel_in_a_cell():
# (3, 1) and (5, -1) have residuals (-1, 1) and (1, -1) to (4, 0): they cancel.
assert vlad_blocks([[3.0, 1.0], [5.0, -1.0]], CENTERS) == [[0.0, 0.0], [0.0, 0.0]]
def test_tie_goes_to_smaller_index():
assert nearest_center([2.0, 5.0], CENTERS) == 0
def test_dimension_and_unit_norm():
rng = random.Random(1)
for K, D in [(1, 3), (4, 2), (8, 5)]:
C = random_set(rng, K, D)
z = vlad(random_set(rng, 30, D), C, alpha=0.5)
assert len(z) == K * D
assert abs(sum(t * t for t in z) - 1.0) < 1e-12
def test_order_of_descriptors_does_not_matter():
rng = random.Random(2)
C = random_set(rng, 5, 4)
xs = random_set(rng, 40, 4)
ys = list(xs)
rng.shuffle(ys)
assert close(vlad(xs, C, alpha=0.5, intra=True), vlad(ys, C, alpha=0.5, intra=True), 1e-12)
def test_block_is_count_times_mean_minus_center():
rng = random.Random(3)
C = random_set(rng, 6, 3)
xs = random_set(rng, 50, 3)
v = vlad_blocks(xs, C)
counts, means = cell_means(xs, C)
for k in range(6):
if counts[k] == 0:
assert v[k] == [0.0, 0.0, 0.0]
else:
expect = [counts[k] * (m - c) for m, c in zip(means[k], C[k])]
assert close(v[k], expect, 1e-9)
def test_inner_product_is_the_sum_match_kernel():
rng = random.Random(4)
for _ in range(5):
C = random_set(rng, 4, 3)
xs, ys = random_set(rng, 15, 3), random_set(rng, 12, 3)
a = vlad(xs, C, l2=False)
b = vlad(ys, C, l2=False)
dot = sum(s * t for s, t in zip(a, b))
assert abs(dot - sum_match_kernel(xs, ys, C)) < 1e-9
def test_equals_hard_fisher_mean_gradient_up_to_scale():
# Fisher vector mean part with hard assignment, w_k = 1/K and sigma = 1:
# G_k = (1 / (T sqrt(w_k))) sum over the cell of (x - mu_k).
rng = random.Random(5)
K, D, T = 5, 3, 40
C = random_set(rng, K, D)
xs = random_set(rng, T, D)
g = [[0.0] * D for _ in range(K)]
for x in xs:
k = nearest_center(x, C)
for i in range(D):
g[k][i] += (x[i] - C[k][i]) / (T * math.sqrt(1.0 / K))
flat_g = [t for block in g for t in block]
v = vlad(xs, C, l2=False)
assert close(flat_g, [math.sqrt(K) / T * t for t in v], 1e-12)
assert close(l2_normalize(flat_g), vlad(xs, C), 1e-12)
def test_intra_normalization_blocks():
rng = random.Random(6)
C = random_set(rng, 6, 4)
xs = random_set(rng, 8, 4)
z = vlad(xs, C, intra=True, l2=False)
for k in range(6):
s = sum(t * t for t in z[4 * k:4 * k + 4])
assert abs(s - 1.0) < 1e-12 or s == 0.0
def test_power_normalization_keeps_sign():
z = [-4.0, 0.0, 9.0, -0.25]
assert power_normalize(z, 0.5) == [-2.0, 0.0, 3.0, -0.5]
assert power_normalize(z, 1.0) == z
def test_empty_set_gives_zero_vector():
assert vlad([], CENTERS) == [0.0, 0.0, 0.0, 0.0]
History
Jegou, Douze, Schmid and Perez introduced VLAD at CVPR 2010 as a compact alternative to the bag of words, to be combined with dimension reduction and product quantization for search in collections of millions of images. The 2012 journal version with Perronnin and Sanchez adds power normalization, compares VLAD with the Fisher vector of Perronnin and Dance (2007), and shows that VLAD is a simplified Fisher vector. Arandjelovic and Zisserman (2013) proposed intra-normalization and vocabulary adaptation. Arandjelovic et al. (2016) made VLAD a trainable layer, NetVLAD, for place recognition.
References
- Herve Jegou, Matthijs Douze, Cordelia Schmid and Patrick Perez, Aggregating local descriptors into a compact image representation, CVPR 2010, 3304-3311, The definition of VLAD as the sum of the residuals to the nearest center, followed by L2 normalization, and its use with compact codes
- Herve Jegou, Florent Perronnin, Matthijs Douze, Jorge Sanchez, Patrick Perez and Cordelia Schmid, Aggregating local image descriptors into compact codes, IEEE Transactions on Pattern Analysis and Machine Intelligence 34(9), 2012, 1704-1716, The VLAD descriptor, its power-law normalization, and VLAD as a simplified Fisher vector
- Relja Arandjelovic and Andrew Zisserman, All about VLAD, CVPR 2013, 1578-1585, Intra-normalization of each residual block against bursty features
- Jorge Sanchez, Florent Perronnin, Thomas Mensink and Jakob Verbeek, Image classification with the Fisher vector: theory and practice, International Journal of Computer Vision 105(3), 2013, 222-245, Section 2.5, Relationship with other methods (VLAD as a Fisher vector with hard assignment and only the gradient with respect to the means)
- Relja Arandjelovic, Petr Gronat, Akihiko Torii, Tomas Pajdla and Josef Sivic, NetVLAD: CNN architecture for weakly supervised place recognition, CVPR 2016, 5297-5307, The NetVLAD layer: soft assignment with trainable centers, intra-normalization and L2 normalization (arXiv 1511.07247)
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 | W2 basic |
|
Tag D9847P Edit this page History Report an error Markdown