from __future__ import print_function
import tensorflow as tf
def example():
g1 = tf.Graph()
with g1.as_default():
# Define operations and tensors in `g`.
c1 = tf.constant(42)
assert c1.graph is g1
g2 = tf.Graph()
with g2.as_default():
# Define operations and tensors in `g`.
c2 = tf.constant(3.14)
assert c2.graph is g2
# MonitoredTrainingSession example
with g1.as_default():
with tf.train.MonitoredTrainingSession() as sess:
print(c1.eval(session=sess))
# Next line raises
# ValueError: Cannot use the given session to evaluate tensor:
# the tensor's graph is different from the session's graph.
try:
print(c2.eval(session=sess))
except ValueError as e:
print(e)
# Session example
with tf.Session(graph=g2) as sess:
print(c2.eval(session=sess))
# Next line raises
# ValueError: Cannot use the given session to evaluate tensor:
# the tensor's graph is different from the session's graph.
try:
print(c1.eval(session=sess))
except ValueError as e:
print(e)
if __name__ == '__main__':
example()
This wrapper is used as a base class for various session wrappers
that provide additional functionality such as monitoring, coordination,
and recovery.
我无法对这些类是如何创建的给出一些见解,但我认为以下几点与如何使用它们有关。
tf.Session
是python TensorFlow API中的低级对象,而, 正如您所说,tf.train.MonitoredTrainingSession
具有许多方便的特性,特别是在大多数常见情况下非常有用。在描述
tf.train.MonitoredTrainingSession
的一些好处之前,让我回答关于会话使用的图的问题。您可以使用上下文管理器指定MonitoredTrainingSession
使用的tf.Graph
:所以,正如您所说,使用
MonitoredTrainingSession
的好处是,这个对象负责但是它也有使代码易于分发的好处,因为它的工作方式也不同,这取决于您是否将正在运行的进程指定为主进程。
例如,您可以运行类似于:
以非分布式方式调用:
或以分布式方式(有关输入的更多信息,请参见distributed doc):
另一方面,使用原始
tf.Session
对象的好处是,您没有tf.train.MonitoredTrainingSession
的额外好处,如果您不打算使用它们,或者希望获得更多的控制权(例如队列是如何启动的),这些好处可能很有用。编辑(根据注释): 对于操作初始化,您必须执行如下操作(cf.official doc:
对于QueueRunner,我将向您介绍official doc,在这里您将找到更完整的示例。
编辑2:
了解
tf.train.MonitoredTrainingSession
如何工作的主要概念是_WrappedSession
类:tf.train.MonitoredTrainingSession
以这种方式工作(截至version 1.1):StopAtStepHook
在这个阶段将只检索global_step
张量。Chief
(或Worker
会话)包装成一个_HookedSession
包装成一个_CoordinatedSession
包装成一个_RecoverableSession
。Chief
/Worker
会话负责运行由Scaffold
提供的初始化操作。chief
会话还负责所有检查点部分:例如,使用Scaffold
中的Saver
从检查点还原。_HookedSession
基本上是用来修饰run
方法的:它在相关的时候调用_call_hook_before_run
和after_run
方法。_CoordinatedSession
构建一个Coordinator
来启动队列运行器并负责关闭它们。_RecoverableSession
将确保在发生tf.errors.AbortedError
时重试。总之,
tf.train.MonitoredTrainingSession
避免了大量的锅炉板代码,同时使用hooks机制易于扩展。相关问题 更多 >
编程相关推荐