Tensorflow1,How to calculate tensor's cosin-similarity to form a similarity matrix?

101 views Asked by At

First,I have a tensor like this,

a = [[A B],[C D]]

I'd like to calculate cosin-similarity between each other,I mean calculate cos([A B],[A B]),cos([A B],[C D]),cos([C D],[A B]),cos([C D],[C D]) to form a similarity matrix like this,

[[cos([A B],[A B]),cos([A B],[C D])],
 [cos([C D],[A B]),cos([C D],[C D])]]

I want to use follow code to get similarity matrix,it did't work.

`tf.losses.cosine_distance(tf.expand_dims(a, 0),
 tf.expand_dims(a, 1), axis = 2)`

How to use efficient vectorization to do this work in TF1?thank your reply.

1

There are 1 answers

0
AudioBubble On

This may help,

import tensorflow as tf
a = [1.,2.,3.]
b = [1.,2.,3.]
#cosine_similarity = tf.losses.cosine_distance(tf.nn.l2_normalize(a, 0), tf.nn.l2_normalize(b, 0), dim=0)  ##normalize_input
cosine_similarity = tf.losses.cosine_distance(a, b, dim=0)
print(tf.Session().run(cosine_similarity))

output

-13.0