gpt4 book ai didi

tensorflow - 如何理解sess.as_default()和sess.graph.as_default()?

转载 作者:行者123 更新时间:2023-12-02 09:13:32 25 4
gpt4 key购买 nike

我读了docs of sess.as_default()

N.B. The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a with sess.as_default(): in that thread's function.

我的理解是,如果创建新线程时多了两个 session ,我们必须设置一个 session 来在其中运行 TensorFlow 代码。因此,为此,需要选择一个 session 并调用 as_default()

N.B. Entering a with sess.as_default(): block does not affect the current default graph. If you are using multiple graphs, and sess.graph is different from the value of tf.get_default_graph, you must explicitly enter a with sess.graph.as_default(): block to make sess.graph the default graph.

sess.as_default() block 中,要调用特定的图,必须调用sess.graph.as_default()来运行该图?

最佳答案

tf.Session API 提到图表是在 session 中启动的。下面的代码说明了这一点:

import tensorflow as tf

graph1 = tf.Graph()
graph2 = tf.Graph()

with graph1.as_default() as graph:
a = tf.constant(0, name='a')
graph1_init_op = tf.global_variables_initializer()

with graph2.as_default() as graph:
a = tf.constant(1, name='a')
graph2_init_op = tf.global_variables_initializer()

sess1 = tf.Session(graph=graph1)
sess2 = tf.Session(graph=graph2)
sess1.run(graph1_init_op)
sess2.run(graph2_init_op)

# Both tensor names are a!
print(sess1.run(graph1.get_tensor_by_name('a:0'))) # prints 0
print(sess2.run(graph2.get_tensor_by_name('a:0'))) # prints 1

with sess1.as_default() as sess:
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 0

with sess2.as_default() as sess:
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 1

with graph2.as_default() as g:
with sess1.as_default() as sess:
print(tf.get_default_graph() == graph2) # prints True
print(tf.get_default_session() == sess1) # prints True

# This is the interesting line
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 0
print(sess.run(g.get_tensor_by_name('a:0'))) # fails

print(tf.get_default_graph() == graph2) # prints False
print(tf.get_default_session() == sess1) # prints False

您不需要调用sess.graph.as_default()来运行该图,但您需要在图中获取正确的张量或操作来运行它。上下文允许您使用 tf.get_default_graphtf.get_default_session 获取图表或 session 。

在上面有趣的一行中,默认 session 是 sess1 并且它隐式调用 sess1.graph,这是 sess1 中的图表,这是 graph1,因此它打印 0。

在接下来的行中,它失败了,因为它尝试使用 sess1graph2 中运行操作。

关于tensorflow - 如何理解sess.as_default()和sess.graph.as_default()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093688/

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