Search code examples
pythontensorflowcosine-similarity

Tensorflow cosine similarity between each tensor in a list


I have 2 list(array) with tensors and want to calculate cosine similarity of the tensors between two lists. And get output list(tensor) with similarities.

For example:

a: [ 
[1, 2, 3], 
[4, 5, 6], 
[7, 8, 9] 
]   

b: [ 
[1, 2, 3], 
[7, 5, 6], 
[7, 4, 9] 
]

Output:

out: [
1.0,
0.84,
0.78
]

Would be gratefull for any help regarding how to execute this in tensorflow.

For now I've finished on this:

a = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_a")
b = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_b")
normalize_a = tf.nn.l2_normalize(a, dim=1)
normalize_b = tf.nn.l2_normalize(b, dim=1)
cos_similarity=tf.matmul(normalize_a, normalize_b,transpose_b=True)

sess=tf.Session()
cos_sim=sess.run(cos_similarity,feed_dict={
  a: np.array([[1, 2, 3], 
               [4, 5, 6]]),

  b: np.array([[1, 2, 3], 
               [8, 7, 9]]),
})
print(cos_sim)


Solution

  • a = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_a")
    b = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_b")
    numerator = tf.reduce_sum(tf.multiply(a, b), axis=1)
    denominator = tf.multiply(tf.norm(a, axis=1), tf.norm(b, axis=1))
    cos_similarity = numerator/denominator
    
    sess=tf.Session()
    cos_sim=sess.run(cos_similarity,feed_dict={
      a: np.array([[1, 2, 3], 
                   [4, 5, 6]]),
    
      b: np.array([[1, 2, 3], 
                   [8, 7, 9]]),
    })
    print(cos_sim)