在训练期间逐渐更新 Keras 中自定义损失的权重

Kat*_*mli 5 python keras tensorflow loss-function keras-2

我在 Keras(张量流后端)中定义了一个自定义损失函数,该函数由重建 MSE 以及学习的概率分布和标准正态分布之间的 kullback leibler 散度组成。(它用于变分自动编码器。)

我希望能够在训练期间慢慢增加 KL 散度项对成本的影响,权重称为“reg”,从 reg=0.0 开始,逐渐增加,直到达到 1.0。我希望将增长率调整为超参数。(到目前为止,我只是将“reg”参数设置为常量 0.5。)

Keras 中有执行此操作的功能吗?

def vae_loss(y_true,y_pred):
    reg = 0.5
    # Average cosine distance for all words in a sequence 
    reconstruction_loss = tf.reduce_mean(mean_squared_error(y_true, y_pred),1)    
    # Second part of the loss ensures the z probability distribution doesn't stray too far from normal
    KL_divergence_loss = tf.reduce_mean(tf.log(z_sigma) + tf.div((1 + tf.square(z_mu)),2*tf.square(z_sigma)) - 0.5,1)
    loss = reconstruction_loss + tf.multiply(reg,KL_divergence_loss)
    return loss
Run Code Online (Sandbox Code Playgroud)