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

后端 未结 6 1786
孤城傲影
孤城傲影 2020-12-12 20:23

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

相关标签:
6条回答
  • 2020-12-12 20:35

    Another simple solution is to use map() as follows:

    tensor_shape = map(int, my_tensor.shape)
    

    This converts all the Dimension objects to int

    0 讨论(0)
  • 2020-12-12 20:37

    Another way to solve this is like this:

    tensor_shape[0].value
    

    This will return the int value of the Dimension object.

    0 讨论(0)
  • 2020-12-12 20:37

    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)
    
    0 讨论(0)
  • 2020-12-12 20:44

    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())
    
    0 讨论(0)
  • 2020-12-12 20:46

    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]
    
    0 讨论(0)
  • 2020-12-12 20:56

    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.

    0 讨论(0)
提交回复
热议问题