如何在 1000 万+ 语料库上使用 BERT 执行文本相似度?使用 LSH/ANNOY/fiass 还是 sklearn?

问题描述

我的想法是为数据库中的所有文本提取 CLS 标记并将其保存在 CSV 或其他地方。因此,当出现新文本时,我必须使用一些近似值,例如 Cosine Similarity/JAccard/MAnhattan/Euclidean 或此处给出的 LSH,ANN (ANNOY,sklearn.neighbor) ,而不是使用 faiss 或其他距离。那怎么办呢?我的代码如下:

PyTorch

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
input_ids = torch.tensor(tokenizer.encode("Hello,I am a text")).unsqueeze(0)  # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple

使用 Tensorflow:

import tensorflow as tf
from transformers import BertTokenizer,TFBertModel

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = TFBertModel.from_pretrained('bert-base-uncased')
input_ids = tf.constant(tokenizer.encode("Hello,my dog is cute"))[None,:]  # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple

我认为可以将 CLS 标记为:(如有错误,请更正

last_hidden_states = outputs[0]
cls_embedding = last_hidden_states[0][0]

请告诉我这是否是正确的使用方式,我该如何使用 LSH,ANNOT,faiss 或类似的东西?

所以对于每个文本,都会有一个 768 长度向量,我们可以创建一个 N(No of texts 10M)x768 矩阵,我如何找到 Index top-5 个数据点(文本)与给定的图像/嵌入/数据点最相似?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)