深度学习tensorflow2.x RuntimeError: The Session graph is empty. Add operations to the graph before calling run(). 报错解决方法
import tensorflow as tf tf.compat.v1.disable_eager_execution() #保证sess.run()能够正常运行 hello = tf.constant('hello,tensorflow') sess= tf.compat.v1.Session()#版本2.0的函数
#sess=tf.Session 版本1.0的函数 print(sess.run(hello))
![](https://img2020.cnblogs.com/blog/2187330/202108/2187330-20210807163544537-1368231402.png)
tf.compat.v1.disable_eager_execution()
This function can only be called before any Graphs, Ops, or Tensors have been created. It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.
此函数只能在创建任何图、操作或张量之前调用。它可以在程序开始时用于从TensorFlow 1.x到2.x的复杂迁移项目。
tensorflow2.4 官方API文档
摘要:
Tensorflow 1.x and 2.x APIs
The compat.v1
and compat.v2
submodules provide a complete copy of both the v1
and v2
APIs for backwards and forwards compatibility across TensorFlow versions 1.x and 2.x. See the migration guide for details.
这个compat.v1
和compat.v2
子模块提供两个v1
和v2
用于前后兼容的API跨TensorFlow版本1.x和2.x。见迁移指南关于细节。
Utilities for writing compatible code
Aside from the compat.v1
and compat.v2
submodules, tf.compat
also contains a set of helper functions for writing code that works in both:
除了compat.v1
和compat.v2
子模块,tf.compat
还包含一组用于编写代码的助手函数,这些函数在以下两个方面都可以工作:
- TensorFlow 1.x and 2.x
- Python 2 and 3
https://tensorflow.google.cn/versions/r2.4/api_docs/python/tf/compat