Search code examples
tensorflowkerascosine-similarity

Computing cosine similarity between vector and matrix in Keras


I have a vector as input for a layer. For this vector I would like to calculate the cosine similariy to several other vectors (that can be arranged in a matrix)

Example (other vectors: c1,c2,c3 ...):

Input: 
v 
(len(v) = len(c1) = len(c2) ...)

Output: 
[cosinsSimilarity(v,c1),cosineSimilarity(v,c2),cosineSimilarity(v,c3),consinSimilarity(v,...)]

I think the problem could be solved by an approach like the following:

cosineSimilarity (v, matrix (c1, c2, c3, ...))

but unfortunately I have no idea how I can implement that in a keras layer with input_shape(1,len(v)) and output_shape(1,columns(matrix))


Solution

  • okay it was so easy now. I simply inserted this lambda layer
    because the mean function also works for vector - matrix multiplication.

    def cosine_similarity(x):
      #shape x: (10,)
      y = tf.constant([c1,c2])
      #shape c1,c2: (10,)
      #shape y: (2,10)
    
      x = K.l2_normalize(x, -1)
      y = K.l2_normalize(y, -1)
      s = K.mean(x * y, axis=-1, keepdims=False) * 10
      return s
    

    input is in my case a vector with shape (10,). Output is a vector with the cosine-similarity-values of the input vector to c1 and c2 with shape (2,)