Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the size of a variable batch dimension

Tags:

tensorflow

assuming the input to the network is a placeholder with variable batch size, i.e.:

x = tf.placeholder(..., shape=[None, ...])

is it possible to get the shape of x after it has been fed? tf.shape(x)[0] still returns None.

like image 556
MBZ Avatar asked Jul 07 '16 01:07

MBZ


1 Answers

If x has a variable batch size, the only way to get the actual shape is to use the tf.shape() operator. This operator returns a symbolic value in a tf.Tensor, so it can be used as the input to other TensorFlow operations, but to get a concrete Python value for the shape, you need to pass it to 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"
like image 189
mrry Avatar answered Sep 30 '22 22:09

mrry