如何获取Tensorflow张量尺寸(形状)作为int值?


88

假设我有一个Tensorflow张量。如何获取张量的尺寸(形状)作为整数值?我知道有两种方法,tensor.get_shape()tf.shape(tensor),但是我不能将形状值作为整int32数值。

例如,下面我创建了一个二维张量,我需要获取行数和列数,int32以便可以调用reshape()以创建shape张量(num_rows * num_cols, 1)。但是,该方法tensor.get_shape()返回值作为Dimension类型,而不是类型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))    
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1750, in reshape
#     name=name)
#   File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 454, in apply_op
#     as_ref=input_arg.is_ref)
#   File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", 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/constant_op.py", 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/constant_op.py", 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/tensor_util.py", line 353, in make_tensor_proto
#     _AssertCompatible(values, dtype)
#   File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 290, in _AssertCompatible
#     (dtype.name, repr(mismatch), type(mismatch).__name__))
# TypeError: Expected int32, got Dimension(6) of type 'Dimension' instead.

Answers:


126

要将形状显示为整数列表,请执行tensor.get_shape().as_list()

要完成tf.shape()通话,请尝试tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1]))。或者,您可以直接tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1]))在可以推断出其第一维的地方进行操作。


谢谢,这让我打电话给complete tf.reshape(),但是我真的很想为其他操作获取num_rowsnum_cols作为整数。
stackoverflowuser2010

6
试试tensor.get_shape().as_list()
yuefengz

1
是的,as_list()工作。请添加到您的答案中,我会接受。
stackoverflowuser2010

2
为了完整起见,此代码有效:num_rows, num_cols = x.get_shape().as_list()
stackoverflowuser2010

1
真好!我正在使用python int()强制转换x.get_shape()的结果。例如num_rows = int(x.get_shape()[1]),num_cols = int(x.get_shape()[2]),等等。是的,有点怪癖,可以解决这个讨厌的错误,但它确实有效。感谢您启发我采用更好的方法:-)
SherylHohman

31

解决此问题的另一种方法是这样的:

tensor_shape[0].value

这将返回Dimension对象的int值。


6

对于二维张量,可以使用以下代码将行和列的数量获取为int32:

rows, columns = map(lambda i: i.value, tensor.get_shape())

2
非常优雅。这如何添加到已经提供的答案中?
rayryeng

4

2.0兼容答案:在中Tensorflow 2.x (2.1),您可以获取张量的尺寸(形状)为整数值,如以下代码所示:

方法1(使用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]

方法2(使用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

在更高版本中(使用TensorFlow 1.14测试),有一种更类似numpy的方式来获取张量的形状。您可以tensor.shape用来获取张量的形状。

tensor_shape = tensor.shape
print(tensor_shape)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.