首页 > 解决方案 > 如何用 Keras Dot 函数训练余弦相似度?

问题描述

在比较两个文档的嵌入时,我想在 Keras 模型中使用余弦相似度。

我已经建立了我的模型如下:

from tensorflow.python.keras.layers import Dot
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential

input_document1 = Input(200)
model_1 = Sequential()
model_1.add(Dense(100, activation='relu'))
encoded_document1 = model_1(input_document1)

input_document2 = Input(200)
model_2 = Sequential()
model_2.add(Dense(100, activation='relu'))
encoded_document2 = model_2(input_document2)

distance_layer = Dot(axes=1, normalize=True) # cosine proximity
prediction = distance_layer([encoded_document1, encoded_document2])

siamese_net = Model(inputs=[input_document1, input_document2], outputs=prediction)

他们在文档中说:

是否在取点积之前沿点积轴对样本进行 L2 归一化。如果设置为 True,则点积的输出是两个样本之间的余弦接近度

标签: keraskeras-layercosine-similaritysiamese-network

解决方案


[-1,1] 之间的输出值之间的余弦相似度,其中 1 表示向量完全相反,-1 表示完全重叠/相似。

您可以在这里查看如何计算余弦相似度KerasComputing cosinesimilarity between two tensors in Keras

至于轴/轴的解释,这里的文档做得很好:https ://www.tensorflow.org/guide/tensor


推荐阅读