Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: empty computational graph & garbage collection

Tags:

tensorflow

1 EMPTY GRAPH ERROR

Hey I am trying to run multiple tensorflow graphs completely separate and am running into the following inheritance problem.

Also does

import tensorflow as tf


class A:

    g = tf.Graph()
    g.as_default()
    s = tf.Session(graph=g)

    x = tf.placeholder(tf.float32)

    __call__ = lambda self,X: self.s.run(self.y, {self.x:X})


class B(A):

    y = 2 * A.x


test = B()
print test([1,1,2])

error

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

2 - GARBAGE COLLECTION

I am also curious to find out about deleting these distinct graphs, if I close the session with Session().close() and it is the only session aware of the graph will this graph now disappear and be garbage collected?

like image 720
user2255757 Avatar asked Jun 26 '16 22:06

user2255757


1 Answers

Question 1

If you want your operations to be added to a specific graph, you need to use with g.as_default() as context:

class A:

    g = tf.Graph()
    with g.as_default():
        x = tf.placeholder(tf.float32)

    s = tf.Session(graph=g)

    __call__ = lambda self,X: self.s.run(self.y, {self.x:X})


class B(A):

    with g.as_default():
        y = 2 * A.x


test = B()
print test([1,1,2])

(PS: your code is really badly written, hope it's just for testing)


Question 2

A graph is not affected by a corresponding session.

You can create a graph, open a session and close it, the graph will remain intact:

g = tf.Graph()
with g.as_default():
    # build graph...
    x = tf.constant(1)

sess = tf.Session(graph=g)
sess.run(x)
sess.close()

# Now we can create a new session with the same graph
sess2 = tf.Session(graph=g)
sess2.run(x)
sess2.close()
like image 145
Olivier Moindrot Avatar answered Nov 02 '22 00:11

Olivier Moindrot