How to calculate the Cosine similarity between two tensors?

前端 未结 3 902
無奈伤痛
無奈伤痛 2020-12-08 11:29

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         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 12:15

    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!

提交回复
热议问题