使用在GCP中训练的模型进行推理?

时间:2020-05-20 21:15:13

标签: tensorflow google-cloud-platform image-segmentation tpu gcp-ai-platform-training

我是这个主题的新手,所以请多多包涵。

我一直在按照本教程训练自己的细分模型:ShapeMask on GCP 培训过程成功完成,我得到以下输出:

enter image description here

现在,我正尝试在Google提供的colab笔记本中使用此工具:Colab

但是,我无法为其提供训练有素的模型。我需要在该笔记本中保存一个模型,但是运气不佳,无法将输出转换为保存的模型。我在VM和TPU上使用的是TF版本1.15.2。

在训练和推论之间,我缺少一些步骤。但是我不知道它们是什么。非常感谢您的帮助。谢谢!

到目前为止,我已经尝试使用this将文件转换为保存的模型。并通读this,但不明白如何使用它。

1 个答案:

答案 0 :(得分:0)

因此,我能够从检查点保存模型。在colab笔记本上使用以下代码段。我不得不在colab笔记本中启用TPU(运行时>更改运行时类型> TPU),可能是因为我在TPU上进行过尝试(否则会引发错误)。

import os
import tensorflow.compat.v1 as tf
from google.protobuf import text_format
from tensorflow import keras

trained_checkpoint_prefix ='<GC storage bucket path>/model.ckpt-1000'
export_dir = '<GC storage bucket path>'
tpu_address = 'grpc://' + os.environ['COLAB_TPU_ADDR']

graph = tf.Graph()
with tf.Session(target=tpu_address,graph=graph) as sess:
    # Reste from checkpoint
    loader = tf.train.import_meta_graph(trained_checkpoint_prefix + '.meta', clear_devices=True)
    loader.restore(sess, trained_checkpoint_prefix)
    # Export checkpoint to SavedModel
    builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(export_dir)
    builder.add_meta_graph_and_variables(sess, [tf.saved_model.TRAINING, tf.saved_model.SERVING], strip_default_attrs=True)
    builder.save()

现在,我说这种情况是因为此保存的模型插入到Colab教程noteook中不起作用。它在单元格6中成功读取了模型,但推理部分出现错误。就在这里:

num_detections, detection_boxes, detection_classes, detection_scores, detection_masks, detection_outer_boxes, image_info = session.run(
['NumDetections:0', 'DetectionBoxes:0', 'DetectionClasses:0', 'DetectionScores:0', 'DetectionMasks:0', 'DetectionOuterBoxes:0', 'ImageInfo:0'],
feed_dict={'Placeholder:0': np_image_string})

该过程以以下错误结束:

KeyError: "The name 'Placeholder:0' refers to a Tensor which does not exist. The operation, 'Placeholder', does not exist in the graph." 

它也找不到所有其他变量名。我不确定是什么原因导致的,一旦我这样做,便会更新答案!

EDIT1:

我使用以下readme解决了问题。

首先,我使用TF 2.2和TPU repo的主分支而不是shapemask分支。然后按照原始教程中的确切步骤进行培训。并使用以下命令导出保存的模型:

python ~/tpu/models/official/detection/export_saved_model.py \
--export_dir="${EXPORT_DIR?}" \
--checkpoint_path="${CHECKPOINT_PATH?}" \
--params_override="${PARAMS_OVERRIDE?}" \
--batch_size=${BATCH_SIZE?} \
--input_type="${INPUT_TYPE?}" \
--input_name="${INPUT_NAME?}" \

此处应传递训练期间创建的params.yaml文件中的params覆盖标志。批处理大小设置为1,一次只能处理一张图像。在自述文件中可以找到更多详细信息。

注意:我必须注释掉以下行才能执行:

import segmentation from serving

它导出了模型,并在笔记本中进行了一些细微调整,就可以在colab笔记本中加载和使用它。

相关问题