【问题标题】:How to train on the cosine similarity with the Keras Dot function?如何用 Keras Dot 函数训练余弦相似度?
【发布时间】:2020-09-03 21:52:23
【问题描述】:

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

  • 训练的目标应该在哪个值范围内?意味着在哪个值范围内可能是 Dot 函数的结果?如果嵌入非常相似,目标应该是什么值?如果它们非常不同,目标应该是什么?
  • 在这种情况下,axis 参数是什么意思?设置axis=1对吗?

我的模型如下:

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)

documentation 他们说:

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

【问题讨论】:

    标签: keras keras-layer cosine-similarity siamese-network


    【解决方案1】:

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

    您可以在这里查看如何计算 Keras 中的余弦相似度:Computing cosine similarity between two tensors in Keras

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

    【讨论】:

    • 只是说,在 TF 和 tf.keras.losses.cosine_simiarity 中你写的完全相反:-1 表示向量相同,1 完全相反。
    • 谢谢 Krzyzstof,我相应地更新了答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2019-06-21
    • 2011-01-01
    • 2017-12-12
    • 2013-05-24
    相关资源
    最近更新 更多