ELMO 嵌入可以用来找到 n 个最相似的句子吗?

人工智能 自然语言处理 词嵌入
2021-10-22 11:55:35

假设我有一个句子列表,它只是一个字符串列表。我需要一种将一些输入字符串与这些句子进行比较以找到最相似的方法。ELMO 嵌入可以用来训练一个模型吗?n与输入字符串最相似的句子?

作为参考,gensim 提供了一个可以在字符串列表上训练的doc2vec模型,然后您可以使用训练后的模型从某个输入字符串中推断出一个向量。然后可以使用该推断向量来找到n最相似的向量。

可以做类似的事情,但使用 ELMO 嵌入代替吗?

任何指导将不胜感激。

2个回答

我最终找到了这篇文章,它可以满足我的需求。以下是我根据需要修改的代码部分

from sklearn.metrics.pairwise import cosine_similarity

import tensorflow_hub as hub
import tensorflow as tf

elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)

def elmo_vectors(x):
  embeddings=elmo(x, signature="default", as_dict=True)["elmo"]

  with tf.device('/device:GPU:0'):
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      sess.run(tf.tables_initializer())
      # return average of ELMo features
      return sess.run(tf.reduce_mean(embeddings,1))


corpus=["I'd like an apple juice",
        "An apple a day keeps the doctor away",
         "Eat apple every day",
         "We buy apples every week",
         "We use machine learning for text classification",
         "Text classification is subfield of machine learning"]


elmo_embeddings=[]
print (len(corpus))
for i in range(len(corpus)):
    print (corpus[i])
    elmo_embeddings.append(elmo_vectors([corpus[i]])[0])

print ( elmo_embeddings, len(elmo_embeddings))
print(elmo_embeddings[0].shape)
sims = cosine_similarity(elmo_embeddings, elmo_embeddings)
print(sims)
print(sims.shape)

我假设您正在尝试训练一个比较 2 个句子并给出它们的相似程度的网络。

为此,您将需要数据集(句子列表)和相应的“正确答案”列表(句子的确切相似性,我假设您没有?)。

为什么你需要使用神经网络来比较它们呢?对于 python,difflib 的序列匹配器是我的建议,但我敢肯定还有很多其他的库 :)