I have two normalized tensors and I need to calculate the cosine similarity between these tensors. How do I do it with TensorFlow?
cosine(normalize_a,normali
Times change. With the latest TF API, this can be computed by calling tf.losses.cosine_distance
.
Example:
import tensorflow as tf
import numpy as np
x = tf.constant(np.random.uniform(-1, 1, 10))
y = tf.constant(np.random.uniform(-1, 1, 10))
s = tf.losses.cosine_distance(tf.nn.l2_normalize(x, 0), tf.nn.l2_normalize(y, 0), dim=0)
print(tf.Session().run(s))
Of course, 1 - s
is the cosine similarity!