【问题标题】:faiss: How to retrieve vector by id from pythonfaiss:如何从 python 中通过 id 检索向量
【发布时间】:2022-01-07 16:53:01
【问题描述】:

我有一个 faiss 索引,想在我的 python 脚本中使用一些嵌入。嵌入的选择应该由 id 完成。由于 faiss 是用 C++ 编写的,所以 swig 被用作 API。

我猜我需要的函数是reconstruct

/** Reconstruct a stored vector (or an approximation if lossy coding)
     *
     * this function may not be defined for some indexes
     * @param key         id of the vector to reconstruct
     * @param recons      reconstucted vector (size d)
     */
    virtual void reconstruct(idx_t key, float* recons) const;

因此,我在python中调用了这个方法,例如:

vector = index.reconstruct(0)

但这会导致以下错误:

向量 = index.reconstruct(0) 文件 "lib/python3.8/site-packages/faiss/init.py", 第 406 行,在 replacement_reconstruct self.reconstruct_c(key, swig_ptr(x)) 文件“lib/python3.8/site-packages/faiss/swigfaiss.py”, 第 1897 行,在重建中 return _swigfaiss.IndexFlat_reconstruct(self, key, recons)

TypeError:在方法“IndexFlat_reconstruct”中,类型的参数 2 'faiss::Index::idx_t' python-BaseException

有人知道我的方法有什么问题吗?

【问题讨论】:

  • 我猜reconstruct 替换了索引中的向量。好像它需要一个向量作为第二个参数

标签: python c++ swig faiss


【解决方案1】:

这是我手动找到的唯一方法。

import faiss
import numpy as np

a = np.random.uniform(size=30)
a = a.reshape(-1,10).astype(np.float32)
d = 10
index = faiss.index_factory(d,'Flat', faiss.METRIC_L2)
index.add(a)

xb = index.xb
print(xb.at(0) == a[0][0])

输出:

True

你可以通过循环获得任何向量

required_vector_id = 1
vector = np.array([xb.at(required_vector_id*index.d + i) for i in range(index.d)])
    
print(np.all(vector== a[1]))

输出:

True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多