请参见tf.unstack之后的张量值



使用命令返回张量值

a, b, c, d, e = tf.unstack(x, axis=1)

那么当我试图显示a的值时,我得到的只是:

<tf.Tensor 'unstack_4:0' shape=(5,) dtype=int32>

我怎样才能看到这个张量的值?

我是TensorFlow的新手。

在TensorFlow 2中,如果尚未对tf.function之外的张量求值,则可以使用tf.backend.eval()对其求值(下一节将对此进行详细介绍(。

a, b, c, d, e = tf.unstack(x, axis=1)
print(tf.keras.backend.eval(a))

为什么不可能只键入a并查看张量值?

您可能没有启用Eager Execution。这一点的意义在于深入研究TensorFlow的内部工作原理。

TensorFlow有两种执行模式,Eager ExecutionGraph Execution

渴望执行

Eager Execution中,像tf.unstack这样的操作会立即求值并返回具体值。这是您期望python的常见行为,也是TensorFlow 2中tf.function和类似tf.compat.v1.disable_eager_execution()的函数之外的默认执行模式。

Eager Execution中,将a传递到解释器中确实会返回一个具体的值。

>>> import tensorflow as tf
>>> # Create a 5x5 matrix
>>> x = tf.constant([[i for i in range(5)] for i in range(5)])
# A bunch of messages regarding compute devices appear as TensorFlow initializes its backend to evaluate the expression immediately
>>> a, b, c, d, e = tf.unstack(x, axis=1)
>>> a
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 0, 0, 0, 0], dtype=int32)>

图形执行

使用Graph Execution,每次输入像tf.add(a, b)tf.unstack这样的操作时,这些操作都会添加到TensorFlow图中,而不是立即执行。通过首先构建图并推迟执行,Tensorflow可以通过优化构建的图来提高计算性能。

因此,使用类似a, b, c, d, e = tf.unstack(x, axis=1)的语句,a将打印TensorFlow操作,而不是输出值。

>>> import tensorflow as tf
>>> # Here we disable eager execution
>>> tf.compat.v1.disable_eager_execution()
>>> # Create a 5x5 matrix as before. Notice the lack of messages
>>> x = tf.constant([[i for i in range(5)] for i in range(5)])
>>> a, b, c, d, e = tf.unstack(x, axis=1)
>>> a
<tf.Tensor 'unstack:0' shape=(5,) dtype=int32>
>>> # Evaluate the graph and store it in result
>>> result = tf.keras.backend.eval(a)
>>> result
array([0, 0, 0, 0, 0], dtype=int32)
>>> # `a` still refers to an operation if you were wondering
>>> a
<tf.Tensor 'unstack:0' shape=(5,) dtype=int32>