获取可变批量维度的大小

MBZ*_*MBZ 4 tensorflow

假设网络输入是一个placeholder具有可变批量大小的输入,即:

x = tf.placeholder(..., shape=[None, ...])
Run Code Online (Sandbox Code Playgroud)

是否有可能x在喂食后得到它的形状? tf.shape(x)[0]仍然回来None.

mrr*_*rry 16

如果x具有可变批量大小,获得实际形状的唯一方法是使用tf.shape()运算符.此运算符返回a中的符号值tf.Tensor,因此它可以用作其他TensorFlow操作的输入,但要获取形状的具体Python值,需要将其传递给Session.run().

x = tf.placeholder(..., shape=[None, ...])
batch_size = tf.shape(x)[0]  # Returns a scalar `tf.Tensor`

print x.get_shape()[0]  # ==> "?"

# You can use `batch_size` as an argument to other operators.
some_other_tensor = ...
some_other_tensor_reshaped = tf.reshape(some_other_tensor, [batch_size, 32, 32])

# To get the value, however, you need to call `Session.run()`.
sess = tf.Session()
x_val = np.random.rand(37, 100, 100)
batch_size_val = sess.run(batch_size, {x: x_val})
print x_val  # ==> "37"
Run Code Online (Sandbox Code Playgroud)