【问题标题】:tensorflow: run model evaluation over multiple checkpointstensorflow:在多个检查点上运行模型评估
【发布时间】:2017-07-20 19:11:59
【问题描述】:

在我当前的项目中,我每 100 个迭代步骤训练一个模型并保存检查点。检查点文件都保存在同一目录中(model.ckpt-100、model.ckpt-200、model.ckpt-300 等)。之后,我想根据所有已保存检查点的验证数据来评估模型,而不仅仅是最新的检查点。

目前我用于恢复检查点文件的代码如下所示:

ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
ckpt_list = saver.last_checkpoints
print(ckpt_list)
if ckpt and ckpt.model_checkpoint_path:
    print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
    saver.restore(sess, ckpt.model_checkpoint_path)
    # extract global_step from it.
    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    print('Succesfully loaded model from %s at step=%s.' %
            (ckpt.model_checkpoint_path, global_step))
else:
    print('No checkpoint file found')
    return

但是,这只会恢复最新保存的检查点文件。那么如何在所有保存的检查点文件上编写一个循环呢?我尝试使用 saver.last_checkpoints 获取检查点文件的列表,但是返回的列表为空。

任何帮助将不胜感激,在此先感谢!

【问题讨论】:

  • 如何准确保存模型?您是自己建立输出文件的名称,还是在调用saver.save(..) 时使用global_step 参数?

标签: python tensorflow


【解决方案1】:

您可以遍历目录中的文件:

import os

dir_path = './' #change that to wherever your files are
ckpt_files = [f for f in os.listdir(dir_path) if os.path.isfile(
    os.path.join(dir_path, f)) and 'ckpt' in f]

for ckpt_file in ckpt_files:
    saver.restore(sess, dir_path + ckpt_file)
    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    print('Succesfully loaded model from %s at step=%s.' %
          (ckpt.model_checkpoint_path, global_step))

    # Do your thing

在上述列表理解中添加更多条件以更具选择性,例如:and 'meta' not in f 等等,具体取决于该目录中的内容和您拥有的保护程序版本

【讨论】:

    【解决方案2】:

    最快的解决方案:

    tensor2tensor 有一个模块utils 和一个脚本avg_checkpoints.py,它将平均权重保存在一个新的检查点中。假设您有一个要平均的检查点列表。您有两种使用方式:

    1. 从命令行

      TRAIN_DIR=path_to_your_model_folder
      FNC_PATH=path_to_tensor2tensor+'/utils/avg.checkpoints.py'
      CKPTS=model.ckpt-10000,model.ckpt-20000,model.ckpt-100000
      
      python3 $FNC_PATH --prefix=$TRAIN_DIR --checkpoints=$CKPTS \ 
          --output_path="${TRAIN_DIR}averaged.ckpt"
      
    2. 来自您自己的代码(使用os.system):

      import os
      os.system(
          "python3 "+FNC_DIR+" --prefix="+TRAIN_DIR+" --checkpoints="+CKPTS+
          " --output_path="+TRAIN_DIR+"averaged.ckpt"
      )
      

    作为指定检查点列表和使用--checkpoints 参数的替代方法,您可以只使用--num_checkpoints=10 来平均最后10 个检查点。

    如果你不想依赖tensor2tensor

    这是一个不依赖于tensor2tensor 的代码 sn-p,但仍然可以平均 可变数量的检查点(与 ted 的答案相反)。假设steps 是应合并的检查点列表(例如[10000, 20000, 30000, 40000])。

    然后:

    # Restore all sessions and save the weight matrices
    values = []
    for step in steps:
        tf.reset_default_graph()
        path = model_path+'/model.ckpt-'+str(step)
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph(path+'.meta')
            saver.restore(sess, path)
            values.append(sess.run(tf.all_variables()))
    
    # Average weights
    variables = tf.all_variables()
    all_assign = []
    for ind, var in enumerate(variables):
        weights = np.concatenate(
            [np.expand_dims(w[ind],axis=0)  for w in values],
            axis=0
        )
        all_assign.append(tf.assign(var, np.mean(weights, axis=0))
    

    然后你可以继续,但你喜欢,例如。保存平均检查点:

    # Now save the new values into a separate checkpoint
    with tf.Session() as sess_test:
        sess_test.run(all_assign)
        saver = tf.train.Saver() 
        saver.save(sess_test, model_path+'/average_'+str(num_checkpoints))
    

    【讨论】:

      【解决方案3】:

      最佳解决方案,请关注link

      我已经用了很长时间了,它很整洁。 您可以根据您喜欢的任何指标保存模型。 它会在恢复模型时删除旧的检查点并加载最佳检查点。

      如果您使用准确度作为指标,则设置 Maximize=True 以根据最大准确度保存模型。 如果您是根据验证损失评估模型,您可以将最大化标志设置为 False 以保存验证损失最小的模型。

      【讨论】:

        猜你喜欢
        • 2020-06-03
        • 2016-10-05
        • 1970-01-01
        • 2016-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多