获取变量批次尺寸
问题描述:
假设输入到网络的规模是一个placeholder
具有可变批量大小,即:获取变量批次尺寸
x = tf.placeholder(..., shape=[None, ...])
是有可能得到的x
形状已经馈送后? tf.shape(x)[0]
仍然返回None
。
答
如果x
具有变量批量大小,获得实际形状的唯一方法是使用tf.shape()
运算符。该运算符在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"
答
使用x.get_shape().as_list()
可以得到张量x的形状。要获得第一维(批量大小),您可以使用x.get_shape().as_list()[0]
。