【问题标题】:Computing cosine_proximity loss between two outputs of the network计算网络两个输出之间的 cosine_proximity 损失
【发布时间】:2017-04-08 19:09:49
【问题描述】:

我正在使用 Keras 2.0.2 功能 API (Tensorflow 1.0.1) 来实现一个网络,该网络接受多个输入并产生两个输出 ab。我需要使用 cosine_proximity 损失来训练网络,这样b 就是a 的标签。我该怎么做?

在这里分享我的代码。最后一行model.fit(..) 是有问题的部分,因为我本身没有标记数据。标签由模型本身产生。

from keras.models import Model
from keras.layers import Input, LSTM
from keras import losses

shared_lstm = LSTM(dim)

q1 = Input(shape=(..,.. ), name='q1')
q2 = Input(shape=(..,.. ), name='q2')
a = shared_lstm(q1)
b = shared_lstm(q2)
model = Model(inputs=[q1,q2], outputs=[a, b])
model.compile(optimizer='adam', loss=losses.cosine_proximity)

model.fit([testq1, testq2], [?????])

【问题讨论】:

    标签: deep-learning keras loss


    【解决方案1】:

    你可以先定义一个假的真标签。例如,将其定义为输入数据大小的一维数组。

    现在是损失函数。可以这样写。

    def my_cosine_proximity(y_true, y_pred):
        a = y_pred[0]
        b = y_pred[1]
        # depends on whether you want to normalize
        a = K.l2_normalize(a, axis=-1)
        b = K.l2_normalize(b, axis=-1)        
        return -K.mean(a * b, axis=-1) + 0 * y_true
    

    我已将 y_true 乘以零并添加它,这样 Theano 不会给出丢失输入警告/错误。

    您应该正常调用您的 fit 函数,即包含您的虚假真实标签。

    model.compile('adam', my_cosine_proximity) # 'adam' used as an example optimizer 
    model.fit([testq1, testq2], fake_y_true)
    

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 2021-05-14
      • 2020-07-19
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多