0 votes
1 view
in Machine Learning by (13.5k points)

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 tf.shape(tensor), but I can't get the shape values as integer int32 values.

For example, 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 reshape() to create a tensor of shape (num_rows * num_cols, 1). However, the method tensor.get_shape() returns values as Dimension type, not int32.

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)

sess.run(tensor)    

# array([[ 1001.,  1002., 1003.],

#        [ 3.,     4., 5.]], dtype=float32)

tensor_shape = tensor.get_shape()    

tensor_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)) 

TypeError: Expected int32, got Dimension(6) of type 'Dimension' instead.

1 Answer

0 votes
by (33.1k points)

Code to get the shape as a list of ints

tensor.get_shape().as_list()

To complete your

tf.shape() function is incomplete, Add the following code to complete:

tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))

Or 

tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1])) 

Hope this answer helps.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...