如何获得概率层的形状? [英] How to get the shape of a probabilistic layer?

查看:34
本文介绍了如何获得概率层的形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a building model with TensorFlow probability layers. When I do, model.output.shape, I get an error:

AttributeError: 'UserRegisteredSpec' 对象没有属性 '_shape'

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

If I do, output_shape = tf.shape(model.output) it gives a Keras Tensor:

<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(),但这给出了 Tensor 形状 [5].

How can I get the actual values [None, 3, 128, 128, 128]? I tried output_shape.get_shape(), but that gives the Tensor 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

推荐答案

tf.shape 会返回一个 KerasTensor,不容易直接得到输出形状.

tf.shape will return a KerasTensor which is not easy to get the output shape directly.

但是你可以这样做:

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]

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

Basically you can access any layer's output shape with:

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

其中 idx 是所需层的索引.

where idx is the index of the desired layer.

这篇关于如何获得概率层的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆