Mario Palazuelos
Mario Palazuelos

Reputation: 33

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

I have the following error when trying to run the code:

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

Code

h = tf.constant('Hello, this is TensorFlow')
s = tf.compat.v1.Session()
print(s.run(h))

Upvotes: 1

Views: 2957

Answers (2)

Ako Zoom
Ako Zoom

Reputation: 1

As there could be this error:

AttributeError:
Tensor.graph is meaningless when eager execution is enabled.

you'll need to disable eager in TF2.x with:

 tf.compat.v1.disable_eager_execution()

Upvotes: -1

thushv89
thushv89

Reputation: 11333

You can fix this three ways,

Downgrade to TF 1.x

tf.Session() is a thing of the past. So if you want to use sessions, you should use TF 1.x. Otherwise you need to change your code to use eager execution by removing session objects.

Use TF 2.x but not use tf.Session()

h = tf.constant('Hello, this is TensorFlow')
print(tf.print(h))

Use TF 2.x

You can get your sample to work by doing the following. So we are specifically saying that this operation goes in the default TF graph, which the session will then recognize the operations from.

s = tf.compat.v1.Session()
with tf.compat.v1.get_default_graph().as_default():
  h = tf.constant('Hello, this is TensorFlow')
  print(s.run(h))

Upvotes: 2

Related Questions