首页 > 解决方案 > 调用 Session() 后无法打印变量

问题描述

我见过如下工作示例:

# GOOD CODE

import tensorflow as tf

# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

# Launch the graph in a session.
sess = tf.compat.v1.Session()

# Evaluate the tensor `c`.
print(sess.run(c))

这可以。我想我明白了。构建图只是定义了图架构,但不执行图。只有在调用会话时才会执行。但后来我认为以下方法会起作用:

# BAD CODE 

import tensorflow as tf

# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

# Launch the graph in a session.
sess = tf.compat.v1.Session()

# Evaluate the tensor `c`.

sess.run(c)
print(c)

但它没有,我所看到的只是......

Tensor("mul:0", shape=(), dtype=float32)

...我不知道为什么。我有两个想法:

想法 1:也许变量 c 仅存在于会话的上下文中,并且在 sess.run(c) 完成时以某种方式过期?可以修改代码以使变量 c 在 sess.run(c) 调用后保持活动状态吗?

想法 2:不知何故,TF 想——“这家伙没有对 c 做任何事情(至少不是立即),所以我现在不打算执行任何事情”......所以根本没有对 c 进行评估。

标签: tensorflow

解决方案


推荐阅读