Tensorflow:空的计算图和垃圾回收

use*_*757 4 tensorflow

1空图错误

嗨,我正在尝试完全分开运行多个张量流图,并遇到以下继承问题。

还可以

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])
Run Code Online (Sandbox Code Playgroud)

错误

RuntimeError: The Session graph is empty.  Add operations to the graph before calling run()
Run Code Online (Sandbox Code Playgroud)

2-垃圾收集

我也很好奇要删除这些不同的图,如果我使用Session()。close()关闭会话,并且这是唯一知道该图的会话,该图现在会消失并被垃圾回收吗?

Oli*_*rot 8

问题1

如果要将操作添加到特定图形,则需要with g.as_default()用作上下文:

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])
Run Code Online (Sandbox Code Playgroud)

(PS:您的代码确实写得不好,希望只是为了测试)


问题2

图不受相应会话的影响。

您可以创建一个图形,打开一个会话并关闭它,该图形将保持不变:

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()
Run Code Online (Sandbox Code Playgroud)

  • 感谢m8,我想那还真是...回到theano! (2认同)