【发布时间】:2021-08-29 13:20:36
【问题描述】:
我正在尝试使用预训练的 bert 模型和转换器进行语义搜索。我正在使用 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 colab 中运行相同的程序时,没有返回错误。我现在在 Windows 10 本地电脑上运行这个程序
我得到了答案,我们必须将 np.array(range(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')
【问题讨论】:
-
我建议添加您的解决方案作为答案。允许并鼓励原始发帖者在找到解决方案时回答自己的问题。
标签: nlp bert-language-model huggingface-transformers sentence