我正在使用Bayesian Neural Network实现的Tensorflow Probability上运行示例代码。
我的问题是关于用于变分推断的ELBO损失的实现。 ELBO等于代码中实现的两个项的总和,即neg_log_likelihood
和kl
。我很难理解kl
术语的实现。
这里是模型的定义方式:
with tf.name_scope("bayesian_neural_net", values=[images]):
neural_net = tf.keras.Sequential()
for units in FLAGS.layer_sizes:
layer = tfp.layers.DenseFlipout(units, activation=FLAGS.activation)
neural_net.add(layer)
neural_net.add(tfp.layers.DenseFlipout(10))
logits = neural_net(images)
labels_distribution = tfd.Categorical(logits=logits)
这里是'kl'术语的定义:
kl = sum(neural_net.losses) / mnist_data.train.num_examples
我不确定neural_net.losses
在这里返回什么,因为没有为neural_net
定义损失函数。显然,neural_net.losses
将返回一些值,但是我不知道返回值的含义是什么。对此有何评论?
我的猜测是L2规范,但我不确定。如果是这样,我们仍然缺少一些东西。根据VAE论文的附录B,当先验为标准正态时,作者推导了KL项。事实证明,除了存在额外的对数方差项和常数项之外,它非常接近变分参数的L2范数。对此有何评论?
losses
的TensorFlow Keras Layer属性表示副作用计算,例如正则化器罚分。与特定TensorFlow变量的正则化惩罚不同,此处losses
代表KL散度计算。签出implementation here和docstring's example:
我们以variational inference表示贝叶斯神经网络,假设数据集为
features
和labels
。import tensorflow_probability as tfp model = tf.keras.Sequential([ tfp.layers.DenseFlipout(512, activation=tf.nn.relu), tfp.layers.DenseFlipout(10), ]) logits = model(features) neg_log_likelihood = tf.nn.softmax_cross_entropy_with_logits( labels=labels, logits=logits) kl = sum(model.losses) loss = neg_log_likelihood + kl train_op = tf.train.AdamOptimizer().minimize(loss)
它使用Flipout梯度估算器将Kullback-Leibler散度一直到一个常数,也称为负证据下界。它由两个项的和组成:预期的负对数似然率,我们通过蒙特近似卡洛和KL散度,通过正则化条件添加这是图层的参数。