当将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仍在加载。

我可能会在下一次迭代中覆盖我的估算器,但我想知道是否应该以某种方式在估算器中构建它。

最佳答案

我有一个类似的问题,我通过提供一个在 session 开始时运行的初始化 Hook 并使用了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。

关于Tensorflow估算器-warm_start_from和model_dir,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49846207/

10-13 09:11