Tensorflow Estimator - warm_start_from和model_dir

时间:2018-04-15 19:58:48

标签: tensorflow tensorflow-estimator

tf.estimatorwarm_start_from model_dir一起使用时,warm_start_from目录和model_dir目录都包含有效的检查点,检查站将实际恢复?

为了给出一些上下文,我的估算代码看起来像

est = tf.estimator.Estimator(
    model_fn=model_fn,
    model_dir=model_dir,
    warm_start_from=warm_start_dir)

for epoch in range(num_epochs):
    est.train(input_fn=train_input_fn)
    est.evaluate(input_fn=eval_input_fn)

(输入函数使用一次性迭代器。)

所以在第一次迭代中,当model_dir为空时,我希望加载热启动检查点,但是在下一个时代,我希望从中获得中间微调检查点要加载的model_dir中的最后一次迭代。但至少从日志中可以看出warm_start_dir仍在加载。

我可能会在下一次迭代中覆盖我的估算器,但我想知道它是不是应该在估算器中构建一些如何。

1 个答案:

答案 0 :(得分:2)

我遇到了类似的问题,我通过提供一个在会话开始时运行的初始化钩子并使用tf.estimator.train_and_evaluate来解决了这一问题(尽管我不能相信整个解决方案,正如我在其他地方看到的其他目的类似的东西)

class InitHook(tf.train.SessionRunHook):
    """initializes model from a checkpoint_path
    args:
        modelPath: full path to checkpoint
    """
    def __init__(self, checkpoint_dir):
        self.modelPath = checkpoint_dir
        self.initialized = False

    def begin(self):
        """
        Restore encoder parameters if a pre-trained encoder model is available and we haven't trained previously
        """
        if not self.initialized:
            log = logging.getLogger('tensorflow')
            checkpoint = tf.train.latest_checkpoint(self.modelPath)
            if checkpoint is None:
                log.info('No pre-trained model is available, training from scratch.')
            else:
                log.info('Pre-trained model {0} found in {1} - warmstarting.'.format(checkpoint, self.modelPath))
                tf.train.warm_start(checkpoint)
            self.initialized = True

然后,进行培训:

initHook = InitHook(checkpoint_dir = warm_start_dir)
trainSpec = tf.estimator.TrainSpec(
    input_fn = train_input_fn,
    max_steps = N_STEPS, 
    hooks = [initHook]
)
evalSpec = tf.estimator.EvalSpec(
    input_fn = eval_input_fn,
    steps = None,
    name = 'eval',
    throttle_secs = 3600
)
tf.estimator.train_and_evaluate(estimator, trainSpec, evalSpec)

此操作从头开始运行一次,以初始化warm_start_dir中的变量。稍后,当估算器model_dir中有新的检查点时,它将继续从那里开始warm_start。