如何在 TensorFlow 中打印 Tensor 对象的值?

2024-01-18

我一直在使用 TensorFlow 中矩阵乘法的介绍性示例。

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

当我打印产品时,它会将其显示为Tensor object:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>

但我怎么知道的价值product?

以下内容没有帮助:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)

我知道图表运行于Sessions,但是有没有什么方法可以检查 a 的输出Tensor对象而不在 a 中运行图形session?


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函数获取给定张量的常量值(如果其值可有效计算)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 TensorFlow 中打印 Tensor 对象的值? 的相关文章

随机推荐