[TensorFlow笔记] 获取Tensor的维度(tf.shape(x)、x.shape和x.get_shape()的区别)

import tensorflow as tf

input = tf.constant([[0,1,2],[3,4,5]])

print(type(input.shape))
print(type(input.get_shape()))
print(type(tf.shape(input)))
Out:
<class 'tensorflow.python.framework.tensor_shape.TensorShape'>
<class 'tensorflow.python.framework.tensor_shape.TensorShape'>
<class 'tensorflow.python.framework.ops.Tensor'>

可以看到s.shape和x.get_shape()都是返回TensorShape类型对象,而tf.shape(x)返回的是Tensor类型对象。

因此要想获得维度信息,则需要调用TensorShape的ts.as_list()方法,返回的是Python的list:

input.shape.as_list() # Out: [2,3]
input.get_shape().as_list() # Out: [2,3]

此外,还可以获得维度的个数:

input.shape.ndims # Out: 2
input.get_shape().ndims # Out: 2
tf.rank(input) # Out: type=Tensor, value=2

总结

获得Python原生类型的维度信息:

input.shape.as_list() # [2,3]
input.shape.ndims # 2

获得TensorFlow中Tensor类型的维度信息:

tf.shape(input)
tf.rank(input)

你可能感兴趣的:(TensorFlow,TensorFlow)