我有一个 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)
但这会导致以下错误:
向量=索引.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 行,重建中 返回 _swigfaiss.IndexFlat_reconstruct(self, key, recons)
TypeError:在方法“IndexFlat_reconstruct”中,参数 2 类型 'faiss::Index::idx_t' python-BaseException
有人知道我的方法有什么问题吗?
这是我手动找到的唯一方法。
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
您可以使用它来获取添加到索引中的所有嵌入,
# 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)
参考