Skip to content

Instantly share code, notes, and snippets.

@mmeendez8
Created October 4, 2018 15:48
Show Gist options
  • Save mmeendez8/73f909768c9a4c38f7003cb711e7e906 to your computer and use it in GitHub Desktop.
Save mmeendez8/73f909768c9a4c38f7003cb711e7e906 to your computer and use it in GitHub Desktop.
Tensorflow function to compute cosine similarity between a column vector and the rows of a matrix.
import tensorflow as tf
import numpy as np
def cosine_similarity(matrix, vector):
''' Computes cosine similarity of a given vector with vector rows from matrix'''
# normalize input
norm_matrix = tf.nn.l2_normalize(matrix, 1)
norm_vector = tf.nn.l2_normalize(vector, 0)
# multiply row i with row j using transpose
similarity = tf.matmul(norm_matrix, norm_vector)
return similarity
with tf.Session() as sess:
input_vector = tf.placeholder(tf.float32, shape=(None ), name='input_vector')
input_matrix = tf.placeholder(tf.float32, shape=(None, None), name='input_matrix')
sim = cosine_similarity(input_matrix, input_vector)
input_matrix_ = np.array(
[[ 1, 1, 1 ],
[ 0, 1, 1 ],
[ 0, 0, 1 ],
],
dtype = 'float32')
input_vector_ = np.ones((3,1))
print (sess.run([sim], feed_dict = { input_matrix: input_matrix_, input_vector: input_vector_}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment