【问题标题】:Should tf.Session() fall inside the context of tf.Graph()?tf.Session() 是否应该在 tf.Graph() 的上下文中?
【发布时间】:2018-01-06 06:43:18
【问题描述】:

我经常在 Tensorflow 代码中看到以下模式,但通常忽略它们会获得更好的性能。

with tf.Graph().as_default():

    # Build graph here ...
    loss, train_op = ...

    with tf.Session() as sess: # OR: with sv.managed_sess() as sess, etc.

        # Run training steps here ...
        sess.run(train_op)

但我更喜欢先定义我的图表,然后按如下方式单独运行会话(尤其是在 Jupyter 笔记本中)。

在一个单元格中:

with tf.Graph().as_default():

    # Build graph here ...
    loss, train_op = ...

在另一个单元格中:

with tf.Session() as sess: # OR: with sv.managed_sess() as sess, etc.

    # Run training steps here ...
    sess.run(train_op)

我注意到在第一种方法中创建图表需要时间。有时我使用多个图表,而第二种方法是我唯一的选择。为什么一种方法会比另一种更好?

【问题讨论】:

  • (如果不清楚,主要区别是with块的缩进)

标签: python python-3.x machine-learning tensorflow


【解决方案1】:

不要使用第二个版本。我真的很惊讶它可以像你一样工作。这个

import tensorflow as tf

with tf.Graph().as_default():
  x = tf.zeros(())

with tf.Session() as sess:
  sess.run(x)

在我的 tensorflow 1.2.1 上失败了

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

如果您使用的是单个图表,您实际上可以安全地删除 with tf.Graph().as_default(): 行,因为默认情况下 已经 是默认图表。您不需要额外创建一个。所以这个

import tensorflow as tf

x = tf.zeros(())

with tf.Session() as sess:
  sess.run(x)

完全合法,在我看来更可取。

现在,如果您使用多个图表...好吧,通常您最好使用单个图表。您不会从使用多个图表中获得任何好处。您应该只在必要时使用它们。

【讨论】:

  • 为了清楚起见,我省略了细节。如果您在创建 tf.Session 时指定哪个图表,或者将 tf.train.Supervisor 与托管会话一起使用(如我的问题所示),这两个示例都可以正常工作。
  • @awallllllll 好的,有道理。我认为这不会影响我回答的主要信息。
【解决方案2】:

在常规 python 脚本中,这两种方法没有区别。但是,如果您使用笔记本并单独执行单元格,那么显然不重新创建图表比从头开始创建图表要快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2010-10-07
    • 2019-06-18
    • 2016-04-14
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多