【问题标题】:How to get the shape of a probabilistic layer?如何获得概率层的形状?
【发布时间】:2021-08-19 07:52:38
【问题描述】:

我是一个带有 TensorFlow 概率层的构建模型。当我这样做时,model.output.shape,我得到一个错误:

AttributeError: 'UserRegisteredSpec' object has no attribute '_shape'

如果我这样做,output_shape = tf.shape(model.output) 它会给出一个 Keras 张量:

<KerasTensor: shape=(5,) dtype=int32 inferred_value=[None, 3, 128, 128, 128] (created by layer 'tf.compat.v1.shape_15') 

我怎样才能得到实际值[None, 3, 128, 128, 128]? 我试过output_shape.get_shape(),但这给出了张量形状[5]

重现错误的代码:

import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd

tfd = tfp.distributions

model = tf.keras.Sequential()
model.add(tf.keras.layers.Input(10))

model.add(tf.keras.layers.Dense(2, activation="linear"))
model.add(
    tfp.layers.DistributionLambda(
        lambda t: tfd.Normal(
            loc=t[..., :1], scale=1e-3 + tf.math.softplus(0.1 * t[..., 1:])
        )
    )
)


model.output.shape

【问题讨论】:

  • 试试model.layers[-1].output_shape
  • 没用。

标签: tensorflow shapes tf.keras tensorflow-probability


【解决方案1】:

tf.shape会返回一个KerasTensor,直接获取输出shape不容易。

但是你可以这样做:

tf.shape(model.output)
>> `<KerasTensor: shape=(2,) dtype=int32 inferred_value=[None, 1] (created by layer 'tf.compat.v1.shape_168')>`

你想得到inferred_value,所以:

tf.shape(model.output)._inferred_value
>> [None, 1]

基本上,您可以通过以下方式访问任何层的输出形状:

tf.shape(model.layers[idx].output)._inferred_value

其中idx 是所需层的索引。

【讨论】:

  • 非常感谢。那行得通。请再问一个问题,我看到您关于 channel_first 问题的拉取请求已合并到 GitHub TensorFlow 概率 (convolutional_variational.py) 上。因此,当我导入 tensorflow_probability 时,它不应该导入那个版本吗?每次运行 Colab 时,我仍然需要更改它的源代码。
  • 我认为除非您从源代码构建 TFP,否则更改将包含在新版本中。
  • 有机会可以看看这个问题吗?与tensorflow概率中的data_format(channel_first)相关:*.com/questions/69052849/…
【解决方案2】:

例如,要获得所有图层的输出形状:

out_shape_list=[] 
    for layer in model.layers:
            out_shape = layer.output_shape
            out_shape_list.append(out_shape)

你会得到一个输出形状列表,每一层都有一个

【讨论】:

    最近更新 更多