2

Running the following simple code:

import tensorflow as tf
#%%
a=tf.Variable(1, name="a")
b=tf.Variable(2, name="b")
f=a+b
init=tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as s:
    s.run(int)
    print(f.eval())

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

E V
  • 21
  • 3
  • Hello and welcome to SO. Have you search Internet for the error? Maybe [this question](https://stackoverflow.com/questions/54404821/runtimeerror-the-session-graph-is-empty-add-operations-to-the-graph-before-cal) helps? – Arthur Nov 14 '19 at 10:27
  • Or [this one](https://stackoverflow.com/questions/42593771/session-graph-is-empty) ? – Arthur Nov 14 '19 at 10:29
  • Also, you may want to explain where your code is adapted from... so that people can see the difference between your code and the template you used. – Arthur Nov 14 '19 at 10:30
  • This is the original code I got from a training Youtube video for tensorflow import tensorflow as tf a=tf.Variable(1, name="a") b=tf.Variable(2, name="b") f=a+b init=tf.global_variables_initializer() with tf.Session as s: init.run(f.eval8() – E V Nov 14 '19 at 10:40
  • Don't write that in the comments. You can edit your question instead :) And add a link to the video. Note that you can tag code like so `\`some short code\`` or by letting 4 spaces in front of a line. – Arthur Nov 14 '19 at 10:45
  • Just a thought, but if you plan on learning modern TensorFlow 2.x more generally, you might want to find a more recent tutorial. Things have changed quite a bit since the TensorFlow 1.x style of code you use above. – James Paul Turner Nov 14 '19 at 10:46

2 Answers2

2

In tensorflow 2.0 you don't need to create the session. If you'd like to print the value of f you can just write

tf.print(f)

Or if you'd like to assign value to the variable you can write

new_value = f.numpy()
pawols
  • 406
  • 4
  • 10
-1

Try this:

import tensorflow as tf
#%%
graph = tf.Graph()
with graph.as_default():
  a=tf.Variable(1, name="a")
  b=tf.Variable(2, name="b")
  init=tf.compat.v1.global_variables_initializer()
  f=a+b


with tf.compat.v1.Session(graph = graph) as s:
    s.run(init)
    print(f.eval())

If you want to use TensorFlow V1.X, you need to construct a graph that basically lines up all the operations and the flow of your data. Then you pass that graph to a session and you will run the session.

Here is a good intro I found: https://www.easy-tensorflow.com/tf-tutorials/basics/graph-and-session

Another thing I noticed about your code is that you initialized your variables after you used them to calculate f. This should come before. So I changed that as well. Lastly, you wrote s.run(**int**) while I think you meant s.run(**init**). So I changed that as well.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
MSAPRUN20
  • 1
  • 1