stackoverflowuser2010 stackoverflowuser2010 - 1 year ago 1165
Python Question

How to get Tensorflow tensor dimensions (shape) as int values?

Suppose I have a Tensorflow tensor. How do I get the the dimensions (shape) of the tensor as integer values? I know there are two methods,

, but I can't get the shape values as integer (int32) values.

For example, in the code below, I've created a 2-D tensor, and I need to get the number of rows and columns as int32 so that I can call
to create a new tensor of shape
(num_rows * num_cols, 1)
. However, the method
returns values as
type, not

import tensorflow as tf
import numpy as np

sess = tf.Session()
tensor = tf.convert_to_tensor(np.array([[1001,1002,1003],[3,4,5]]), dtype=tf.float32)
# array([[ 1001., 1002., 1003.],
# [ 3., 4., 5.]], dtype=float32)

tensor_shape = tensor.get_shape()
# TensorShape([Dimension(2), Dimension(3)])
print tensor_shape
# (2, 3)

num_rows = tensor_shape[0] # ???
num_cols = tensor_shape[1] # ???

tensor2 = tf.reshape(tensor, (num_rows*num_cols, 1))
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/", line 1750, in reshape
# name=name)
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 454, in apply_op
# as_ref=input_arg.is_ref)
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 621, in convert_to_tensor
# ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 180, in _constant_tensor_conversion_function
# return constant(v, dtype=dtype, name=name)
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 163, in constant
# tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 353, in make_tensor_proto
# _AssertCompatible(values, dtype)
# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/", line 290, in _AssertCompatible
# (, repr(mismatch), type(mismatch).__name__))
# TypeError: Expected int32, got Dimension(6) of type 'Dimension' instead.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download