计算网络两个输出之间的 cosine_proximity 损失
Computing cosine_proximity loss between two outputs of the network
我正在使用 Keras 2.0.2 Functional API (Tensorflow 1.0.1) 来实现一个接受多个输入并产生两个输出 a
和 b
的网络。我需要使用 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], [?????])
你可以先定义一个假的真标签。例如,将其定义为输入数据大小的一维数组。
损失函数来了。可以这样写。
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 就不会给出缺失的输入 warning/error。
您应该正常调用您的 fit
函数,即包含您的假地面真实标签。
model.compile('adam', my_cosine_proximity) # 'adam' used as an example optimizer
model.fit([testq1, testq2], fake_y_true)
我正在使用 Keras 2.0.2 Functional API (Tensorflow 1.0.1) 来实现一个接受多个输入并产生两个输出 a
和 b
的网络。我需要使用 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], [?????])
你可以先定义一个假的真标签。例如,将其定义为输入数据大小的一维数组。
损失函数来了。可以这样写。
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 就不会给出缺失的输入 warning/error。
您应该正常调用您的 fit
函数,即包含您的假地面真实标签。
model.compile('adam', my_cosine_proximity) # 'adam' used as an example optimizer
model.fit([testq1, testq2], fake_y_true)