【问题标题】:TensorFlow Probability MixtureSameFamily layer code example: what are the parameters output from a connected dense layer?[python]TensorFlow Probability MixtureSameFamily 层代码示例:连接的密集层输出的参数是什么?[python]
【发布时间】:2021-08-24 09:09:50
【问题描述】:

我正在查看来自MixtureSameFamily layer documantion page 的示例代码。具体来说,我有兴趣了解连接到 MixtureSameFamily 层的最后一个 Dense 层输出的参数是什么:

import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import matplotlib.pyplot as plt

tfd = tfp.distributions
tfpl = tfp.layers
tfk = tf.keras
tfkl = tf.keras.layers

n = 2000
t = tfd.Uniform(low=-np.pi, high=np.pi).sample([n, 1])
r = 2 * (1 - tf.cos(t))
x = r * tf.sin(t) + tfd.Normal(loc=0., scale=0.1).sample([n, 1])
y = r * tf.cos(t) + tfd.Normal(loc=0., scale=0.1).sample([n, 1])

event_shape = [1]
num_components = 5
params_size = tfpl.MixtureSameFamily.params_size(
    num_components,
    component_params_size=tfpl.IndependentNormal.params_size(event_shape))
md_model = tfk.Sequential([
  tfkl.Dense(12, activation='relu'),
  tfkl.Dense(params_size, activation=None),
  tfpl.MixtureSameFamily(num_components, tfpl.IndependentNormal(event_shape)),
])

在这种情况下,我们从最后一个 Dense 层输出了 15 个值。如果我以以下方式为索引为 0 的一个固定输入样本收集它们:

extractor = tfk.Model(inputs=md_model.inputs,
                        outputs=[layer.output for layer in md_model.layers[:-1]])
features = extractor(x)
parameters = features[1][0]

参数数组中的值是什么?我想它们应该以某种方式与构成混合模型的 5 个正态分布分量的混合系数、位置和规模有关。但具体如何?并按什么顺序?我在任何地方都找不到这些信息。换句话说,我想做的一件事是在 MixtureSameFamily distribution 对象中使用它们,但我不知道如何分配它们。我只能为 num_components=1 做到这一点:

probs = [1] 
loc = [parameters[1]]
scale = [parameter[2]]

gm = tfd.MixtureSameFamily(
    mixture_distribution=tfd.Categorical(probs=probs), 
    components_distribution=tfd.Normal(loc=loc, scale=scale))

但我找不到适合 num_components>1 的模式。你对如何做到这一点有什么建议吗? 如果我们找到解决方案,也许可以将其添加到示例/文档页面(我可以尝试为它做出贡献)。 提前致谢!

【问题讨论】:

    标签: python tensorflow tensorflow-probability


    【解决方案1】:

    我想我已经找到了答案。 将参数分配给分布对象的代码应如下所示:

    params_reshape = tf.reshape(parameters[..., num_components:], tf.concat([tf.shape(parameters)[:-1], [num_components, -1]], axis=0))
    loc_params, scale_params = tf.split(params_reshape, 2, axis=-1)
    scale_params = tf.math.softplus(scale_params)
    gm = tfd.MixtureSameFamily(
        mixture_distribution=tfd.Categorical(logits=parameters[..., :num_components]), 
        components_distribution=tfd.Independent(tfd.Normal(loc=loc_params, scale=scale_params), reinterpreted_batch_ndims=tf.size(event_shape)))
    

    我通过深入研究 github 存储库中的源代码找到了答案。特别是,这两个类很有用:MixtureSameFamilyIndependentNormal

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-17
      • 2023-03-05
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2017-12-14
      • 2020-06-10
      • 2018-02-09
      相关资源
      最近更新 更多