c++ faiss:如何从python中通过id检索vector

ruarlubt  于 2023-08-09  发布在  Python
关注(0)|答案(2)|浏览(152)

我有一个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)


但这会导致以下错误:
vector = index.reconstruct(0)File“lib/python3.8/site-packages/faiss/init.py”,line 406,in replacement_reconstruct self.reconstruct_c(key,swig_ptr(x))File“lib/python3.8/site-packages/faiss/swigfaiss.py“,line 1897,in reconstruct return _swigfaiss.IndexFlat_reconstruct(self,key,recons)
TypeError:in method 'IndexFlat_reconstruct',argument 2 of type 'faiss::Index::idx_t' python-BaseException
有人知道我的方法有什么问题吗?

ctrmrzij

ctrmrzij1#

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

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

3npbholx

3npbholx2#

你可以得到你添加到索引中的所有嵌入,

# Number of docs added to your index
num_docs = index.ntotal
# Get the dimension of your embeddings
embedding_dimension = index.d

embeddings = faiss.rev_swig_ptr(index.get_xb(), num_docs*embedding_dimension).reshape(num_docs, embedding_dimension)

字符串

参考资料

  • github repo中的FAISS测试用例

相关问题