Python 在图形创建时跟踪张量形状

Python 在图形创建时跟踪张量形状,python,tensorflow,Python,Tensorflow,在某些情况下,tensorflow似乎能够在图形创建时检查张量的值,而在其他情况下则无法检查 >>> shape = [constant([2])[0], 3] >>> reshape([1,2,3,4,5,6], shape) <tf.Tensor 'Reshape_13:0' shape=(2, 3) dtype=int32> >>> zeros(shape) <tf.Tensor 'zeros_2:0' shape=(

在某些情况下,tensorflow似乎能够在图形创建时检查张量的值,而在其他情况下则无法检查

>>> shape = [constant([2])[0], 3]
>>> reshape([1,2,3,4,5,6], shape)
<tf.Tensor 'Reshape_13:0' shape=(2, 3) dtype=int32>
>>> zeros(shape)
<tf.Tensor 'zeros_2:0' shape=(?, 3) dtype=float32>
>>shape=[常数([2])[0],3]
>>>重塑([1,2,3,4,5,6],形状)
>>>零(形状)
在上面的示例中,reforme()可以看到作为shape传入的张量的值为2,结果输出的形状为(2,3),但zeros()不能,静态形状为(?,3)。差异的原因是什么

我的同事发表了一篇文章,这篇文章基于相同的基本问题,但他提出了一个稍微不同的问题,即如何最好地使用tensorflow来解决这类问题,而我的问题是为什么tensorflow会这样做。这是一个bug吗?

TD;博士:

  • tf.reforme
    可以推断输出的形状,但是
    tf.zero
    不能
  • shape
    支持两个函数的整数(as静态/确定的)和张量(as动态/不确定的

代码更具体、更清晰:

shape = [tf.constant([2])[0], tf.constant([3])[0]]
print(tf.reshape([1,2,3,4,5,6], shape))  
# Tensor("Reshape:0", shape=(?, ?), dtype=int32)
print(tf.zeros(shape))  
# Tensor("zeros:0", shape=(?, ?), dtype=float32)
这是:

shape = [tf.constant([5])[0], 3]
print tf.reshape([1,2,3,4,5,6], shape)  
# Tensor("Reshape:0", shape=(2, 3), dtype=int32)
# This will cause an InvalidArgumentError at running time!
当使用一个
张量
(如
tf.常量([2])[0]
)作为
形状
创建另一个
张量
(如
tf.零(形状)
)时,形状在图形创建时总是不确定的。但是,
tf.reformate()
是不同的。它可以使用输入的形状和给定的形状(静态部分)推断输出的形状


在您的代码中,
3
是一个静态整数,输入的形状是给定的(
[6]
);形状
(2,3)
实际上是通过推断而不是提供的。这可以在代码的第二部分中得到证明。虽然我给出了一个
tf.常数([5])
,但形状没有改变。(在图形创建时并没有错误,但在运行时引发了一个错误!)

是的,我得出了相同的结论,即整形是使用第一个参数的形状来推断输出形状应该是什么。