TensorFlow技术解析与实战
在阅读《TensorFlow技术解析与实战》(ISBN 978-7-115-45613-7)的过程中,发现全书是基于TensorFlow 1.1版本来着手的,而当前普遍已经使用TensorFlow 2.x版本,因此我将自己在阅读过程中以及代码实现过程中产生的问题以及寻找到的解决方法记录下来,方便其他的读者在阅读过程中遇到相同的问题时可以更加快速的得以解决。
TensorFlow环境的准备
在tensorflow1.x 版本下的代码需修改后才能使用
tensorflow 1.x版本下的代码:
import tensorflow as tf
sess = tf.Session()
a = tf.constant(10)
b = tf.constant(22)
print(sess.run(a+b))
在2.x版本下运行上述代码会产生错误:
RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
问题产生的原因及解决方案来自于博客1:
原因:无法执行sess.run()的原因是tensorflow版本不同导致的,tensorflow版本2.x无法兼容版本1.x.
解决方案:tf.compat.v1.disable_eager_execution()
tensorflow 2.x版本下的正确运行代码为:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()
a = tf.constant(10)
b = tf.constant(22)
print(sess.run(a+b))
https://blog.csdn.net/weixin_38410551/article/details/103631977 ↩︎