在自定义损失函数内拆分多个输出

时间:2018-12-03 21:12:01

标签: python keras

我正在为我的VAE模型实现自定义损失函数。我正在考虑输入和编码表示对之间的汉明丢失。但是在多输出的情况下,如何在自定义损失函数中使用来自不同输出层的值。我试图在下面的代码中实现它:

def vae_loss(x):
    def enc_ham_loss(y_true,y_pred):
         y_pred, pred_matrix = y_pred
    """ Calculate loss = reconstruction loss + KL loss for each data in minibatch """
    # E[log P(X|z)]
        #recon = K.sum(mean_squared_error(y_true,y_pred))
        recon = K.sum(K.binary_crossentropy(y_true,pred_matrix),axis=1)
    # D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist. are Gaussian
        kl = 0.5 * K.sum(K.exp(z_cov) + K.square(z_mean) - 1. - z_cov, axis=1)

        pairwise_diff_pred = K.abs(K.expand_dims(y_pred, 0) - 
K.expand_dims(y_pred, 1))
        pairwise_distance_pred = K.sum(pairwise_diff_pred, axis=-1)

    # calculate pairwise hamming distance matrix for inputs
        pairwise_diff_true = K.abs(K.expand_dims(x, 0) - K.expand_dims(x, 1))
        pairwise_distance_true = K.sum(pairwise_diff_true, axis=-1)

    #Difference between the distances of y_true and y_predictions
        hamm_sum= Lambda(differences)([pairwise_distance_true, pairwise_distance_pred])

        loss1,loss2 = recon + kl,hamm_sum
        return loss1 + loss2 
     return enc_ham_loss  

vae.compile(optimizer='adam', loss=vae_loss(x_train))

vae.fit(x_train, x_train, batch_size= 5, epochs=10)

我遇到错误:

  

TypeError:仅在启用急切执行后,张量对象才可迭代。要遍历此张量,请使用tf.map_fn

有人可以指导我吗?还是有其他方法可以在损失函数中使用2个输出。

非常感谢帮助。预先感谢。

0 个答案:

没有答案