The easiest[A] way to evaluate the actual value of a Tensor
object is to pass it to the Session.run()
method, or call Tensor.eval()
when you have a default session (i.e. in a with tf.Session():
block, or see below). In general[B], you cannot print the value of a tensor without running some code in a session.
如果您正在尝试编程模型,并且想要一种简单的方法来评估张量,那么tf.InteractiveSession https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/InteractiveSession允许您在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()
(and Operation.run()
) 来电。在交互式环境(例如 shell 或 IPython 笔记本)中,当传递一个信息很乏味时,这会更容易。Session
对象无处不在。例如,以下内容适用于 Jupyter 笔记本:
with tf.Session() as sess: print(product.eval())
对于如此小的表达式来说,这可能看起来很愚蠢,但 Tensorflow 1.x 中的关键思想之一是延迟执行:构建一个大型且复杂的表达式非常便宜,当您想要评估它时,后端(您与Session
)能够更有效地安排其执行(例如并行执行独立部分并使用 GPU)。
[A]:要打印张量的值而不将其返回到 Python 程序,您可以使用tf.print() https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/print运算符,如Andrzej 在另一个答案中建议 https://stackoverflow.com/a/36296783/3574081。根据官方文档:
为了确保操作符运行,用户需要将生成的操作传递给tf.compat.v1.Session
的 run 方法,或者通过指定 with 将操作用作已执行操作的控制依赖项tf.compat.v1.control_dependencies([print_op]
),它被打印到标准输出。
另请注意:
在 Jupyter 笔记本和协作中,tf.print
打印到笔记本单元输出。它不会写入笔记本内核的控制台日志。
[乙]:你might能够使用tf.get_static_value() https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/get_static_value函数获取给定张量的常量值(如果其值可有效计算)。