首页 > 解决方案 > 在 Keras 中使用 add_loss 进行回调

问题描述

我正在尝试在 Keras 中实现 VAE 风格的网络。我计算我的负对数似然和 KL 散度,并分别用model.add_loss(NLL)和将它们添加到我的模型中。model.add_loss(KL)

我想随着训练的进行扩展我的 KL 术语(“KL 退火”)。我尝试使用自定义回调(在此处详述)来执行此操作,但 KL 损失项没有得到更新 -model.add_loss(KL)尽管 KL 权重得到更新,但该项随着时间的推移是恒定的(见图)。

训练时期的损失 我怎样才能使这个model.add_loss(KL)术语依赖于KL_weight

演示这个想法的代码:

...
<NLL calculations>
...

# Add the first loss to the model, the NLL:
model.add_loss(NLL)

from keras.callbacks import Callback

klstart = 40
# number of epochs over which KL scaling is increased from 0 to 1
kl_annealtime = 20

weight = tf.keras.backend.variable(0.0) #intialiase KL weight term
class AnnealingCallback(Callback):
    def __init__(self, weight):
        self.weight = weight
    def on_epoch_end (self, epoch, logs={}):
        if epoch > klstart :
            new_weight = min(tf.keras.backend.get_value(self.weight) + (1./ kl_annealtime), 1.)
            tf.keras.backend.set_value(self.weight, new_weight)
        print ("Current KL Weight is " + str(tf.keras.backend.get_value(self.weight)))

# Now the KL divergence:
<KL weight calculations>
KL = weight*tf.reduce_mean(tfp.distributions.kl_divergence(p, q))
model.add_loss(KL)

# Now compile the model with a specified optimiser
opt = tf.keras.optimizers.Adam(lr=0.001,clipnorm=0.1)
model.compile(optimizer=opt)

# Monitor how the NLL and KL divergence differ over time
model.add_metric(KL, name='kl_loss', aggregation='mean')
model.add_metric(NLL, name='mse_loss', aggregation='mean')

ops.reset_default_graph()
history=model.fit(Y_portioned, # Input or "Y_true"
                    verbose=1,
                    callbacks=[earlystopping_callback,callback_reduce_lr,AnnealingCallback(weight)],
                    epochs=650,
                    batch_size=8
                    ) # <- Increase batch size for speed up

版本:TensorFlow 2.1.0、Keras 2.2.4

提前谢谢了

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


所以当我看到你的帖子时,我正是在 Keras 中寻找这个实现。过了一会儿,我似乎只发现了两个错误:

  1. 您在类上下文之外声明了一个 tf 变量,因此无法识别它。
  2. 第一个原因,您没有正确实例化权重。

更正后的版本如下所示:

#start = klstart
#time = kl_annealtime

class AnnealingCallback(keras.callbacks.Callback):
    def __init__(self, weight=tf.keras.backend.variable(0.0), start=20, time=40):
        self.weight = weight
        self.start = start
        self.time = time    
    def on_epoch_end (self, epoch, logs={}):
        if epoch > self.start :
            new_weight = min(tf.keras.backend.get_value(self.weight) + (1./self.time), 1.)
            tf.keras.backend.set_value(self.weight, new_weight)
        print("Current KL Weight is " + str(tf.keras.backend.get_value(self.weight)))

现在您可以实例化权重:

AC = AnnealingCallback()
w = AC.weight

它预先乘以您的 KL 散度。


推荐阅读