gpt4 book ai didi

python - 如何在 TensorFlow 中打印张量对象的值?

转载 作者:IT老高 更新时间:2023-10-28 12:12:14 26 4
gpt4 key购买 nike

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

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

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

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

但是我怎么知道product的值(value)呢?

以下没有帮助:

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

我知道图表在 Sessions 上运行,但没有任何方法可以检查 Tensor 对象的输出,而无需在 中运行图表 session

最佳答案

评估 Tensor 对象的实际值的最简单[A] 方法是将其传递给 Session.run()方法,或在有默认 session 时调用 Tensor.eval()(即在 with tf.Session(): block 中,或见下文)。通常[B],如果不在 session 中运行一些代码,就无法打印张量的值。

如果您正在试验编程模型,并且想要一种简单的方法来评估张量,tf.InteractiveSession让您在程序开始时打开一个 session ,然后将该 session 用于所有 Tensor.eval()(和 Operation.run())调用。当在任何地方传递 Session 对象很乏味时,这在交互式环境中会更容易,例如 shell 或 IPython 笔记本。例如,以下内容适用于 Jupyter 笔记本:

with tf.Session() as sess:  print(product.eval()) 

对于这么小的表达式,这可能看起来很傻,但是 Tensorflow 1.x 中的一个关键思想是延迟执行:构建一个大而复杂的表达式非常便宜,并且当你需要时为了评估它,后端(您通过 Session 连接到的)能够更有效地安排其执行(例如,并行执行独立部分并使用 GPU)。


[A]:要打印张量的值而不将其返回到 Python 程序,可以使用 tf.print()运算符,如 Andrzej suggests in another answer .根据官方文档:

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 with tf.compat.v1.control_dependencies([print_op]), which is printed to standard output.

还要注意:

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

关于python - 如何在 TensorFlow 中打印张量对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33633370/

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