keras - 如何用 Keras Dot 函数训练余弦相似度?
问题描述
在比较两个文档的嵌入时,我想在 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)
他们在文档中说:
是否在取点积之前沿点积轴对样本进行 L2 归一化。如果设置为 True,则点积的输出是两个样本之间的余弦接近度。
解决方案
[-1,1] 之间的输出值之间的余弦相似度,其中 1 表示向量完全相反,-1 表示完全重叠/相似。
您可以在这里查看如何计算余弦相似度Keras
:Computing cosinesimilarity between two tensors in Keras
至于轴/轴的解释,这里的文档做得很好:https ://www.tensorflow.org/guide/tensor
推荐阅读
- nativescript - 在 Nativescript 代码共享项目中使用 Angular 库
- javascript - 带复选框的字段验证
- ios - AVAudioSession - 如何在扬声器和耳机输出之间切换
- sql - CASE in WHERE 子句 SQL VBA Excel
- python - Python Numpy:循环中的随机数
- ruby-on-rails - Ruby on Rails 应用程序部署到 heroku 但应用程序错误?
- ios - GLKit,Opengl ES 3.0,使用 glReadPixels 获取深度
- php - sumbit:php 后我得到一个空帖子
- r - 根据多列获取最新记录 - R
- python - 从 docker 发送 ddtrace