ELMO 嵌入可以用来找到 n 个最相似的句子吗?
人工智能
自然语言处理
词嵌入
2021-10-22 11:55:35
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 的序列匹配器是我的建议,但我敢肯定还有很多其他的库 :)
其它你可能感兴趣的问题