因为你能够做一个
with tf.Session() as sess:
# Run stuff here with sess.run()
但也
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
sess.run(x)
我想知道是否有可能在图形创建中做类似的事情,例如:
a_graph = tf.Graph()
x = tf.placeholder(dtype=tf.float32, name='test')
a_graph.add(x)
向图形添加节点/操作的传统方法当然是......
with a_graph.as_default():
x = tf.placeholder(dtype=tf.float32, name='test')
我无法在文档中阅读有关此的任何内容......dir(a_graph)
也没有向我展示一个简单的.add()
方法。我唯一能想到的就是向集合添加一些操作......但我不知道该怎么做。
始终可以手动进入/退出上下文管理器:
# Enter the `graph` context
cm = graph.as_default()
cm.__enter__()
print(tf.get_default_graph() == graph) # True
# All nodes are added to the `graph` now
x = tf.placeholder(dtype=tf.float32, name='x')
y = tf.placeholder(dtype=tf.float32, name='y')
# Exit the context
cm.__exit__(None, None, None)
但是with
声明版本对我来说看起来要好得多。