gpt4 book ai didi

python - 在图形创建时跟踪张量形状

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:34 25 4
gpt4 key购买 nike

在某些情况下,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>

在上面的示例中,reshape() 可以看到作为 shape 传入的张量的值为 2,结果输出的形状为 (2,3) 但 zeros() 不能,静态形状为 ( ,3).差异的原因是什么?

我的同事发布了 Determining tensor shapes at time of graph creation in TensorFlow ,这是基于相同的潜在问题,但他问的是一个略有不同的问题,即如何最好地使用 tensorflow 来解决此类问题,而我的问题是关于为什么 tensorflow 会以这种方式运行。是错误吗?

最佳答案

TD;DR:

  • tf.reshape 可以推断输出的形状,但 tf.zeros 不能;
  • shape 两个函数都支持整数(如static/definite)和张量(如dynamic/indefinite)。

代码更具体、更清晰:

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!

当使用 Tensor(如 tf.constant([2])[0])作为 shape 创建另一个 张量(如tf.zeros(shape)),形状在图创建时总是不确定的。然而,tf.reshape() 是不同的。它可以使用输入的形状和给定​​的形状(静态部分)推断出输出的形状。

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

关于python - 在图形创建时跟踪张量形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com