在tensorflow占位符上使用tf.shape()

时间:2019-03-05 22:44:45

标签: tensorflow

让我们看一下这个简单的tf操作:

data = np.random.rand(1,2,3)
x = tf.placeholder(tf.float32, shape=[None, None, None], name='x_pl')
out = x
print ('shape:', tf.shape(out))
sess = tf.Session()
sess.run(out, feed_dict={x: data})

打印为:

shape: Tensor("Shape_13:0", shape=(3,), dtype=int32)

我读到您应该使用tf.shape()获得张量的“动态”形状,这似乎是我所需要的,但是为什么形状是shape =(3,)? 为什么不是(1,2,3)?因为应该确定何时运行会话?

假设这是神经网络的一部分,我需要知道x的最后一个维度,例如,将x传递到Dense层,为此需要知道x的最后一个维度。 怎么办呢?

1 个答案:

答案 0 :(得分:0)

这是因为(?:(date)? ?\D ?)?\b([14]) ?([-:.]) ?[-+]?([0-9]+)( ?# ?([a-zA-Z0-9]*))? ^^^ ^ ^^^ 是op,因此您必须在会话中运行它。

tf.shape()

将返回

data = np.random.rand(1,2,3)
x = tf.placeholder(tf.float32, shape=[None, None, None], name='x_pl')
out = x
print ('shape:', tf.shape(out))
z = tf.shape(out)
sess = tf.Session()
out_, z_ =sess.run([out,z], feed_dict={x: data})
print(f"shape of out: {z_}")

即使您查看文档(https://www.tensorflow.org/api_docs/python/tf/shape)中的示例:

shape: Tensor("Shape:0", shape=(3,), dtype=int32) 
shape of out: [1 2 3]

如果只运行它,它将返回类似的内容

t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.shape(t)

但是,如果您在会话中运行它,则将获得预期的结果

<tf.Tensor 'Shape_4:0' shape=(3,) dtype=int32>