keras求两向量间的余弦值
具体要自己定义一个layer,余弦相似度计算公式如下:
步骤:
- 计算两个向量L2范数,计算两个向量的点乘
- 点乘结果除以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)