首页 > 解决方案 > 如何更改 retrain.py 以获取 b64 图像

问题描述

现在,我正在使用 tensorflow 中的默认 retrain.py 来训练图像分类模型。但是当我在 google ai 平台上提供模型并尝试调用 api 时,我收到一个错误,说图像太大,因为它是一个 float32 数组。我认为最好的办法是更改 retrain.py 以接收 b64 图像而不是 float32 数组,但我不知道该怎么做。有什么建议么?

任何帮助表示赞赏!谢谢!

更新

def export_model(module_spec, class_count, saved_model_dir):
 sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count)

 image = tf.placeholder(shape=[None], dtype=tf.string)
 export_dir = "/tmp/save/"

 inputs = {'image_bytes': image}
 with sess.graph.as_default() as graph:
    tf.saved_model.simple_save(sess, export_dir, inputs, {'prediction': graph.get_tensor_by_name('final_result:0')})

这就是我已经更新了我的代码,但它仍然不起作用

标签: tensorflow

解决方案


看看这篇文章,它包含你需要的信息。如果没有,请回复,我会帮助您准备一些代码,不过您可能需要 url 安全 b64 变体。

编辑

您的代码有点混乱,我认为输入尚未连接到您的图表,您是否使用 tf.summary.FileWriter('output folder', sess.graph) 查看了图表?

我将逐步尝试解释您如何在模型前面构建一些层,并通过一些示例,此代码不应在 retrain.py 中,并且可以在您训练模型后运行。

1)加载你的tensorflow模型,如果它是用savedModelBuilder构建的,或者你可以像这样简单的保存东西:

def loader(path):
    with tf.Session(graph=tf.Graph()) as sess:
        tf.saved_model.loader.load(sess, [tag_constants.TRAINING], path)
        return tf.get_default_graph().as_graph_def()

可以使用saved_model_cli 工具检查 tagconstants ,在您的情况下,这可能必须为空 []。

2)添加你需要的层/张量,你需要接受一个字节字符串的东西,或者在这种情况下是base 64,解码它并将其转换为3D图像:

image_str_tensor = tf.placeholder(dtype=tf.string, shape=(None,), name='input_image_bytes')
input_image = tf.decode_base64(image_str_tensor)          
decoder = tf.image.decode_jpeg(input_image[0], channels=3)

如果您从 retrain.py 中获得其他张量,例如转换为 float、dim_expanding 和 reshaping,应该已经在图中。

3)通过将它们输入到图表中来将它们实施到您的图表中。

graph_def_inception = loader('path to your saved model')
output_prediction, = tf.import_graph_def(graph_def_inception, input_map={"DecodeJpeg:0": decoder}, return_elements=['final_result:0'], name="")

4)创建一个保存的模型并检查一切是否如你所愿!

builder = tf.saved_model.builder.SavedModelBuilder('output/model/path')

with tf.Session() as sess:
    tf.summary.FileWriter('output/graph_log/files', sess.graph)

    input_tensor_info = tf.saved_model.utils.build_tensor_info(input_image)
    output_tensor_info = tf.saved_model.utils.build_tensor_info(output_prediction)
    signature = tf.saved_model.signature_def_utils.build_signature_def(
        inputs={'input_image': input_tensor_info},
        outputs={'output_prediction': output_tensor_info},
        method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)

    # save as SavedModel
    builder.add_meta_graph_and_variables(sess,
                                         [tf.saved_model.tag_constants.SERVING],
                                         signature_def_map={'serving_default': signature})
    builder.save()

5)如果您遇到错误,请尝试使用 tensorboard 进行调试

tensorboard --logdir=output/graph_log/files

我希望我能帮上忙,这段代码在第一次尝试时不会起作用,你需要对一些部分感到困惑。如果你真的不能成功,那么你应该分享模型,如果我有时间的话,也许我可以做到并与你分享代码。


推荐阅读