在 FAISS 相似性搜索中使用迭代器获取下一个(k)

问题描述 投票:0回答:1

在 FAISS 中,构建索引(IVF、HNSW 或 LSH)后,您可以根据查询 q_x 获得 k 最近邻。

在 FAISS 中进行初始向量搜索(假设 k = 50)后,我想要获得更多 NN(即 51、52、53..),直到满足为空间计算设置的标准。 (我正在结合空间和语义相似性搜索。)

有没有一种方法可以从 NN 列表中获取下一个(k),而不必用 k=51、然后 k=52 等等重新开始搜索?

import faiss
import numpy as np


d = 128  # dimension of vectors
index = faiss.IndexFlatL2(d)

# Add some vectors to the index
np.random.seed(123)
xb = np.random.random((1000, d)).astype('float32')
index.add(xb)

# Query vector
xq = np.random.random((1, d)).astype('float32')

def incremental_knn(index, xq, k, step_size):
    """Simulate an iterator-like behavior to get the next k-NN."""
    start = 0
    while True:
        # Incrementally increase the number of nearest neighbors
        k_next = start + step_size
        D, I = index.search(xq, k_next)  # Perform the search
        yield I[0][start:k_next], D[0][start:k_next]  # Return new results
        start = k_next  # Update starting point for the next iteration
        if k_next >= k:
            break

# Simulate fetching k-NN incrementally
step_size = 5  # Fetch 5 neighbors at a time
k = 20  # Total number of neighbors to fetch
for neighbors, distances in incremental_knn(index, xq, k, step_size):
    print(f"Next batch of neighbors: {neighbors}, distances: {distances}")

到目前为止我发现的唯一方法是增加 k 并使用新向量进行计算。

python knn faiss vector-search approximate-nn-searching
1个回答
0
投票

根据 Pincone 上的 FAISS 教程,IndexFlatL2 执行详尽的搜索,即将您的查询与索引中的每个向量进行比较。 因此,我希望搜索的运行时间或多或少独立于您对 k 的选择。所以,我首先测试一下 k 对运行时的影响。

如果大的 k 对运行时的影响可以忽略不计,根据您的用例,我会将 k 设置得足够大或设置为数据集的大小。

如果您使用更高效的索引结构和近似 KNN 搜索,我认为 FAISS 不可能实现高效的增量搜索。另一种方法是使用范围搜索。

© www.soinside.com 2019 - 2024. All rights reserved.