我试图用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]))发布于 2021-05-20 13:16:54
在这里的线程中:NotImplementedError: Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. T。解决方案是更改numpy版本(1.19.5可能是一个合适的版本)。
我认为提供(Python + TensorFlow + NumPy)的所有版本都很重要。
另外,就像评论中提到的@Edwin一样,您可能在丢失函数中混合了numpy和Tensorflow代码。向我们提供这些信息也很重要,这里的问题是损失函数计算/创建:NotImplementedError: Cannot convert a symbolic Tensor (2nd_target:0) to a numpy array。
https://stackoverflow.com/questions/67611744
复制相似问题