python - 在 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
提前谢谢了
解决方案
所以当我看到你的帖子时,我正是在 Keras 中寻找这个实现。过了一会儿,我似乎只发现了两个错误:
- 您在类上下文之外声明了一个 tf 变量,因此无法识别它。
- 第一个原因,您没有正确实例化权重。
更正后的版本如下所示:
#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 散度。
推荐阅读
- c++ - 内联静态常量与静态常量变量
- google-api-nodejs-client - Google Drive v3 文件夹创建
- excel - If 语句公式破坏 VBA 循环代码
- javascript - pdfjs:使用正确的换行符/带空格从 pdf 获取原始文本
- selenium - 当我的断言通过时如何停止执行?
- angular - ionic3 中的深层链接:不要使用 Gmail 链接启动 ionic 应用
- c# - 从数据库中获取数据后如何多次提高排序列表的性能
- sql - 将 HTML 解析为 SQL Server 中的列
- sdk - VLC Vetinari(360 度视频).NET SDK
- java - 检查条件并在java中发送邮件