首页 > 解决方案 > 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))

标签: tensorflowkerascosine-similarity

解决方案


好吧,现在很容易。我只是插入了这个 lambda 层
,因为 mean 函数也适用于向量 - 矩阵乘法。

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

在我的例子中,输入是一个形状为 (10,) 的向量。输出是一个向量,其输入向量的余弦相似度值与 c1 和 c2 的形状为 (2,)


推荐阅读