更新时间:2023-12-02 18:46:10
评估 Tensor
对象的实际值的最简单的[A] 方法是传递它到 Session.run()
方法,或者当你有一个默认会话时调用 Tensor.eval()
(即在 中使用 tf.Session():
块,或见下文).通常[B],如果不在会话中运行一些代码,就无法打印张量的值.
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
允许您在程序开始时打开一个会话,然后将该会话用于所有 Tensor.eval()
(和 Operation.run()
)调用.这在交互式设置中会更容易,例如 shell 或 IPython 笔记本,因为到处传递 Session
对象很乏味.例如,以下内容适用于 Jupyter 笔记本:
If you are experimenting with the programming model, and want an easy way to evaluate tensors, the tf.InteractiveSession
lets you open a session at the start of your program, and then use that session for all Tensor.eval()
(and Operation.run()
) calls. This can be easier in an interactive setting, such as the shell or an IPython notebook, when it's tedious to pass around a Session
object everywhere. For example, the following works in a Jupyter notebook:
with tf.Session() as sess: print(product.eval())
对于这么小的表达式来说,这可能看起来很愚蠢,但 Tensorflow 1.x 中的一个关键思想是延迟执行:构建一个大而复杂的表达式非常便宜,而且当你想要的时候为了对其进行评估,后端(您通过 Session
连接到该后端)能够更有效地安排其执行(例如并行执行独立部分和使用 GPU).
This might seem silly for such a small expression, but one of the key ideas in Tensorflow 1.x is deferred execution: it's very cheap to build a large and complex expression, and when you want to evaluate it, the back-end (to which you connect with a Session
) is able to schedule its execution more efficiently (e.g. executing independent parts in parallel and using GPUs).
[A]:要打印张量的值而不将其返回到 Python 程序,您可以使用 tf.print()
运算符,如 Andrzej 在另一个答案中建议.根据官方文档:
[A]: To print the value of a tensor without returning it to your Python program, you can use the tf.print()
operator, as Andrzej suggests in another answer. According to the official documentation:
为了保证operator运行,用户需要将生成的op传递给tf.compat.v1.Session
的run方法,或者使用op作为执行ops的控制依赖使用 tf.compat.v1.control_dependencies([print_op]
) 指定,打印到标准输出.
To make sure the operator runs, users need to pass the produced op to
tf.compat.v1.Session
's run method, or to use the op as a control dependency for executed ops by specifying withtf.compat.v1.control_dependencies([print_op]
), which is printed to standard output.
还要注意:
在 Jupyter 笔记本和 colab 中,tf.print
打印到笔记本单元输出.它不会写入笔记本内核的控制台日志.
In Jupyter notebooks and colabs,
tf.print
prints to the notebook cell outputs. It will not write to the notebook kernel's console logs.
[B]:您可能能够使用tf.get_static_value()
函数用于获取给定张量的常量值(如果其值可有效计算).
[B]: You might be able to use the tf.get_static_value()
function to get the constant value of the given tensor if its value is efficiently calculable.