Suppose I have a Tensorflow tensor. How do I get the dimensions (shape) of the tensor as integer values? I know there are two methods, tensor.get_shape()
and
Another simple solution is to use map()
as follows:
tensor_shape = map(int, my_tensor.shape)
This converts all the Dimension
objects to int
Another way to solve this is like this:
tensor_shape[0].value
This will return the int value of the Dimension object.
In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape
to get the shape of the tensor.
tensor_shape = tensor.shape
print(tensor_shape)
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
2.0 Compatible Answer: In Tensorflow 2.x (2.1)
, you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:
Method 1 (using tf.shape
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape) # [2,3]
Method 2 (using tf.get_shape()
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape) # [2,3]
To get the shape as a list of ints, do tensor.get_shape().as_list()
.
To complete your tf.shape()
call, try tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))
. Or you can directly do tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1]))
where its first dimension can be inferred.