Skip to main content
 首页 » 编程设计

python之`sess.graph` 和 `tf.get_default_graph()` 之间的区别

2024年10月01日6soundcode

sess.graph 和 tf.get_default_graph() 在 tensorboard 中给出相同的结果。根据手册,我不太清楚它们之间有什么区别。有人可以帮忙解释一下区别吗? anyboby 能否提供一个 sess.graph 和 tf.get_default_graph() 不能互换使用的示例?

#!/usr/bin/env python 
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: 
 
import tensorflow as tf 
import sys 
 
x = tf.Variable(1.0) 
with tf.name_scope('ns_loss'): 
    loss = tf.square(x) 
with tf.name_scope('ns_adam'): 
    train_op = tf.train.AdamOptimizer().minimize(loss) 
 
init = tf.global_variables_initializer() 
 
tf.summary.scalar('scalar_loss', loss) 
merged_summary_op = tf.summary.merge_all() 
 
with tf.Session() as sess: 
    sess.run(init) 
    summary_writer = tf.summary.FileWriter(logdir=sys.argv[1]) 
    summary_writer.add_graph(graph=tf.get_default_graph()) 
    #summary_writer.add_graph(graph=sess.graph) 
 
    for i in xrange(100): 
        sess.run(train_op) 
        summary_writer.add_summary( 
                summary = sess.run(merged_summary_op) 
                , global_step = i 
                ) 

请您参考如下方法:

tf.get_default_graph()始终返回当前计算图。例如,它是甚至在 session 开始之前就定义了 x 和 loss 节点的图。

当您使用 tf.Session() 创建 session 时您可以选择指定要使用的非默认图形。在您的示例中,未指定:

If no graph argument is specified when constructing the session, the default graph will be launched in the session.

在一个脚本中包含多个图表是正常的,但也有可能,例如,当从磁盘恢复图表时。

另请注意,在 session 完成后,默认图仍然存在,因此它们的生命周期不同。