我试图用预先训练好的伯特模型和变压器进行语义搜索。我在使用Facebook AI库Faiss.
守则是:
encoded_data = model.encode(df.Plot.tolist())
encoded_data = np.asarray(encoded_data.astype('float32'))
index = faiss.IndexIDMap(faiss.IndexFlatIP(768))
index.add_with_ids(encoded_data, np.array(range(0, len(encoded_data))))
faiss.write_index(index, 'movie_plot.index')它返回的错误是:
TypeError Traceback (most recent call last)
<ipython-input-19-c09b9ccadf2a> in <module>
----> 1 index.add_with_ids(encoded_data, np.array(range(0, len(encoded_data))))
2 faiss.write_index(index, 'movie_plot.index')
~\t5\lib\site-packages\faiss\__init__.py in replacement_add_with_ids(self, x, ids)
233
234 assert ids.shape == (n, ), 'not same nb of vectors as ids'
--> 235 self.add_with_ids_c(n, swig_ptr(x), swig_ptr(ids))
236
237 def replacement_assign(self, x, k, labels=None):
~\t5\lib\site-packages\faiss\swigfaiss.py in add_with_ids(self, n, x, xids)
4950
4951 def add_with_ids(self, n, x, xids):
-> 4952 return _swigfaiss.IndexIDMap_add_with_ids(self, n, x, xids)
4953
4954 def add(self, n, x):
TypeError: in method 'IndexIDMap_add_with_ids', argument 4 of type 'faiss::IndexIDMapTemplate< faiss::Index >::idx_t const *'当我在google中运行相同的程序时,没有返回错误。我现在在windows 10本地pc中运行这个程序
I得到了答案,我们必须将np.array(范围0,len(Encoded_data))转换为int64
encoded_data = model.encode(df.Plot.tolist())
encoded_data = np.asarray(encoded_data.astype('float32'))
index = faiss.IndexIDMap(faiss.IndexFlatIP(768))
ids = np.array(range(0, len(df)))
ids = np.asarray(ids.astype('int64'))
index.add_with_ids(encoded_data, ids)
faiss.write_index(index, 'movie_plot.index')发布于 2021-06-14 20:40:03
在完成了encoded_data.astype('float32')之后,您可以转换np.asarray(encoded_data),例如:
np.asarray(encoded_data).astype('float32')发布于 2022-01-05 03:52:16
Faiss add_with_ids()只接受np.int64 dtype的ids。
我没有找到这个数据类型需求的Python文档,但是这个链接https://faiss.ai/cpp_api/struct/structfaiss_1_1Index.html (尽管它在c++中)显示了它的id数据类型。
https://stackoverflow.com/questions/67956633
复制相似问题