2016-11-17 102 views
31

假設我有一個Tensorflow張量。我如何獲得張量的尺寸(形狀)作爲整數值?我知道有兩種方法,tensor.get_shape()tf.shape(tensor),但我無法獲取整型值爲int32的形狀值。如何獲得Tensorflow張量的維度(形狀)爲int值?

例如,下面我創建了一個2-d張量,和我需要的行和列int32的號碼,以便我可以調用reshape()創建形狀(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. 

回答

45

要獲得形狀作爲整數列表,請執行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]))其中第一維可以推斷。

+0

謝謝,這讓我打電話和完整'tf.reshape()',但我真的想把'num_rows'和'num_cols'作爲其他操作的整數。 – stackoverflowuser2010

+0

嘗試'tensor.get_shape()。as_list()' – yuefengz

+1

是的,'as_list()'的作品。請將其添加到您的答案中,我會接受。 – stackoverflowuser2010

14

另一種方式來解決這個問題是這樣的:

tensor_shape[0].value 

這將返回Dimension對象的int值。

2

的2-d張量,就可以得到行數和列數爲INT32使用下面的代碼:

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

非常不雅。這如何增加已經提供的答案? – rayryeng

+0

@rayryeng謝謝 – Anna

相關問題