Trending

TensorFlow | cosine_similarity for vectors

This code snippet is written for TensorFlow2.0.

tf.keras.losses.cosine_similarity function in tensorflow computes the cosine similarity between two vectors. It is a negative quantity between -1 and 0, where 0 indicates less similarity and values closer to -1 indicate greater similarity.

"tensors" in below code is a list of four vectors, tf.keras.losses.cosine_similarity is used for calculating similarity between vectors. Notice output would be -1 when vector is compared with itself.


import tensorflow as tf

tensors = [[.34, .45, .67, .65], [.14, .35, .67, .65],
            [.54, .95, .07, .5], [.64, .75, .81, .05]]

# Similarity of one vector with all other vectors
print(tf.keras.losses.cosine_similarity(
    tensors[0],
      tensors,
    axis=-1
))

======Output======
tf.Tensor([-1.   -0.9804376  -0.74875045 -0.8115672 ], 
shape=(4,), dtype=float32)

Similarity of one vector with another vector



print(tf.keras.losses.cosine_similarity(
    tensors[0],
      tensors[1],
    axis=-1
))

=====Output=====
tf.Tensor(-0.9804376, shape=(), dtype=float32)