AI Wiki中文/EN

Image retrieval: similar vectors, relevant answers

图像检索

Implement visual aggregation and geometric reranking, check complete NetVLAD gradients, and distinguish candidate recall from relevance and AP conventions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Find this building, or find buildings like it?

Suppose you photograph a doorway and search a collection of travel photos. A result showing another doorway of the same architectural style may be useful for inspiration. It is wrong if you are trying to identify the exact entrance. Both systems can return visually plausible images; only one answers your question.

Image retrieval ranks a gallery of images for a query. The query can be an image, a crop, text or a combination. Instance retrieval asks for the same object or place despite changes of viewpoint, lighting and occlusion. Semantic retrieval asks for a category, attribute or meaning; near-duplicate search asks for the same underlying image after changes such as resizing. These are different relevance rules, not interchangeable names for nearest-neighbor search. The original Video Google system searched for a user-outlined object in film frames; NetVLAD was developed for recognizing places. Their tasks help explain why a classifier’s category score is not automatically a good instance descriptor. Object queries Place recognition

Start with the cheapest baseline that can answer the actual question. A filename, timestamp or product ID may already identify the record. A cryptographic file hash detects identical bytes, but a new JPEG encoding changes those bytes even when the picture looks the same. A color histogram is a useful visual baseline; it also discards where the colors occur. For learned retrieval, retain such baselines and measure which errors the representation actually removes.

There are three separate decisions: what counts as relevant, how an image is represented, and which gallery items the search examines. A better index cannot recover information that the representation discarded. Conversely, an excellent descriptor cannot retrieve a correct image that candidate selection never visits.

The example below makes this separation visible. It creates six distinct little tiles and rearranges them into another picture. A global orderless descriptor sees exactly the same collection of tiles. It assigns both pictures essentially the same score, and the distractor comes first under a stable tie rule. Checking whether tile matches agree on one translation puts the correct picture first. This is a synthetic counterexample, not a claim that all real retrieval systems need translation verification.

Computed example: rearranging tiles preserves global similarity. Translation consensus restores the intended match; AP conventions and candidate omissions remain separate questions.
Computed example: rearranging tiles preserves global similarity. Translation consensus restores the intended match; AP conventions and candidate omissions remain separate questions.

Representation, candidates and evidence

A distance only means something after its representation is specified

Let q be the query and I a gallery image. A feature extractor and aggregation rule produce f(q) and f(I). Normalize each nonzero vector to z. The identity below explains why decreasing squared Euclidean distance and increasing inner product give the same ranking for unit vectors:

z(I)=f(I)∥f(I)∥2,s(q,I)=z(q)⊤z(I),∥z(q)−z(I)∥22=2−2s(q,I).z(I)=\frac{f(I)}{\|f(I)\|_2},\qquad s(q,I)=z(q)^\top z(I),\qquad \|z(q)-z(I)\|_2^2=2-2s(q,I).

The constant two disappears when ranking. Without normalization, a large vector norm can dominate an inner product; the rankings need not agree. A zero vector has no cosine direction. The example rejects it rather than manufacturing a confident match. Sorting ties by gallery order makes the demonstration reproducible, but does not make the first tied result more relevant.

From visual words to residuals

Take N local descriptors x_i of dimension D and K centers c_k fitted on suitable reference data. Hard assignment sends each descriptor to its nearest center. A bag of visual words counts assignments. VLAD instead sums their signed residuals, retaining which direction features lie from the center:

a(i)=arg⁡min⁡k∥xi−ck∥22,hk=∑i1[a(i)=k],Vk=∑i:a(i)=k(xi−ck).a(i)=\arg\min_k\|x_i-c_k\|_2^2,\qquad h_k=\sum_i\mathbf1[a(i)=k],\qquad V_k=\sum_{i:a(i)=k}(x_i-c_k).

VLAD has KD coordinates before dimensionality reduction, while the count vector has K. With one-dimensional centers 0 and 2, descriptors 0.2, 0.3 and 1.7 produce counts [2,1] and residuals [0.5,-0.3]. The 2010 paper applies global L2 normalization to this residual vector. Later variants add different normalization or compression steps; they should be named explicitly. Original VLAD

The visual-word analogy also enables corpus weighting and inverted lists. A common IDF variant downweights words present in many gallery images; its document-frequency convention, smoothing and fitting collection must be fixed. Our count example implements neither IDF nor vocabulary learning: the small centers are supplied. Video Google’s visual vocabulary and weighted ranking provide the historical connection, rather than a license to treat every later bag-of-words recipe as identical. Visual vocabulary and weighting

Neither counts nor residual sums retain the order of the input descriptors. Permute the descriptors and the vector is unchanged. A local descriptor can encode the geometry inside its patch, but that does not recover the positions of different patches across the image. This distinction is the source of the shuffled-tile failure.

GeM: how much should a strong activation matter?

A convolutional feature map supplies positive activations x_ik, with position i and channel k. Generalized-mean pooling returns one number per channel. For p=1 it is the arithmetic mean; as p grows without bound it approaches the maximum. A large p emphasizes strong responses, which may belong to the target or to a distracting background object. It is a modeling choice to validate, not a universal improvement. GeM definition

Sk=1N∑ixikp,gk=Sk1/p,∂gk∂xik=1Ngk1−pxikp−1,∂gk∂p=gkp(∑ixikplog⁡xik∑ixikp−log⁡Skp).S_k=\frac1N\sum_i x_{ik}^p,\qquad g_k=S_k^{1/p},\qquad \frac{\partial g_k}{\partial x_{ik}}=\frac1N g_k^{1-p}x_{ik}^{p-1}, \qquad \frac{\partial g_k}{\partial p}=\frac{g_k}{p}\left( \frac{\sum_i x_{ik}^p\log x_{ik}}{\sum_i x_{ik}^p}-\frac{\log S_k}{p}\right).

The derivatives follow by differentiating log g_k = log S_k / p. The first tells us which spatial activations receive gradient; the second lets training adjust p. Our implementation uses a single shared positive p and strictly positive inputs. Subtracting the largest log activation before exponentiation avoids forming enormous powers directly. The author’s fixed PyTorch helper first clamps activations to a positive floor. That changes behavior at and below the floor; our strict-domain example does not claim to reproduce that boundary derivative. Fixed GeM helper

For activations [1,4], the actual example returns 2.5 at p=1, about 3.1913 at p=3 and 3.9086 at p=30. A larger value does not reveal whether either activation belongs to the queried object. That requires useful features and relevant training pairs.

NetVLAD: learn assignments and reference points

Hard nearest-center assignments change abruptly at a boundary. NetVLAD uses a softmax assignment and learns its weights, biases and residual reference points. With initial choices w_k=2αc_k and b_k=−α||c_k||², the softmax can express a soft nearest-center rule. During learning these parameter sets are independent. The infinite-α hard-assignment interpretation requires a unique nearest center: tied centers can keep shared probability. NetVLAD layer

aik=exp⁡(wk⊤xi+bk)∑lexp⁡(wl⊤xi+bl),Vk=∑iaik(xi−ck),uk=Vk∥Vk∥2,z=[u1;…;uK]∥[u1;…;uK]∥2.a_{ik}=\frac{\exp(w_k^\top x_i+b_k)}{\sum_l\exp(w_l^\top x_i+b_l)},\qquad V_k=\sum_i a_{ik}(x_i-c_k),\qquad u_k=\frac{V_k}{\|V_k\|_2},\quad z=\frac{[u_1;\ldots;u_K]}{\|[u_1;\ldots;u_K]\|_2}.

Normalize each residual block, then normalize the concatenated vector. This is a different normalization recipe from the original global-only VLAD example. The program implements this complete small aggregation layer and its backward pass, with two clusters and three descriptor coordinates: six assignment weights, two biases and six residual-center coordinates, for 14 trainable parameters. It receives descriptors; no unshown CNN is being trained.

To see the backward calculation, let G_k be the loss gradient after undoing both normalization operations, so it is with respect to V_k. Let A_ik denote the gradient with respect to the assignment probability and Z the softmax logits. Applying the product rule and the softmax Jacobian gives:

Aik=Gk⊤(xi−ck),∂L∂Zik=aik(Aik−∑lailAil),∂L∂xi=∑kaikGk+∑k∂L∂Zikwk,∂L∂ck=−(∑iaik)Gk.A_{ik}=G_k^\top(x_i-c_k),\qquad \frac{\partial L}{\partial Z_{ik}}=a_{ik}\left(A_{ik}-\sum_l a_{il}A_{il}\right), \qquad \frac{\partial L}{\partial x_i}=\sum_k a_{ik}G_k+\sum_k\frac{\partial L}{\partial Z_{ik}}w_k, \qquad \frac{\partial L}{\partial c_k}=-\left(\sum_i a_{ik}\right)G_k.

The two terms in the input gradient have different roles: changing a descriptor changes its residual and changes its assignments. Omitting either is an incorrect backward pass. The program checks every learned parameter and every input coordinate in its independent gradient fixture with central differences. A zero residual block is rejected explicitly; production implementations need a chosen epsilon policy and corresponding derivatives.

The target of training matters as much as the layer. GeM’s paper uses matching and nonmatching pairs with the contrastive loss below. Positive pairs are pulled together; negative pairs cease contributing once their distance reaches the margin τ. Its automatic pair construction still uses data and existing reconstruction machinery; “no human annotation” is not a claim that nothing in the system was previously learned. Pair loss and stated scope

D=∥zi−zj∥2,L(i,j)={12D2,y=1,12max⁡(0,τ−D)2,y=0.D=\|z_i-z_j\|_2,\qquad L(i,j)=\begin{cases}\tfrac12D^2,&y=1,\\ \tfrac12\max(0,\tau-D)^2,&y=0.\end{cases}

Our independent update uses a fixed synthetic target vector and half squared error only to check that all 14 aggregation parameters can receive a consistent gradient. The target is not a label from a retrieval dataset. The loss falls from 0.9930459801 to 0.9911978620; this demonstrates the calculation, not an improvement in retrieval quality. To train a retrieval model, replace this diagnostic with a justified pair/list objective and evaluate on held-out identities or scenes.

Candidate selection can lose the answer before ranking

Exact search compares the query with every stored descriptor. A coarse inverted index assigns gallery vectors to centers offline and stores an ID list per center. At query time it visits a limited number of nearby lists, then computes exact distances inside them. The fixed Faiss IVFFlat tutorial separates training, insertion and search, and exposes the number of probed lists. IVFFlat stores original floating-point vectors; this is different from product quantization. IVF usage Stored vectors and metric declaration

Here is a one-dimensional boundary failure. The query is 0.99, gallery values are 0 and 1.01, and centers are 0 and 2. The query selects center 0, while the true nearest gallery value 1.01 belongs to center 2. Probing only one list returns the wrong neighbor. Probing both returns 1.01. Exact reranking inside the wrong candidate set cannot repair the omission.

The tutorial’s comment about an inner-product default conflicts with the same commit’s constructor declaration, whose default is METRIC_L2. We use explicit squared Euclidean distance and follow the declaration; copying the comment would introduce an error. This example is an original small implementation, not a call to or speed test of Faiss.

For M gallery vectors of dimension d and C coarse centers, our offline assignment costs O(MCd). A query computes O(Cd) center distances, sorts C centers, then evaluates B candidates in O(Bd) and sorts them in O(B log B). Exact search instead computes O(Md) distances and, in this simple implementation, sorts M results. Real systems can use top-k selection, compressed vectors and other indexes. Candidate recall against exact neighbors measures approximation; relevance recall measures whether the answer is useful. Those two recalls can move differently.

An AP score needs its protocol

After removing ignored images, let r_j be the one-based rank of the j-th positive, and R the total positive count. Ordinary non-interpolated average precision averages precision at positive ranks. The fixed Oxford evaluation code instead integrates trapezoids around each positive’s recall increment:

AP⁡=1R∑j=1Rjrj,ℓj={1,rj=1,(j−1)/(rj−1),rj>1,AP⁡Oxford=1R∑j=1Rℓj+j/rj2.\operatorname{AP}=\frac1R\sum_{j=1}^R\frac{j}{r_j},\qquad \ell_j=\begin{cases}1,&r_j=1,\\(j-1)/(r_j-1),&r_j>1,\end{cases}\qquad \operatorname{AP}_{\mathrm{Oxford}}=\frac1R\sum_{j=1}^R\frac{\ell_j+j/r_j}{2}.

A complete ranking [irrelevant,relevant] has AP=0.5 but Oxford trapezoidal AP=0.25. Neither number is an arithmetic mistake. They use different interpolation conventions. The implementation exposes both fields and refuses a supposed full ranking that omits a labeled positive. A truncated-ranking metric needs its own definition rather than silently borrowing the full-list denominator. Actual evaluator

The revisited Oxford/Paris protocol further changes which images are positive or ignored. Easy evaluates easy positives and ignores hard/unclear images. Medium evaluates easy plus hard and ignores unclear. Hard evaluates hard and ignores easy/unclear. Queries without positives in a setting are excluded. Query crops, rather than their full source images, must be used, and query source images are removed from the gallery. These rules are part of the task, not optional preprocessing. Benchmark protocol

P@k=∣top⁡k∩R∣k,R@k=∣top⁡k∩R∣∣R∣,Hit⁡@k=1[∣top⁡k∩R∣>0].P@k=\frac{|\operatorname{top}_k\cap\mathcal R|}{k},\qquad R@k=\frac{|\operatorname{top}_k\cap\mathcal R|}{|\mathcal R|},\qquad \operatorname{Hit}@k=\mathbf1[|\operatorname{top}_k\cap\mathcal R|>0].

Here top-k is taken after ignored items are removed. Precision uses the requested k as its denominator, even for a short returned list; missing slots count as failures. Recall counts how many of all relevant items were retrieved. Hit@k records only whether at least one was found. Some image/text and place-retrieval reports call that last success measure “Recall@k”; write down the exact definition. The author’s fixed P@K helper also limits its denominator using the last positive rank, so our fixed-k result is deliberately not labeled a reproduction of that helper. Evaluator conventions

For multiple queries, average over the specified eligible queries and report how many were excluded. Never use one easy query’s AP to describe a whole system. Keep dataset version, crop policy, distractor gallery, feature training, tie rule and any transductive gallery processing with the result.

Run the failures as well as the successes

Save this as image_retrieval.py and run it with Python3.12 and NumPy1.26.4. It needs no external images, model downloads, Faiss or PyTorch. The supplied pixel extractor takes nonzero, nonoverlapping 2×2 tiles; it is not SIFT or a learned feature extractor. The two fixed VLAD centers are part of the synthetic demonstration, not a fitted real-image vocabulary.

The geometry step keeps mutual nearest tile matches within a descriptor-distance threshold. Each surviving match proposes a translation; exhaustive consensus counts how many other matches agree within a pixel tolerance. It implements neither scale/rotation invariance nor perspective geometry. A repetitive pattern can also make mutual nearest matching ambiguous. For P surviving matches, this small consensus stage uses O(P²) comparisons, after an all-pairs descriptor comparison.

"""Original NumPy teaching examples; no pretrained model or real-image benchmark."""
import json
import numpy as np


def matrix(x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 2 or not all(x.shape) or not np.isfinite(x).all():
        raise ValueError('Expected a nonempty finite matrix')
    return x


def unit(x):
    x = np.asarray(x, dtype=float)
    n = np.linalg.norm(x)
    if not np.isfinite(x).all() or n <= 1e-12 or not np.isfinite(n):
        raise ValueError('A zero or nonfinite vector has no unit direction')
    return x / n


def unit_backward(x, gradient):
    y = unit(x)
    return (gradient - y * np.sum(y * gradient)) / np.linalg.norm(x)


def assignments(x, centers):
    x, centers = matrix(x), matrix(centers)
    if x.shape[1] != centers.shape[1]:
        raise ValueError('Descriptor dimensions differ')
    return ((x[:, None] - centers[None]) ** 2).sum(axis=2).argmin(axis=1)


def bow(x, centers):
    # Raw counts: no implicit corpus IDF or vocabulary training.
    return np.bincount(assignments(x, centers), minlength=len(centers))


def vlad(x, centers):
    x, centers = matrix(x), matrix(centers)
    a = assignments(x, centers)
    residuals = np.zeros_like(centers)
    np.add.at(residuals, a, x - centers[a])
    return unit(residuals.reshape(-1))


def gem(x, p=3.0):
    """Positive activations, scalar p. Return output and analytic derivatives."""
    x = matrix(x)
    if (x <= 0).any() or not np.isfinite(p) or p <= 0:
        raise ValueError('GeM requires positive activations and p > 0 here')
    logs = np.log(x)
    largest = logs.max(axis=0)
    delta = logs - largest
    a = p * delta
    weights = np.exp(a)
    weights /= weights.sum(axis=0)
    log_mean = np.log(np.exp(a).mean(axis=0))
    y = np.exp(largest + log_mean / p)
    dx = y * weights / x
    dp = (y / p) * ((weights * delta).sum(axis=0) - log_mean / p)
    return y, dx, dp


def netvlad(x, w, b, centers):
    """Complete small aggregation layer. No CNN feature extractor is hidden."""
    x, w, centers = matrix(x), matrix(w), matrix(centers)
    b = np.asarray(b, dtype=float)
    if w.shape != centers.shape or x.shape[1] != w.shape[1] or b.shape != (len(w),) or not np.isfinite(b).all():
        raise ValueError('Incompatible NetVLAD shapes')
    logits = x @ w.T + b
    logits -= logits.max(axis=1, keepdims=True)
    a = np.exp(logits)
    a /= a.sum(axis=1, keepdims=True)
    residuals = x[:, None, :] - centers[None, :, :]
    v = (a[:, :, None] * residuals).sum(axis=0)
    # A zero cluster residual is explicitly rejected, not divided by zero.
    rows = np.stack([unit(row) for row in v])
    y = unit(rows.reshape(-1))
    return y, (x, w, centers, a, residuals, v, rows)


def netvlad_backward(cache, gradient):
    x, w, centers, a, residuals, v, rows = cache
    dr = unit_backward(rows.reshape(-1), gradient).reshape(v.shape)
    dv = np.stack([unit_backward(row, grad) for row, grad in zip(v, dr)])
    da = np.einsum('nkd,kd->nk', residuals, dv)
    dz = a * (da - (a * da).sum(axis=1, keepdims=True))
    dx = a @ dv + dz @ w
    dw = dz.T @ x
    db = dz.sum(axis=0)
    dc = -a.sum(axis=0)[:, None] * dv
    return dx, dw, db, dc


def ranking_metrics(order, relevant, ignored=(), k=1):
    """Binary full-list AP plus explicitly different Oxford trapezoidal AP."""
    order = list(order)
    relevant, ignored = set(relevant), set(ignored)
    if len(order) != len(set(order)) or relevant & ignored:
        raise ValueError('Duplicate result IDs or conflicting relevance labels')
    if not isinstance(k, (int, np.integer)) or isinstance(k, bool) or k < 1:
        raise ValueError('k must be a positive integer')
    if not relevant <= set(order):
        raise ValueError('Full-ranking example requires every positive in the list')
    kept = [v for v in order if v not in ignored]
    if not relevant:
        return {'ap': None, 'oxford_ap': None, 'precision': None, 'recall': None, 'hit': None}
    ranks = [i for i, v in enumerate(kept, 1) if v in relevant]
    ap = sum(j / rank for j, rank in enumerate(ranks, 1)) / len(relevant)
    area = sum(((1 if rank == 1 else (j - 1) / (rank - 1)) + j / rank) / 2
               for j, rank in enumerate(ranks, 1)) / len(relevant)
    retrieved = set(kept[:k]) & relevant
    return {'ap': ap, 'oxford_ap': area, 'precision': len(retrieved) / k,
            'recall': len(retrieved) / len(relevant), 'hit': int(bool(retrieved))}


def protocol(easy, hard, unclear, mode):
    e, h, u = set(easy), set(hard), set(unclear)
    if e & h or e & u or h & u:
        raise ValueError('Ground-truth labels must be disjoint')
    if mode == 'easy':
        return e, h | u
    if mode == 'medium':
        return e | h, u
    if mode == 'hard':
        return h, e | u
    raise ValueError('Unknown evaluation protocol')


def search_inputs(query, database, k):
    q = np.asarray(query, dtype=float)
    x = matrix(database)
    if q.shape != (x.shape[1],) or not np.isfinite(q).all() or not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= len(x):
        raise ValueError('Invalid query or k')
    return q, x


def exact_search(query, database, k):
    q, x = search_inputs(query, database, k)
    d = ((x - q) ** 2).sum(axis=1)
    return np.argsort(d, kind='stable')[:k].tolist()


def build_coarse_index(database, centers):
    """Offline assignment to a supplied codebook; no PQ compression."""
    x, c = matrix(database).copy(), matrix(centers).copy()
    a = assignments(x, c)
    return x, c, [np.flatnonzero(a == j) for j in range(len(c))]


def coarse_search(query, index, probes=1, k=1):
    """Query a previously built index, without scanning unselected vectors."""
    x, c, lists = index
    if not isinstance(probes, int) or isinstance(probes, bool) or not 1 <= probes <= len(c):
        raise ValueError('Invalid number of probes')
    query = np.asarray(query, dtype=float)
    if query.shape != (x.shape[1],) or not np.isfinite(query).all() or not isinstance(k,int) or isinstance(k,bool) or not 1 <= k <= len(x):
        raise ValueError('Invalid query or k')
    selected = exact_search(query, c, probes)
    ids = np.sort(np.concatenate([lists[j] for j in selected]))
    if not len(ids):
        return [], []
    d = ((x[ids] - query) ** 2).sum(axis=1)
    order = ids[np.argsort(d, kind='stable')[:k]].tolist()
    return order, ids.tolist()


def patches(image):
    """Raw nonzero 2x2 tiles with their pixel coordinates; not SIFT."""
    image = matrix(image)
    if any(s % 2 for s in image.shape):
        raise ValueError('Even image dimensions required')
    descriptors, positions = [], []
    for y in range(0, image.shape[0], 2):
        for x in range(0, image.shape[1], 2):
            p = image[y:y+2, x:x+2].reshape(-1)
            if np.any(p):
                descriptors.append(p)
                positions.append([x, y])
    if not descriptors:
        raise ValueError('No nonzero patches')
    return np.array(descriptors), np.array(positions)


def translation_consensus(query_image, image, tolerance=0.01, descriptor_tolerance=1e-8):
    """Exhaustive translation hypotheses from mutual nearest raw tiles."""
    if not np.isfinite(tolerance) or tolerance < 0 or not np.isfinite(descriptor_tolerance) or descriptor_tolerance < 0:
        raise ValueError('Invalid geometric tolerance')
    q, qp = patches(query_image)
    d, dp = patches(image)
    distances = ((q[:, None] - d[None]) ** 2).sum(axis=2)
    forward, backward = distances.argmin(axis=1), distances.argmin(axis=0)
    pairs = [(i, j) for i, j in enumerate(forward)
             if backward[j] == i and distances[i,j] <= descriptor_tolerance**2]
    if not pairs:
        return {'inliers': 0, 'matches': 0, 'translation': None}
    shifts = np.array([dp[j] - qp[i] for i, j in pairs])
    counts = (np.linalg.norm(shifts[:, None] - shifts[None], axis=2) <= tolerance).sum(axis=1)
    best = int(counts.argmax())
    return {'inliers': int(counts[best]), 'matches': len(pairs), 'translation': shifts[best].tolist()}


def demo():
    # Six unique tile patterns; shuffling preserves every orderless descriptor.
    tiles = np.array([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1], [1,1,0,0], [1,0,1,0]], dtype=float)
    def mosaic(order):
        return np.block([[tiles[order[3*r+c]].reshape(2,2) for c in range(3)] for r in range(2)])
    query = mosaic(list(range(6)))
    shuffled = mosaic([5, 0, 4, 2, 1, 3])
    shifted = np.pad(query, ((2,2),(2,2)))
    centers = np.array([[0.0]*4, [1.0]*4])
    qdesc, _ = patches(query)
    gallery = [shuffled, shifted]  # Stable similarity tie returns distractor first.
    scores = [float(vlad(qdesc, centers) @ vlad(patches(im)[0], centers)) for im in gallery]
    first = np.argsort(-np.array(scores), kind='stable').tolist()
    geometry = [translation_consensus(query, im) for im in gallery]
    reranked = sorted(first, key=lambda i: -geometry[i]['inliers'])
    before = ranking_metrics(first, {1})
    after = ranking_metrics(reranked, {1})
    # Independent supplied-descriptor training example: full NetVLAD gradients.
    rng = np.random.default_rng(29)
    x = rng.normal(size=(5, 3))
    w, b, c = rng.normal(size=(2, 3)), rng.normal(size=2), rng.normal(size=(2, 3))
    target = unit(rng.normal(size=6))
    y, cache = netvlad(x, w, b, c)
    loss = float(np.sum((y-target)**2) / 2)
    dx, dw, db, dc = netvlad_backward(cache, y-target)
    trained, _ = netvlad(x, w-0.05*dw, b-0.05*db, c-0.05*dc)
    newloss = float(np.sum((trained-target)**2) / 2)
    index = build_coarse_index([[0.], [1.01]], [[0.], [2.]])
    probe1 = coarse_search(np.array([0.99]), index, 1)
    probe2 = coarse_search(np.array([0.99]), index, 2)
    return {'query_pixels': query.tolist(), 'shuffled_pixels': shuffled.tolist(),
            'shifted_pixels': shifted.tolist(), 'global_scores': scores,
            'initial_order': first, 'geometry': geometry, 'reranked_order': reranked,
            'before': before, 'after': after,
            'gem': {str(p): gem(np.array([[1.], [4.]]), p)[0].tolist() for p in [1,3,30]},
            'aggregation_training': {'parameters': w.size+b.size+c.size, 'loss_before': loss,
                                     'loss_after': newloss, 'input_gradient_norm': float(np.linalg.norm(dx))},
            'coarse_probe1': probe1, 'coarse_probe2': probe2,
            'ap_conventions': ranking_metrics(['bad','good'], {'good'})}


if __name__ == '__main__':
    print(json.dumps({k:v for k,v in demo().items() if not k.endswith('_pixels')}, indent=2))

Actual output (pixel arrays are returned by demo() but omitted from the console summary):

{
  "global_scores": [
    1.0000000000000002,
    1.0000000000000002
  ],
  "initial_order": [
    0,
    1
  ],
  "geometry": [
    {
      "inliers": 1,
      "matches": 6,
      "translation": [
        2,
        0
      ]
    },
    {
      "inliers": 6,
      "matches": 6,
      "translation": [
        2,
        2
      ]
    }
  ],
  "reranked_order": [
    1,
    0
  ],
  "before": {
    "ap": 0.5,
    "oxford_ap": 0.25,
    "precision": 0.0,
    "recall": 0.0,
    "hit": 0
  },
  "after": {
    "ap": 1.0,
    "oxford_ap": 1.0,
    "precision": 1.0,
    "recall": 1.0,
    "hit": 1
  },
  "gem": {
    "1": [
      2.5
    ],
    "3": [
      3.1912521494299533
    ],
    "30": [
      3.908639873736984
    ]
  },
  "aggregation_training": {
    "parameters": 14,
    "loss_before": 0.993045980088935,
    "loss_after": 0.9911978619590346,
    "input_gradient_norm": 0.1032709359026662
  },
  "coarse_probe1": [
    [
      0
    ],
    [
      0
    ]
  ],
  "coarse_probe2": [
    [
      1
    ],
    [
      0,
      1
    ]
  ],
  "ap_conventions": {
    "ap": 0.5,
    "oxford_ap": 0.25,
    "precision": 0.0,
    "recall": 0.0,
    "hit": 0
  }
}

Both global similarities print slightly above one because of floating-point rounding. Their common value is effectively one, not evidence of a super-cosine similarity. Gallery ID0 is the rearranged distractor; ID1 is the translated query. The geometry counts are one and six, so the two-image ranking reverses. The AP improvement is for this constructed example only. Increasing descriptor_tolerance may accept wrong local matches; reducing it can reject legitimate photometric changes. Use both kinds of errors when extending the exercise.

Where a plausible result can still be wrong

Global pooling discards spatial arrangements. Geometric verification can recover some instance evidence, but fails when the model of geometry is wrong, when there are too few distinctive correspondences, or when the task deliberately treats different instances as relevant. For semantic search, forcing a common rigid layout may reject good results.

A crop can remove useful background or essential object parts. Higher resolution may preserve small details but increases extraction and storage cost. Query expansion can use good initial matches to build a better query; it can also reinforce an early wrong match. Treat reranking and feedback as new stages to evaluate, not automatic accuracy bonuses.

Training examples must match the target task. Different images of one physical place can be positives for localization, while pictures of different places with similar style may be positives for a semantic browsing task. Duplicate images across train and test can inflate apparent generalization. Fit normalization, projection, vocabulary and thresholds on the declared data, and document any benchmark that permits gallery-dependent processing.

Operational evaluation should separate feature-extraction time, index construction, query latency and reranking cost. Report hardware, gallery size, batch size, memory and tail latency alongside quality. The small code here times none of those production workloads. A gallery update can change relevance counts, IDF weights and approximate candidates, so a score belongs to a versioned gallery.

Four checks before trusting a retrieval score

1. Predict the effect of rearranging patches

If the six tile descriptors are permuted without changing their values, can hard VLAD or GeM distinguish the original arrangement?

Answer: No. Their sums are invariant to permutation. The local tiles still encode their own internal pixel arrangement, but their positions across the image have disappeared. Keeping positions for a separate geometry test can recover evidence that these global vectors lack.

2. Compute two AP values

For the complete list [negative,positive,negative,positive], calculate ordinary AP and the Oxford trapezoidal value, with no ignored items.

Answer: The positive ranks are2 and4, so ordinary AP is (1/2+2/4)/2=1/2. The trapezoids contribute ((0+1/2)/2)/2=1/8 and ((1/3+1/2)/2)/2=5/24, totaling1/3. Record the protocol instead of comparing the values as if they were the same measure.

3. Make approximate search fail

Use query0.99, gallery[0,1.01] and centers[0,2]. Explain why exact reranking after one probed list cannot find the nearest point. What changes with two probes?

Answer: Query0.99 selects the list around0, but1.01 is assigned to2. It is absent from the first candidate set, regardless of the reranker’s accuracy. Two probes include both points and recover1.01. Increasing probes addresses candidate omission, not a poor descriptor’s relevance errors.

4. Design a fair instance-retrieval comparison

You replace global features with a learned embedding and claim improvement. What must remain comparable, and which failure slices should be inspected?

Answer: Fix relevant-instance definitions, query crops, gallery/distractors, ignored images, AP convention and test identities. Declare feature-training data and any gallery-dependent fitting; separate exact feature quality from approximate-index loss. Inspect viewpoint/lighting changes, repeated structures, small query objects and semantically similar wrong instances. Report query counts, latency/memory conditions and failed examples rather than only the best query.

Follow the ideas without collapsing their dates

Video Google appeared at ICCV2003, connecting local visual words with text-style retrieval. VLAD’s CVPR2010 paper replaced counts with compact residual aggregation. Those are conference-year records, not invented exact release days. Video Google VLAD

NetVLAD’s first preprint was submitted on2015-11-23, before its CVPR2016 paper. GeM’s paper first appeared on arXiv on2017-11-03; the later journal publication and revisions should not overwrite that first-submission date. The revisited Oxford/Paris paper was first submitted on2018-03-29 and appeared at CVPR2018. These dates identify particular manuscripts, not the first time anyone thought of pooling, places or evaluation. NetVLAD history GeM history Benchmark history

The linked fixed author code helps compare formulas with implementation. In this article the 18 numerical checks independently cover every aggregation parameter, GeM derivatives, all binary rankings up to length6, coarse-list misses and actual pixel rearrangement. They establish those small calculations. They do not establish benchmark accuracy, human peer review, or mastery from reading the page.

Make a prediction, then check

Why can exact reranking fail to retrieve the best gallery image?

Choose one answer

Learning objectives

  • Define instance, semantic and near-duplicate relevance before ranking.
  • Derive visual aggregation and verify complete NetVLAD and GeM gradients.
  • Diagnose lost geometry separately from approximate-candidate omissions.
  • State AP interpolation, ignored items and query eligibility explicitly.

Prerequisites & connections

Explore related knowledge →

References

  1. Image retrieval: Video Google original method
    Josef Sivic; Andrew Zisserman · 2003
  2. Aggregating local descriptors into a compact image representation
    Hervé Jégou; Matthijs Douze; Cordelia Schmid; Patrick Pérez · 2010
  3. Fine-tuning CNN Image Retrieval with No Human Annotation, v1
    Filip Radenović; Giorgos Tolias; Ondřej Chum · 2017
  4. NetVLAD: CNN architecture for weakly supervised place recognition, CVPR2016
    Relja Arandjelović; Petr Gronat; Akihiko Torii; Tomas Pajdla; Josef Sivic · 2016
  5. Revisiting Oxford and Paris: Large-Scale Image Retrieval Benchmarking
    Filip Radenović; Ahmet Iscen; Giorgos Tolias; Yannis Avrithis; Ondřej Chum · 2018
  6. Fixed author GeM implementation
    VRG, CTU Prague contributors · 2022
  7. Fixed author Oxford and Paris evaluation implementation
    VRG, CTU Prague contributors · 2022
  8. Faiss fixed IVFFlat tutorial
    Meta Platforms and Faiss contributors · 2026
  9. Faiss fixed IVFFlat storage and constructor declaration
    Meta Platforms and Faiss contributors · 2026
  10. Netvlad History submission record
    Relja Arandjelović; Petr Gronat; Akihiko Torii; Tomas Pajdla; Josef Sivic · 2015
  11. Gem History submission record
    Filip Radenović; Giorgos Tolias; Ondřej Chum · 2017
  12. Revisit History submission record
    Filip Radenović; Ahmet Iscen; Giorgos Tolias; Yannis Avrithis; Ondřej Chum · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped original image-retrieval papers and fixed author/Faiss sources; all14 aggregation parameters and12 inputs central differences, GeM derivatives, exhaustive binary rankings, candidate misses, pixel geometry, bilingual comparison and computed diagram binding. Not human peer review or a real-image benchmark reproduction.

  • Eighteen numerical tests plus four bilingual/output/metadata/diagram checks. All14 NetVLAD parameters and12 inputs central differences, GeM input/exponent derivatives, scalar aggregation, all binary rankings length1-6, ignore/empty/protocol handling, coarse-list misses and actual tile geometry.
  • Compared full bilingual arguments, eight display equations, complete code/output, four explained exercises and12 scoped sources. Distinguish instance/semantic relevance, diagnostic target fitting from retrieval training, original VLAD from intra-normalized NetVLAD, ordinary AP from Oxford trapezoids, and fixed-k precision from author helper. Preserve Faiss comment/declaration conflict and untested benchmark scope.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.