Reputation: 27592
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
.
Upvotes: 6
Views: 18945
Reputation: 126154
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"
Upvotes: 21
Reputation: 346
You can get the shape of the tensor x using x.get_shape().as_list()
. For getting the first dimension (batch size) you can use x.get_shape().as_list()[0]
.
Upvotes: 0