【问题标题】:Extract learned NN posterior weight distribution parameters from DenseVariational layer从 DenseVariational 层中提取学习的 NN 后验权重分布参数
【发布时间】:2020-04-23 17:02:01
【问题描述】:

我还在 tensorflow 概率 Github 问题中发布了这个问题: https://github.com/tensorflow/probability/issues/892

我在 python 3.6.8 中使用 Tensorflow 2.1.0 和 tensorflow-probability 0.9.0。 我正在使用 Tensorflow Probability Keras 模型,该模型具有如下定义的 DenseVariational 层(摘自在线示例):

def posterior_mean_field(kernel_size, bias_size=0, dtype=None):
    n = kernel_size + bias_size
    c = np.log(np.expm1(1.))
    return tf.keras.Sequential([
        tfp.layers.VariableLayer(2 * n, dtype=dtype),
        tfp.layers.DistributionLambda(lambda t: tfd.Independent(
            tfd.Normal(loc=t[..., :n], scale=1e-5 + tf.nn.softplus(c + t[..., n:])),
            reinterpreted_batch_ndims=1)),
    ])


def prior_trainable(kernel_size, bias_size=0, dtype=None):
    n = kernel_size + bias_size
    return tf.keras.Sequential([
        tfp.layers.VariableLayer(n, dtype=dtype),
        tfp.layers.DistributionLambda(lambda t: tfd.Independent(tfd.Normal(loc=t, scale=1),
                                                                reinterpreted_batch_ndims=1)),
    ])

dense = tfp.layers.DenseVariational(units=units, make_posterior_fn=posterior_mean_field,
                                                             make_prior_fn=prior_trainable,
                                                            )(prev_layer)

如果我训练我的模型,然后删除该层之后的层,剩余的模型将从学习的后验权重分布中输出随机变量。像这样的:

from tensorflow.keras import Model
# DenseVariational layer is 3rd to last layer in this case
cropped_model = Model(inputs, model.layers[-3].output)  
cropped_mode.predict(test_data)

大多数时候这都很好(例如训练、采样等)。但是,是否有一种直接的方法可以将给定输入(例如 test_data)返回的学习 loc 和缩放后验值返回到这个cropped_model,而不是从他们定义的分布中抽取样本?

【问题讨论】:

  • 你为什么在后面使用VariableLayer?这不应该对所有样本强制执行(学习的)恒定均值和方差吗?
  • @BlackBear,老实说,我只是复制并粘贴了这些图层,但你是对的。它应该为跟随它的分布创建静态均值和方差值。我认为问题是如何提取这些均值和方差值,以便无需采样即可重新创建分布?

标签: python tensorflow neural-network bayesian tensorflow-probability


【解决方案1】:

您可以参考此webpage 的“训练模型和检查”部分。

我这里简单介绍一下网站中提到的解决方案。 假设 DenseVariational 层是训练模型的第一层,您可以通过这种方式获得训练后的先验分布及其均值和方差(由于 DenseVariational 层不受输入影响,虚拟输入可以是任何数组:

dummy_input = np.array([[0]])
model.layers[0]._prior(dummy_input)
print('Prior Variance: ', model_prior.variance().numpy())
print('Posterior mean: ', model_posterior.mean().numpy())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2018-10-28
    • 2013-08-15
    相关资源
    最近更新 更多