tensorflow - 调用 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 进行评估。
解决方案
推荐阅读
- python - 比较两个字符串中的每个字符并递增:Python
- java - 如何查找双向链表中的数字是否介于最大值和最小值之间?
- bash - 通过 bash 回滚一组安全的移动操作
- javascript - getAttribute() 不适用于类名?
- php - 如何将 \n 值更改为 X 之类的值
- sql - sp_executesql 必须声明变量
- reactjs - 如何在本机反应中将数据从抽屉自定义组件传递到屏幕?
- db2 - 如何删除 DB2 Java 存储过程?
- javascript - AngularJS 为什么我的控制器没有响应?
- python - Python:抓取.json,输入pandas DataFrame并输出为excel