tf.session() 在 tensorflow 2.x 中被彻底移除,因其默认启用急切执行;需先调用 tf.compat.v1.disable_eager_execution(),再使用 tf.compat.v1.session(),且禁用必须在任何 tensor 创建前执行。

tf.Session() 在 TensorFlow 2.x 中根本不存在
这不是拼写错误或导入遗漏,而是设计层面的移除。TensorFlow 2.x 默认启用急切执行(eager execution),所有运算立即求值,不再需要显式创建 Session 来“运行图”。所以当你写 sess = tf.Session(),Python 直接报 AttributeError: module 'tensorflow' has no attribute 'Session' —— 因为这个属性确实被删了。
tf.compat.v1.Session() 为什么有时仍会失败
即使改成 tf.compat.v1.Session(),也常遇到两个典型问题:
-
RuntimeError: The Session graph is empty:因为急切执行没关,tf.compat.v1.Session()尝试运行静态图,但此时操作已按 eager 模式执行完毕,图为空 -
AttributeError: module 'tensorflow._api.v2.compat.v1' has no attribute 'Sesstion':纯属手误,比如把Session拼成Sesstion,注意是Session,不是Sesstion或session
正确做法必须同时满足两点:
- 在所有 TensorFlow 调用前加
tf.compat.v1.disable_eager_execution() - 使用
tf.compat.v1.Session()(注意拼写和路径)
为什么不能只换函数,还得关 eager 执行
急切执行和静态图机制互斥。一旦启用 eager(TF2 默认),tf.constant、tf.add 等直接返回具体数值,不构建图节点;而 tf.compat.v1.Session().run() 依赖图结构。不关 eager,就等于让司机开着电动车去加油站——根本没油管。
关键顺序不能错:
- 第一行代码就得是
import tensorflow as tf - 第二行必须是
tf.compat.v1.disable_eager_execution() - 之后才能定义
tf.constant、tf.placeholder(TF1 风格)等图节点
替代方案:真要迁移到 TF2,别硬套 Session
如果只是跑通旧代码,用 compat.v1 + disable_eager_execution() 是最快路径。但长期维护建议转向原生 TF2 模式:
- 去掉所有
Session、placeholder、run() - 用
@tf.function包裹可加速的函数(它自动构建图) - 变量直接用
tf.Variable,无需tf.global_variables_initializer() - Keras 模型训练直接调
model.fit(),不碰底层 session
真正容易被忽略的点是:disable_eager_execution() 必须在任何 Tensor 创建之前调用,哪怕只提前 import 了一个其他模块并触发了 TF 初始化,再调这个函数也会失效 —— 这类隐式初始化很难排查,往往只能重开 Python 进程。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











