tensorflow - 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))
解决方案
好吧,现在很容易。我只是插入了这个 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,)
推荐阅读
- android - 如何在 firebase 数据库中添加值并存储总数
- isabelle - Isabelle/HOL 中类型的语法缩写?
- java - 运行“安装”时如何避免再次运行“测试”
- excel - 尝试将 CSV 文件导入名为 IMPORT 的工作表
- jquery - Bootstrap 切换还使用 jquery 清空某些元素
- html - html中存在href的角度有什么替代方法?
- c# - 如何在 ASP NET 中获取入口程序集引用
- ios - 线程是否在不同的 Dispatch 队列之间共享?
- angular - Ionic 4 - 将令牌的承诺转换为可观察的?
- c++ - Vulkan 中的多个透明绘图调用之间是否需要同步?