我想知道何时需要使用tf.shape()和x.shape()。我目前正在使用tensorflow 2.0 rc0
以下是示例代码。
#!/usr/bin/python3
import tensorflow as tf
a = tf.zeros((4, 3, 1))
print (tf.shape(a).numpy())
print (a.shape)
以上代码的结果如下:
[4 3 1]
(4, 3, 1)
[tf.shape(a).numpy()
返回numpy数组,而a.shape
返回一个元组,但我不容易找到哪一个更好,哪个应该是首选。
任何人都可以对此提供一些建议吗?
.numpy()
或Tensor
上的[Tensorflow ops
将返回您numpy.ndarray
。
示例:
a = tf.constant([1,2,3])
print(a.numpy())
print(tf.shape(a).numpy())
print(type(tf.shape(a)))
[1 2 3]
[3]
<class 'tensorflow.python.framework.ops.EagerTensor'>
但是Tensor.shape()
将具有类型TensorShape
,它将返回一个元组。
print(type(a.shape))
<class 'tensorflow.python.framework.tensor_shape.TensorShape'>
甚至NumPy数组都有一个shape属性,该属性返回数组每个维度的长度的元组。
data = np.array([11, 22, 33, 44, 55])
print(data.shape)
((5,)
在任何操作中使用tensor shape
的理想方式都是tf.shape(a)
,而不必转换为.numpy()
或使用Tensor.shape
希望这能回答您的问题,祝您学习愉快!