赞
踩
因为Merge函数在Keras新版本中已经不再使用了,在计算批次余弦相似度时,需要自定义函数。余弦相似度定义如下:
要计算两个向量相似度有如下步骤:
我们使用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)

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。