Tensorflow 2.0中x.shape和tf.shape()有什么区别?

问题描述 投票:1回答:1

我想知道何时需要使用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返回一个元组,但我不容易找到哪一个更好,哪个应该是首选。

任何人都可以对此提供一些建议吗?

python tensorflow shapes
1个回答
0
投票

.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

希望这能回答您的问题,祝您学习愉快!

© www.soinside.com 2019 - 2024. All rights reserved.