tf.shape() 在张量流中得到错误的形状

tf.shape() get wrong shape in tensorflow

我这样定义张量:

x = tf.get_variable("x", [100])

但是当我尝试打印张量的形状时:

print( tf.shape(x) )

我得到Tensor("Shape:0",shape=(1,),dtype=int32),为什么输出的结果不应该是shape=(100)

tf.shape(input, name=None) returns 表示输入形状的一维整数张量。

您正在寻找:x.get_shape() returns x 变量的 TensorShape

更新:因为这个答案,我写了一篇文章来阐明 Tensorflow 中的 dynamic/static 形状:https://pgaleone.eu/tensorflow/2018/07/28/understanding-tensorflow-tensors-shape-static-dynamic/

澄清:

tf.shape(x) 创建一个 op 和 returns 一个对象,它代表构造的 op 的输出,这就是您当前正在打印的内容。要获得形状,运行 会话中的操作:

matA = tf.constant([[7, 8], [9, 10]])
shapeOp = tf.shape(matA) 
print(shapeOp) #Tensor("Shape:0", shape=(2,), dtype=int32)
with tf.Session() as sess:
   print(sess.run(shapeOp)) #[2 2]

credit:看了上面的答案后,我看到了 的答案,我发现它更有帮助,我试着在这里重新措辞。

类似的问题在TF FAQ中有很好的解释:

In TensorFlow, a tensor has both a static (inferred) shape and a dynamic (true) shape. The static shape can be read using the tf.Tensor.get_shape method: this shape is inferred from the operations that were used to create the tensor, and may be partially complete. If the static shape is not fully defined, the dynamic shape of a Tensor t can be determined by evaluating tf.shape(t).

所以tf.shape()returns你是一个张量,大小总是shape=(N,),并且可以在一个会话中计算:

a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
with tf.Session() as sess:
    print sess.run(tf.shape(a))

另一方面,您可以使用 x.get_shape().as_list() 提取静态形状,这可以在任何地方计算。

举个简单的例子,让事情更清楚:

a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
print('-'*60)
print("v1", tf.shape(a))
print('-'*60)
print("v2", a.get_shape())
print('-'*60)
with tf.Session() as sess:
    print("v3", sess.run(tf.shape(a)))
print('-'*60)
print("v4",a.shape)

输出将是:

------------------------------------------------------------
v1 Tensor("Shape:0", shape=(3,), dtype=int32)
------------------------------------------------------------
v2 (2, 3, 4)
------------------------------------------------------------
v3 [2 3 4]
------------------------------------------------------------
v4 (2, 3, 4)

这也应该有帮助:

简单地说,使用tensor.shape得到静态形状:

In [102]: a = tf.placeholder(tf.float32, [None, 128])

# returns [None, 128]
In [103]: a.shape.as_list()
Out[103]: [None, 128]

而要获得 动态形状 ,请使用 tf.shape():

dynamic_shape = tf.shape(a)

您还可以像在 NumPy 中那样使用 your_tensor.shape 获得形状,如下例所示。

In [11]: tensr = tf.constant([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])

In [12]: tensr.shape
Out[12]: TensorShape([Dimension(2), Dimension(5)])

In [13]: list(tensr.shape)
Out[13]: [Dimension(2), Dimension(5)]

In [16]: print(tensr.shape)
(2, 5)

另外,这个例子,对于可以evaluated的张量。

In [33]: tf.shape(tensr).eval().tolist()
Out[33]: [2, 5]

Tensorflow 2.0 兼容答案Tensorflow 2.x (>= 2.0) nessuno 解决方案的兼容答案如下所示:

x = tf.compat.v1.get_variable("x", [100])

print(x.get_shape())