我正在尝试使用 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]))