从检查点创建 Estimator 并保存为 SavedModel,无需进一步训练

Create Estimator from checkpoint and save as SavedModel without further training

我从 TF Slim Resnet V2 检查点创建了一个 Estimator 并对其进行了测试以进行预测。我所做的主要事情基本上类似于普通的 Estimator 以及 assign_from_checkpoint_fn:

def model_fn(features, labels, mode, params):
  ...
  slim.assign_from_checkpoint_fn(os.path.join(checkpoint_dir, 'resnet_v2_50.ckpt'), slim.get_model_variables('resnet_v2')
  ...
  if mode == tf.estimator.ModeKeys.PREDICT:
    predictions = {
      'class_ids': predicted_classes[:, tf.newaxis],
      'probabilities': tf.nn.softmax(logits),
      'logits': logits,
    }
  return tf.estimator.EstimatorSpec(mode, predictions=predictions)

为了将估算器导出为 SavedModel,我制作了一个 serving_input_fn 如下:

def image_preprocess(image_buffer):
    image = tf.image.decode_jpeg(image_buffer, channels=3)
    image_preprocessing_fn = preprocessing_factory.get_preprocessing('inception', is_training=False)
    image = image_preprocessing_fn(image, FLAGS.image_size, FLAGS.image_size)
    return image

def serving_input_fn():
    input_ph = tf.placeholder(tf.string, shape=[None], name='image_binary')
    image_tensors = image_preprocess(input_ph)
    return tf.estimator.export.ServingInputReceiver(image_tensors, input_ph)

在主函数中,我使用 export_saved_model 尝试将 Estimator 导出为 SavedModel 格式:

def main():
    ...
    classifier = tf.estimator.Estimator(model_fn=model_fn)
    classifier.export_saved_model(dir_path, serving_input_fn)

但是,当我尝试 运行 代码时,它显示“无法在 /tmp/tmpn3spty2z 找到经过训练的模型”。据我了解,此 export_saved_model 试图找到经过训练的 Estimator 模型以导出到 SavedModel。但是,我想知道是否有任何方法可以将预训练的检查点恢复到 Estimator 并将 Estimator 导出到 SavedModel 而无需任何进一步的训练?

我的问题已经解决了。要将 TF 1.14 的 TF Slim Resnet checkpoint 导出到 SavedModel,warm start 可以与 export_savedmodel 一起使用,如下所示:

config = tf.estimator.RunConfig(save_summary_steps = None, save_checkpoints_secs = None)
warm_start = tf.estimator.WarmStartSettings(checkpoint_dir, checkpoint_name)
classifier = tf.estimator.Estimator(model_fn=model_fn, warm_start_from = warm_start, config = config)
classifier.export_savedmodel(export_dir_base = FLAGS.output_dir, serving_input_receiver_fn =  serving_input_fn)