深度學習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))
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.x的框架執行tensorflow1.x語法所寫程式所需要在程式一開始(引用tensorflow庫後)宣告的語句,用於tensorflow不同版本之間相容性的做法tensorflow2.4 官方API文件
摘要:
Tensorflow 1.x and 2.x APIs
Thecompat.v1
andcompat.v2
submodules provide a complete copy of both thev1
andv2
APIs for backwards and forwards compatibility across TensorFlow versions 1.x and 2.x. See the
這個compat.v1
和compat.v2
子模組提供兩個v1
和v2
用於前後相容的API跨TensorFlow版本1.x和2.x。見遷移指南關於細節。
Utilities for writing compatible code
Aside from thecompat.v1
andcompat.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