1. 程式人生 > 其它 >深度學習tensorflow2.x RuntimeError: The Session graph is empty. Add operations to the graph before calling run(). 報錯解決方法

深度學習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))


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.v1andcompat.v2submodules provide a complete copy of both thev1andv2APIs for backwards and forwards compatibility across TensorFlow versions 1.x and 2.x. See the

migration guidefor details.

這個compat.v1compat.v2子模組提供兩個v1v2用於前後相容的API跨TensorFlow版本1.x和2.x。見遷移指南關於細節。

Utilities for writing compatible code

Aside from thecompat.v1andcompat.v2submodules,tf.compatalso contains a set of helper functions for writing code that works in both:

除了compat.v1compat.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