fujiyuu75
4/24/2017 - 6:48 AM

tensorflow_cos_similarity.py

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, [1, None])
y = tf.placeholder(tf.float32, [1, None])

dot = tf.matmul(x, y, transpose_b=True)
x_abs = tf.sqrt(tf.matmul(x, x, transpose_b=True))
y_abs = tf.sqrt(tf.matmul(y, y, transpose_b=True))

cos = tf.div(dot, tf.multiply(x_abs, y_abs))

with tf.Session() as sess:
    sim = sess.run([cos], feed_dict={x: [[1, 9, 8, 2]], y: [[0, 7, 0, 5]]})[0][0]
print (np.arccos(sim) * 180 / np.pi)