当前位置:   article > 正文

keras求两向量间的余弦值_keras 计算余弦相似度

keras 计算余弦相似度

keras求两向量间的余弦值

具体要自己定义一个layer,余弦相似度计算公式如下:
步骤:

  1. 计算两个向量L2范数,计算两个向量的点乘
  2. 点乘结果除以L2范数乘积,分母不能为0

在这里插入图片描述

import keras.backend as K
from keras.layers import Lambda
import numpy as np
import keras
class CosineLayer():
    def __call__(self, x1, x2):
        def _cosine(x):
            dot1 = K.batch_dot(x[0], x[1], axes=1)
            dot2 = K.batch_dot(x[0], x[0], axes=1)
            dot3 = K.batch_dot(x[1], x[1], axes=1)
            max_ = K.maximum(K.sqrt(dot2 * dot3), K.epsilon())
            return dot1 / max_

        output_shape = (1,)
        value = Lambda(
            _cosine,
            output_shape=output_shape)([x1, x2])
        return value

# x1,x2:(batch_size, dim)
x1 = np.random.randint(1, 100, 20)
# x2 = np.random.randint(1, 100, 20)
x2 = np.random.randint(1, 100, 20)
# 一定要是二维
x1 = x1.reshape(4, 5)
x2 = x2.reshape(4, 5)
x1 = K.constant(x1)
x2 = K.constant(x2)
# 转化为keras里的tensor
x = Lambda(lambda x:x)(x1)
y = Lambda(lambda x:x)(x2)
cosine = CosineLayer()
similarity = cosine(x, y)
# tensor输出查看不到具体值
print(similarity)
# model = CosineLayer(x,y)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

参考: 使用Keras计算余弦相似度(Cosine Similarity)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42287
推荐阅读
相关标签
  

闽ICP备14008679号