图像检索:向量相似,答案就相关吗?
Image retrieval
从视觉聚合到几何精排,验证NetVLAD完整梯度,区分候选召回、图片相关性与不同AP协议。
image-retrieval找这栋楼,还是找相似的楼?
假设你拍下一扇门,去旅行照片库里搜索。另一栋楼上风格相似的门,可能适合拿来找装修灵感;如果你想确认眼前这个入口的位置,它就是错误结果。两套系统都能返回“看起来挺像”的图片,但回答的不是同一个问题。
图像检索根据查询给图库中的图片排序。查询可以是图片、局部裁剪、文字或它们的组合。实例检索要找同一个物体或地点在不同视角、光照、遮挡下的照片;语义检索要找类别、属性或含义相符的图片;近重复检索则要找同一张底图经过缩放等修改后的版本。这些是不同的相关性规则,不能统称“找最近的向量”就算定义清楚。Video Google在电影帧中搜索用户圈出的物体;NetVLAD最初针对地点识别。它们的任务也说明,分类器对某个类别的高分,不自动等于一个好用的实例描述子。物体查询 地点识别
先试能回答问题的低成本基线。文件名、时间戳或商品ID可能已经能定位记录。密码学文件哈希可以识别字节完全相同的文件,但重新编码JPEG就会改变字节,即使图片看起来一样。颜色直方图是有用的视觉基线,也会丢掉颜色出现在哪里的信息。使用学习模型时保留这些基线,检验新表示究竟解决了哪类错误。
这里有三个独立决定:什么算相关、如何表示图片、搜索实际查看哪些图库条目。索引再好,也找不回表示已经丢掉的信息;描述子再好,如果候选筛选根本没访问正确图片,它仍然不会出现在结果中。
下面的程序把这件事做成可运行的反例。它生成六个不同的小图块,再打乱它们拼成另一张图。全局无序描述子看到的仍是同一组图块,因此两张图得分几乎一样;按固定规则打破并列时,干扰图排在前面。再检查局部匹配能否共同支持一个平移,正确图片才排到第一。这是合成反例,不表示所有真实检索任务都该用平移验证。
表示、候选与证据
先指定表示,距离才有含义
令q为查询,I为图库图片。特征提取与聚合规则给出f(q)和f(I),把各个非零向量归一化为z。下面的恒等式解释了:为什么对单位向量,按平方欧氏距离从小到大排,与按内积从大到小排是一回事。
排序时常数2可以消去。不做归一化,较大的向量范数可能主导内积,两种排序就不一定相同。零向量没有余弦方向;程序明确拒绝它,而不制造一个看似确定的匹配。按图库顺序处理并列能让演示复现,但不能证明并列中的第一项更相关。
从视觉词到残差
取N个D维局部描述子x_i,以及在适当参考数据上拟合的K个中心c_k。硬分配把每个描述子交给最近中心。视觉词袋统计分配次数;VLAD则累计带符号的残差,保留特征偏向中心哪一侧的信息:
降维前VLAD有KD个坐标,计数向量只有K个。若一维中心为0和2,描述子为0.2、0.3、1.7,那么计数是[2,1],残差是[0.5,-0.3]。2010年原论文对这个残差向量做整体L2归一化。后来的归一化和压缩变体应分别说明,不能混成同一版本。原始VLAD
视觉词的类比也引出了全库加权与倒排列表。常见IDF变体会降低那些出现在很多图库图片里的词的权重;文档频率的定义、平滑方法与拟合集合必须固定。本例的计数函数没有实现IDF,也没有训练词表,小中心是直接给定的。Video Google的视觉词表与加权排序提供历史联系,不意味着所有后来的词袋配方都与它完全相同。视觉词表与加权
计数和残差求和都不保留输入描述子的顺序。把描述子重新排列,向量仍然一样。局部描述子可以编码自身图块内部的几何形状,但这不等于恢复了不同图块在整张图里的位置。打乱图块的反例正是利用了这个区别。
GeM:一个强响应应占多大分量?
卷积特征图给出正激活x_ik,i表示位置,k表示通道。广义均值池化为每个通道输出一个数。p=1时它是算术平均;p不断增大时趋近最大值。较大的p更强调强响应,但强响应可能来自目标,也可能来自背景干扰物。这是需要验证的建模选择,不是普遍有效的提升。GeM定义
对log g_k = log S_k / p求导就得到这两个式子。第一个说明各个空间位置收到多少梯度,第二个让训练能够调整p。程序使用各通道共享的正p,并要求输入严格为正;先减去最大的对数激活再做指数运算,避免直接算巨大的幂。作者固定版本的PyTorch辅助函数则先把激活截到正数下限。下限处及其以下的行为会受截断影响,本例的严格正数域没有冒充那里的边界梯度。固定GeM实现
对于激活[1,4],程序在p=1时输出2.5,p=3时约3.1913,p=30时约3.9086。数值变大并不能告诉你哪处激活属于查询物体;那需要有用的特征与相关的训练配对。
NetVLAD:同时学习分配和参照点
硬最近中心分配跨过边界时会突变。NetVLAD使用softmax软分配,学习分配权重、偏置和残差参照点。若初始设w_k=2αc_k、b_k=−α||c_k||²,softmax可以表示柔和的最近中心规则;进入学习后,这几组参数相互独立。把α趋于无穷理解成硬分配,需要最近中心唯一;中心并列时仍可能分摊概率。NetVLAD聚合层
先归一化每个残差块,再归一化拼接后的整体向量。这与最初只做整体归一化的VLAD例子不同。程序完整实现了这个小聚合层及其反向传播:两个簇、三个描述子坐标,共六个分配权重、两个偏置、六个残差中心坐标,即14个可训练参数。它接收给定描述子,没有在幕后训练一套未展示的CNN。
看反向计算时,令G_k表示反向穿过两次归一化后、损失对V_k的梯度;A_ik表示损失对分配概率的梯度,Z表示softmax之前的logit。乘积法则加上softmax雅可比给出:
输入梯度的两项作用不同:改变一个描述子,既改变残差,也改变它被分到各中心的概率。漏掉任意一项都会算错反向传播。程序用中心差分独立检查梯度夹具中的每个可学参数与每个输入坐标。零残差块被显式拒绝;生产实现需要选择epsilon规则,并使用与之相符的导数。
训练目标与聚合层同样重要。GeM论文对匹配/不匹配图像对使用下面的对比损失。正对被拉近;负对距离达到间隔τ后便不再贡献损失。自动配对仍依赖数据与既有重建方法,“无人工标注”不表示系统里此前没有任何学习过程。配对损失与范围
本例的独立更新只用固定合成目标向量和二分之一平方误差,检验14个聚合参数能否得到一致的梯度;目标不是检索数据集的标签。损失从0.9930459801降到0.9911978620,证明的是这段计算,而不是检索质量改善。若要训练检索模型,需要换成有依据的配对或列表目标,并在保留的物体身份或场景上评测。
排序前,候选筛选就可能丢掉答案
精确搜索把查询与所有已存描述子比较。粗粒度倒排索引先在离线阶段把图库向量分配给中心,每个中心保存一组ID。查询时只探查若干邻近列表,再精确计算列表内部的向量距离。固定Faiss IVFFlat教程把训练、插入、搜索分开,并提供探查列表数量参数。IVFFlat保存原始浮点向量,这与乘积量化不同。IVF用法 存储与距离声明
看一个一维边界错误:查询是0.99,图库值是0和1.01,中心是0和2。查询选择中心0,而真正最近的图库值1.01被分在中心2。只探一个列表会返回错误邻居,探两个才找回1.01。在错误候选集合内部精排,修复不了候选遗漏。
教程中“默认使用内积”的注释,与同提交的构造函数声明冲突;声明的默认值是METRIC_L2。这里明确使用平方欧氏距离,并以声明为准,直接抄注释会引入错误。程序是原创的小规模实现,不是调用Faiss,也不是测量它的速度。
若图库有M个d维向量、C个粗中心,离线分配需要O(MCd)计算。本例每次查询花O(Cd)算中心距离,排序C个中心,再对B个候选花O(Bd)算距离并以O(B log B)排序。精确搜索则花O(Md)算距离,并在这个简单实现中排序M个结果。实际系统可以用top-k选择、压缩向量和其他索引。以精确近邻为参照的候选召回率衡量近似程度,以相关图片为参照的召回率衡量答案是否有用;二者可能朝不同方向变化。
报AP之前,先报协议
去掉忽略图片后,令r_j为第j个正例的一起始排名,R为全部正例数。普通非插值平均精度,对每个正例出现时的精度求平均;固定Oxford评测代码则在各次召回增量两端作梯形积分:
完整排名[无关,相关]的普通AP是0.5,Oxford梯形AP却是0.25。两者都没有算术错误,只是插值约定不同。程序暴露两个字段,并拒绝那种声称是完整排名、实际漏掉已标注正例的输入。截断排名应另行定义指标,不能默默借用完整列表的分母。实际评测实现
重新标注的Oxford/Paris协议还改变了哪些图片算正例、哪些应忽略。Easy评估easy正例,忽略hard/unclear;Medium评估easy和hard,忽略unclear;Hard评估hard,忽略easy/unclear。某设置下没有正例的查询不参与平均。查询必须使用裁剪区域而非完整源图,查询源图也要从图库移除。这些规则属于任务本身,不是可随意省略的预处理。基准协议
这里的top-k在移除忽略项后取。精确率使用请求的k作分母,即使返回列表较短也一样,缺少的位置按失败计;召回率统计全部相关图片中找回了多少;Hit@k只记录是否至少找回一个。有些图文或地点检索报告把最后这种成功率称为“Recall@k”,因此必须写出具体定义。作者固定版本的P@K辅助函数还用最后一个正例的排名限制分母,所以本例固定k的数值不会被标成该函数的复现。评测约定
多个查询求平均时,按规定的有效查询集合统计,并报告排除了多少个。不能拿一条容易查询的AP概括整个系统。结果要同时保留数据集版本、裁剪规则、干扰图库、特征训练方式、并列规则,以及是否使用图库本身参与处理。
把失败也一起跑出来
将程序保存为image_retrieval.py,使用Python3.12和NumPy1.26.4运行。不需要外部图片、模型下载、Faiss或PyTorch。像素提取器只取非零、互不重叠的2×2图块;它不是SIFT,也不是学习特征。两个固定VLAD中心属于合成演示,不是用真实图像训练出的视觉词表。
几何步骤保留描述子距离在阈值内的相互最近图块匹配。每个有效匹配提出一个平移,再用穷举共识统计多少其他匹配在像素容差内同意它。这里没有尺度/旋转不变性,也没有透视几何;重复纹理还可能让相互最近匹配产生歧义。对于P个保留匹配,这个小共识过程需要O(P²)比较,之前还要做局部描述子的全对比较。
"""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))
实际输出(demo()会返回像素数组,控制台摘要省略了它们):
{
"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
}
}
两个全局相似度打印出来略大于1,是浮点舍入造成的。它们实际都约等于1,并非出现了“超过余弦”的相似性。图库ID0是打乱后的干扰图,ID1是平移后的查询图;几何内点数分别为1和6,所以两图排名反转。AP改善仅针对这个构造例子。增大descriptor_tolerance可能接纳错误局部匹配,减小它则可能拒绝正常光照变化;扩展练习时两类错误都要检查。
结果看起来合理,仍可能答错
全局池化会丢掉空间排列。几何验证可以补回一部分实例证据,但几何模型不合适、独特对应太少,或者任务本来就允许不同实例相关时,它也会失败。对语义搜索强求一致的刚性布局,可能反而拒绝好结果。
裁剪可能去掉有用背景,也可能切掉关键目标部分。较高分辨率能保留小细节,却增加提取与存储成本。查询扩展可以利用正确的初始结果改进查询,也可能强化一次早期错配。精排与反馈是需要评测的新阶段,不是自动附送的准确率提升。
训练样本必须符合目标任务。同一真实地点的不同照片可作为定位正例,不同地点但风格相近的照片则可能适合语义浏览。训练与测试之间的重复图片会夸大泛化表现。归一化、投影、词表与阈值应在声明的数据上拟合;若某个协议允许依赖图库的处理,也要明确记录。
工程评测应区分特征提取时间、建索引时间、查询延迟和精排成本。质量之外,还要报告硬件、图库规模、批大小、内存与尾部延迟。本例没有计时这些生产负载。图库更新也会改变正例数量、IDF权重和近似候选,因此每个分数都对应一个有版本的图库。
信任检索分数之前的四个检查
1. 预测重排图块的后果
六个图块描述子只改变排列、不改变数值,硬VLAD或GeM能区分原来的布局吗?
答案:不能。它们的求和对排列不变。局部图块仍包含自身内部的像素排列,但图块之间在整张图里的位置已经丢失。另行保留位置用于几何检查,可以补充全局向量缺少的证据。
2. 算两种AP
完整列表为[负例,正例,负例,正例],没有忽略项。分别计算普通AP与Oxford梯形值。
答案:正例排名为2和4,普通AP为(1/2+2/4)/2=1/2。两个梯形分别贡献((0+1/2)/2)/2=1/8与((1/3+1/2)/2)/2=5/24,总和是1/3。应记录所用协议,不能把这两个值当成同一个指标直接比较。
3. 让近似搜索漏掉答案
使用查询0.99、图库[0,1.01]、中心[0,2]。解释为什么只探一个列表后再精排,仍无法找到最近点。探两个列表会怎样?
答案:查询0.99选择中心0的列表,但1.01被分配给中心2,所以它根本不在第一轮候选里,与精排算得准不准无关。探两个列表会同时访问两点,找回1.01。增大探查数修复的是候选遗漏,而不是描述子本身把不相关图片当成相似的错误。
4. 设计公平的实例检索比较
你用学习嵌入替换全局特征,并宣称结果改善。哪些条件必须可比,又该查看哪些失败分组?
答案:固定相关实例定义、查询裁剪、图库/干扰项、忽略图片、AP约定与测试身份。说明特征训练数据和任何依赖图库的拟合,区分精确搜索下的特征质量与近似索引带来的损失。检查视角/光照变化、重复结构、小查询目标,以及语义相近却不是同一实例的错配;报告查询数、延迟/内存条件和失败案例,不只挑最好的一次查询。
沿着方法追溯,别把日期合并
Video Google发表于ICCV2003,把局部视觉词与文字式检索联系起来;VLAD的CVPR2010论文用紧凑残差聚合替代计数。这些记录使用会议年份,不虚构精确到日的发布日期。Video Google VLAD
NetVLAD首个预印本提交于2015-11-23,早于其CVPR2016论文。GeM论文于2017-11-03首次出现在arXiv,后续期刊出版与修订不能覆盖首版提交日期。重新标注Oxford/Paris的论文首版提交于2018-03-29,发表于CVPR2018。这些日期对应特定稿件,不表示那一天才有人想到池化、地点或评测。NetVLAD历史 GeM历史 基准历史
固定作者代码可用于对照公式和实现。本篇的18项计算检查独立覆盖每个聚合参数、GeM导数、长度不超过6的全部二值排名、粗列表漏检和实际像素重排;它们证明这些小计算符合预期,不能证明基准准确率、人工同行审校,或读完即已精通。
先判断,再看解释
为什么精确重排仍可能找不回最好的图库图片?
学习目标
- 排序前定义实例、语义与近重复的相关性。
- 推导视觉聚合并验证完整NetVLAD与GeM梯度。
- 区分几何信息丢失与近似候选遗漏。
- 明确AP插值、忽略项和有效查询规则。
先修与延伸
查看知识关联图 →参考文献
- Image retrieval: Video Google original method
Josef Sivic; Andrew Zisserman · 2003 - Aggregating local descriptors into a compact image representation
Hervé Jégou; Matthijs Douze; Cordelia Schmid; Patrick Pérez · 2010 - Fine-tuning CNN Image Retrieval with No Human Annotation, v1
Filip Radenović; Giorgos Tolias; Ondřej Chum · 2017 - NetVLAD: CNN architecture for weakly supervised place recognition, CVPR2016
Relja Arandjelović; Petr Gronat; Akihiko Torii; Tomas Pajdla; Josef Sivic · 2016 - Revisiting Oxford and Paris: Large-Scale Image Retrieval Benchmarking
Filip Radenović; Ahmet Iscen; Giorgos Tolias; Yannis Avrithis; Ondřej Chum · 2018 - Fixed author GeM implementation
VRG, CTU Prague contributors · 2022 - Fixed author Oxford and Paris evaluation implementation
VRG, CTU Prague contributors · 2022 - Faiss fixed IVFFlat tutorial
Meta Platforms and Faiss contributors · 2026 - Faiss fixed IVFFlat storage and constructor declaration
Meta Platforms and Faiss contributors · 2026 - Netvlad History submission record
Relja Arandjelović; Petr Gronat; Akihiko Torii; Tomas Pajdla; Josef Sivic · 2015 - Gem History submission record
Filip Radenović; Giorgos Tolias; Ondřej Chum · 2017 - Revisit History submission record
Filip Radenović; Ahmet Iscen; Giorgos Tolias; Yannis Avrithis; Ondřej Chum · 2018
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 十八项数值加四项双语/输出/元数据/图示检查;全部14聚合参数和12输入中心差分、GeM输入/p梯度、标量聚合、长度1—6全部二值排名、忽略/空查询/协议、粗列表漏检与实际图块几何。
- 完整双语论证、八公式、全部代码/输出、四组解释答案及十二限定来源逐项对照;区分实例/语义、诊断目标拟合/检索训练、原VLAD/簇内归一化、普通AP/Oxford梯形与固定k/作者分母。保留Faiss注释声明冲突与未复现基准的限制。
核对的来源位置:
- Image retrieval: Video Google original method · Physical pages 3-4 fully read; page 1 title, authors and opening abstract. Not the full spatial-verification algorithm.
- Aggregating local descriptors into a compact image representation · Physical pages 2-3 fully read; page 1 title, authors and opening abstract.
- Fine-tuning CNN Image Retrieval with No Human Annotation, v1 · Physical pages 4-5 fully read; page 4 visually inspected; page 1 title, authors, abstract and opening introduction.
- NetVLAD: CNN architecture for weakly supervised place recognition, CVPR2016 · Physical pages 3-4 fully read; page 4 visually inspected; page 1 title, authors and opening abstract.
- Revisiting Oxford and Paris: Large-Scale Image Retrieval Benchmarking · Physical page 3 fully read; page 1 title, authors and opening abstract. No benchmark rerun.
- Fixed author GeM implementation · Lines 1-88 read: GeM clamp/power/pool, MAC/SPoC and beginning of regional pooling; only GeM adopted for comparison.
- Fixed author Oxford and Paris evaluation implementation · Entire file read, including trapezoidal AP, ignored IDs, empty-positive exclusion, P@K denominator and E/M/H mappings. Not executed.
- Faiss fixed IVFFlat tutorial · Entire fixed tutorial read: explicit METRIC_L2, train/add/search and nprobe. Default metric comment conflicts with header; not adopted.
- Faiss fixed IVFFlat storage and constructor declaration · Lines 1-53 read: raw float storage comment and constructor default METRIC_L2. Remaining implementation not read.
- Netvlad History submission record · Title, authors and submission history; method read in CVPR2016 PDF separately. First submission 2015-11-23.
- Gem History submission record · Title, authors and submission history; v2 dated 2018-07-10, method read from v1. First submission 2017-11-03.
- Revisit History submission record · Title, authors and submission history; method read in CVPR2018 PDF separately. First submission 2018-03-29.
相关主题