gpt4 book ai didi

Tensorflow:空计算图和垃圾收集

转载 作者:行者123 更新时间:2023-12-04 08:28:34 26 4
gpt4 key购买 nike

1 空图错误

嘿,我正在尝试完全独立地运行多个 tensorflow 图,并且遇到了以下继承问题。

也可以

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])

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

2 - 垃圾收集

我也很想知道如何删除这些不同的图,如果我用 Session().close() 关闭 session 并且它是唯一知道该图的 session ,该图现在会消失并被垃圾收集吗?

最佳答案

问题 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])
(PS:你的代码写的很烂,希望仅供测试)

问题2
图不受相应 session 的影响。
您可以创建一个图形,打开一个 session 并关闭它,图形将保持不变:
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()

关于Tensorflow:空计算图和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38043692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com