Tensorflow错误:RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

在解决了错误:AttributeError: module 'tensorflow' has no attribute 'Session'之后,又出现了新的错误

RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

错误原因:

最终还是因为安装的Tensorflow版本问题

解决方法:

重新安装Tensorflow,选择1.X的版本进行安装,如下图

其他解决方法

在解决上述问题的过程中,起初并没有采取这么简单粗暴的方法,也查询了其他解决办法,但是都没有很好的解决自己的问题,现将方法总结如下:

1.添加代码:tf.compat.v1.disable_eager_execution()

在运行session之前,添加代码tf.compat.v1.disable_eager_execution()保证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的函数
print(sess.run(hello))

2.清理开始的会话session

引入keras来清理考试会话的session

import tensorflow as tf
import keras  #引入keras
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()  
config.gpu_options.allow_growth = True 
sess = tf.Session(config=config)
set_session(sess)
keras.backend.clear_session() #此句代码分量很重

参考博客:

CSDN博主「爱学习的人工智障」:https://blog.csdn.net/weixin_38410551/article/details/103631977

CSDN博主「视觉弘毅」:https://blog.csdn.net/weixin_41041772/article/details/100085170

原文地址:https://www.cnblogs.com/Qi77/p/12573577.html