如何在tf-keras中定义具有多个输出的自定义损失函数?

时间:2019-06-06 09:20:14

标签: tensorflow tf.keras

我想训练一个多输出模型,在tensoflow keras中命名为ctr(点击率)和cvr。 输出应为ctr和cvr。但是损失应该是ctr损失和(ctr * cvr)损失。 因此,如果click-label为零,则(ctr * cvr)损失应为零。

d = concatenate(inp_embed, axis=-1, name='concat') #Embeddings共享
d = Flatten()(d)

d_ctr = BatchNormalization()(d)
d_ctr = Dense(100, activation='relu', kernel_regularizer=l1_l2(l1=0.01, l2=0.01))(d_ctr)
d_ctr = BatchNormalization()(d_ctr)
d_ctr = Dense(50, activation='relu', kernel_regularizer=l1_l2(l1=0.01, l2=0.01))(d_ctr)
d_ctr = Dense(1, activation=activation)(d_ctr)

d_cvr = BatchNormalization()(d)
d_cvr = Dense(100, activation='relu', kernel_regularizer=l1_l2(l1=0.01, l2=0.01))(d_cvr)
d_cvr = BatchNormalization()(d_cvr)
d_cvr = Dense(50, activation='relu', kernel_regularizer=l1_l2(l1=0.01, l2=0.01))(d_cvr)
d_cvr = Dense(1, activation=activation)(d_cvr)

d_ivr = multiply([d_ctr, d_cvr])
deep = Model(inputs=inp_layer, outputs=[d_ctr, d_cvr])

1 个答案:

答案 0 :(得分:0)

这是您可以从多个输出中创建自定义损失的方法:

def custom_loss(y_true, y_pred):

             ctr_loss = losses.binary_crossentropy(y_true, d_ctr)
             cvr_loss = losses.binary_crossentropy(y_true, d_cvr)

             return ctr_loss * cvr_loss          

以及如何使用它:

deep.compile(optimizer = sgd , loss = custom_loss, metrics=['accuracy'])

随时添加评论,以便我可以精确地给出答案。