Danial
Danial

Reputation: 612

tensorflow - session graph empty

import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)

with tf.compat.v1.Session() as sess:
  output = sess.run(result)
  print(output)

As I am new in machine learning,I was trying to implement this code using tensorflow, but I am getting the following error:

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

How can I solve this problem ?

From this thread I changed my code to:

import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)

g = tf.Graph() 
with g.as_default():   
    assert result.graph is g

sess = tf.compat.v1.Session(graph=g)
with tf.compat.v1.Session() as sess:
    output = sess.run(result)
    print(output)

It also gives me the following error :

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

Upvotes: 2

Views: 993

Answers (1)

javidcf
javidcf

Reputation: 59691

You seem to be using TF 2.0, which enables eager execution by default. If that is the case, you should normally not be using graphs or sessions, as you can simply do:

import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)
tf.print(result)  # or print(result.numpy())
# [5 12 21 32]

If you still want to use graphs for some reason, you need to do you operations within the context of a default graph:

import tensorflow as tf

with tf.compat.v1.Graph().as_default():
    x1 = tf.constant([1,2,3,4])
    x2 = tf.constant([5,6,7,8])
    result = tf.multiply(x1, x2)
    with tf.compat.v1.Session() as sess:
        output = sess.run(result)
        print(output)
        # [ 5 12 21 32]

Upvotes: 1

Related Questions