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

因为Merge函数在Keras新版本中已经不再使用了,在计算批次余弦相似度时,需要自定义函数。余弦相似度定义如下:

使用Keras计算余弦相似度(Cosine Similarity)_第1张图片

要计算两个向量相似度有如下步骤:

  1. 分别计算两个向量l2范式,计算两个向量的点乘
  2. 点乘的结果除以l2范式的乘积,注意分母不要为0

我们使用Keras后端函数计算Cosine相似度,因为在使用后端函数时候要使用Lamda函数进行包裹,否则程序会影响出错。K.batch_dot()函数批量计算向量点乘, K.maximum(K.sqrt(dot2 * dot3), K.epsilon())保证分布不为0。具体计算代码如下:

import keras.backend as K
from keras.layers.core import Lambda

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)
# cosine = CosineLayer()
# similarity = cosine(x1, x2)

 

你可能感兴趣的:(深度学习)