如何计算两个张量之间的余弦相似度?

我有两个标准化张量,我需要计算这些张量之间的相似度" title="余弦相似度">余弦相似度。如何使用TensorFlow做到这一点?

cosine(normalize_a,normalize_b)

a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")

b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b")

normalize_a = tf.nn.l2_normalize(a,0)

normalize_b = tf.nn.l2_normalize(b,0)

回答:

这将完成工作:

a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")

b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b")

normalize_a = tf.nn.l2_normalize(a,0)

normalize_b = tf.nn.l2_normalize(b,0)

cos_similarity=tf.reduce_sum(tf.multiply(normalize_a,normalize_b))

sess=tf.Session()

cos_sim=sess.run(cos_similarity,feed_dict={a:[1,2,3],b:[2,4,6]})

此打印 0.99999988

以上是 如何计算两个张量之间的余弦相似度? 的全部内容, 来源链接: utcz.com/qa/405304.html

回到顶部