计算 elmo 模型的余弦相似度

问题描述

我正在尝试使用 Elmo 模型计算 wordsim 集的余弦相似度。这可能没有意义,因为它是为句子词嵌入而设计的,但我想看看模型在这些情况下的表现如何。我使用的 Elmo 来自:

https://tfhub.dev/google/elmo/3

如果我运行以下代码(从文档页面修改以符合 TF 2.0),它将生成单词的张量表示。

import tensorflow_hub as hub
import tensorflow as tf


elmo = hub.load("https://tfhub.dev/google/elmo/3")
tensor_of_strings = tf.constant(["Gray","Quick","Lazy"])
elmo.signatures['default'](tensor_of_strings)

如果我尝试直接计算余弦相似度,则会得到错误 NotImplementedError: Cannot convert a symbolic Tensor (strided_slice_59:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call,which is not supported 。我不确定如何将张量直接转换为 numpy 数组,或者是否有更好的张量评估器而不是余弦相似度?

编辑:这是我为计算余弦相似度所做的

def cos_sim(a,b):
    return np.inner(a,b) / (np.linalg.norm(a) * (np.linalg.norm(b)))

print("ELMo:",cos_sim(elmo.signatures['default'](tensor_of_strings)['word_emb'][0],elmo.signatures['default'](tensor_of_strings)['word_emb'][1]))

解决方法

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

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

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