Tensorflow:会话图为空。 Python

Tensorflow: The Session graph is empty. Python

大家好,我正在使用 Tensorflow 2.0

在这些代码行中:

import tensorflow as tf
hello = tf.constant('Hello World')
sess = tf.compat.v1.Session()
sess.run(hello) <-- Error in this line

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

知道如何解决吗?

好的,我找到方法了:

g = tf.Graph() 
with g.as_default():   
  # Define operations and tensors in `g`.   
  hello = tf.constant('hello')   
  assert hello.graph is g

sess = tf.compat.v1.Session(graph=g) 
sess.run(hello)

b'hello'

感谢您的宝贵时间!

Tensorflow 核心 r2.0 默认启用急切执行。所以,在不改变它的情况下,我们只需要改变我们的代码,如下所示 Launch the graph in a session.

> with tf.compat.v1.Session() as sess:
>     # Building a graph
>     hello = tf.constant("hello")
>     print(sess.run(hello))

根据 Tensorflow 文档..

A default Graph is always registered, and accessible by calling tf.compat.v1.get_default_graph

对于不需要声明 tf.Graph() 的基本操作,您可以定义一个具有更多计算和数据集的图,您可以定义一个图并调用进入session。

请参考:更多信息 https://www.tensorflow.org/api_docs/python/tf/Graph https://github.com/OlafenwaMoses/ImageAI/issues/400