【问题标题】:Restore best checkpoint to an estimator tensorflow 2.x将最佳检查点恢复到估计器 tensorflow 2.x
【发布时间】:2023-03-31 15:41:02
【问题描述】:

简而言之,我使用 tensorflow Dataset API 建立了一个数据输入管道。然后,我使用 keras 实现了一个用于分类的 CNN 模型,并将其转换为估计器。我用我的 input_fn 提供了我的估计器训练和评估规范,为训练和评估提供输入数据。作为最后一步,我使用tf.estimator.train_and_evaluate启动了模型训练

def my_input_fn(tfrecords_path):

    dataset = (...)
    return batch_fbanks, batch_labels

def build_model():
    model = tf.keras.models.Sequential()
    model.add(...)
    model.compile(...)

    return model

model = build_model()

run_config=tf.estimator.RunConfig(model_dir,save_summary_steps=100,save_checkpoints_steps=1000)
estimator = tf.keras.estimator.model_to_estimator(model,config=run_config)

def serving_input_receiver_fn():
    inputs = {'Conv1_input': tf.compat.v1.placeholder(shape=[None, 11,120,1], dtype=tf.float32)}
    return tf.estimator.export.ServingInputReceiver(inputs, inputs)

exporter = tf.estimator.BestExporter(serving_input_receiver_fn, name="best_exporter", exports_to_keep=5)

train_spec_dnn = tf.estimator.TrainSpec(input_fn = lambda: my_input_fn(train_data_path),hooks=[hook])
eval_spec_dnn = tf.estimator.EvalSpec(input_fn = lambda: my_eval_input_fn(eval_data_path),exporters=exporter,start_delay_secs=0,throttle_secs=15)

tf.estimator.train_and_evaluate(estimator, train_spec_dnn, eval_spec_dnn)

如上所示,我使用tf.estimator.BestExporter 保存了 5 个最佳检查点。完成训练后,我想重新加载最佳模型并将其转换为估计器以重新评估模型并预测新数据集。但是我的问题是将检查点恢复到估计器。我尝试了几种解决方案,但每次我没有得到估计器对象时,我都需要运行它的 evaluate 和 predict 方法。

只是为了指定更多,每个最佳检查点目录组织如下:

./
  variables/
      variables.data-00000-of-00002
      variables.data-00001-of-00002
      variables.index
  saved_model.pb

所以问题是如何从最佳检查点获取估计器对象,以便我可以使用它来评估我的模型并预测新数据?

注意:我发现一些建议的解决方案依赖于 TensorFlow v1 功能,但由于我使用的是 TF v2,因此无法解决我的问题。

非常感谢,感谢任何帮助。

【问题讨论】:

    标签: keras tensorflow2.0 tensorflow-datasets tensorflow-estimator


    【解决方案1】:

    您可以使用以下从 tf.estimator.BestExporter

    创建的类

    它的作用是,除了保存最佳模型(.pb 文件等)之外,它还会保存 最佳导出模型检查点在不同的文件夹中。

    下面是类:

    import shutil, glob, os
    # import tensorflow.logging as logging
    ## the path where all the checkpoint reside
    BEST_CHECKPOINTS_PATH_FROM = 'PATH TO ALL CHECKPOINT FILES'
    ## the path it will save the best exporter checkpoint files
    BEST_CHECKPOINTS_PATH_TO = 'PATH TO BEST EXPORTER CHECKPOINT FILES TO BE SAVE' 
    
    class BestCheckpointsExporter(tf.estimator.BestExporter):
          def export(self, estimator, export_path, checkpoint_path, eval_result,is_the_final_export):
              if self._best_eval_result is None or \
                        self._compare_fn(self._best_eval_result, eval_result):
                        #print('Exporting a better model ({} instead of {})...'.format(eval_result, self._best_eval_result))
                  for name in glob.glob(checkpoint_path + '.*'):
                        print(name)
                        print(os.path.join(BEST_CHECKPOINTS_PATH_TO, os.path.basename(name)))
                        shutil.copy(name, os.path.join(BEST_CHECKPOINTS_PATH_TO, os.path.basename(name)))
                    # also save the text file used by the estimator api to find the best checkpoint
                  with open(os.path.join(BEST_CHECKPOINTS_PATH_TO, "checkpoint"), 'w') as f:
                        f.write("model_checkpoint_path: \"{}\"".format(os.path.basename(checkpoint_path)))
                  self._best_eval_result = eval_result
              else:
                  print('Keeping the current best model ({} instead of {}).'.format(self._best_eval_result, eval_result))
    

    类的示例用法
    您只需通过调用类替换导出器并传递 serving_input_receiver_fn。

    def serving_input_receiver_fn():
        inputs = {'my_dense_input': tf.compat.v1.placeholder(shape=[None, 4], dtype=tf.float32)}
        return tf.estimator.export.ServingInputReceiver(inputs, inputs)
    
    exporter = BestCheckpointsExporter(serving_input_receiver_fn=serving_input_receiver_fn) 
    
    train_spec_dnn = tf.estimator.TrainSpec(input_fn = input_fn, max_steps=5)
    
    eval_spec_dnn = tf.estimator.EvalSpec(input_fn=input_fn,exporters=exporter,start_delay_secs=0,throttle_secs=15)
    (x, y) =  tf.estimator.train_and_evaluate(keras_estimator, train_spec_dnn, eval_spec_dnn)
    

    此时,它会将最佳导出的模型检查点文件保存在您指定的文件夹中。

    要加载检查点文件,您需要执行以下步骤:
    第 1 步:重建模型实例

    def build_model():
        model = tf.keras.models.Sequential()
        model.add(...)
        model.compile(...)
    
        return model
    
    model = build_model()
    

    第 2 步:使用模型 load_weights API
    参考网址:https://www.tensorflow.org/tutorials/keras/save_and_load

    ck_path = tf.train.latest_checkpoint('PATH TO BEST EXPORTER CHECKPOINT FILES')
    model.load_weights(ck_path)
    
    ## From there you will be able to call the predict & evaluate the functionality of the trained model
    
    ##PREDICT
    prediction = model.predict(x)
    
    ##EVALUATE
    for features_batch, labels_batch in input_fn().take(1):
      model.evaluate(features_batch, labels_batch)
    

    注意:所有这些都是在 google colab 上模拟的。

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2016-09-29
      相关资源
      最近更新 更多