Tensorflowテンソルがあるとします。どのようにしてテンソルの次元(形状)を整数値として得るのですか?私はtensor.get_shape()
とtf.shape(tensor)
の2つの方法があることを知っていますが、整数値int32
の値として形状値を取得できません。例えばTensorflowテンソルの寸法(形状)をint値として取得するには?
、私は2-Dテンソルを作成した、と私は形状(num_rows * num_cols, 1)
のテンソルを作成するためにreshape()
を呼び出すことができるようにint32
として行と列の数を取得する必要があります下に。ただし、tensor.get_shape()
メソッドは、ではなく、Dimension
タイプの値を返します。
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.
おかげで、しかし、私は本当に 'num_rows'と' num_cols'を他の演算のための整数として得たいと思います。 – stackoverflowuser2010
'tensor.get_shape()。as_list()'を試してください。 – yuefengz
うん、 'as_list()'はうまくいきます。あなたの答えにそれを加えてください、そして私は受け入れます。 – stackoverflowuser2010