张量流将预测作为 b64 输出顶部结果

2024-03-20

我有一个 Keras 模型,我将其转换为张量流服务模型。我可以成功地将预训练的 keras 模型转换为采用 b64 输入、预处理该输入并将其提供给我的模型。我的问题是我不知道如何获取我得到的预测数据(这是巨大的)并且只导出最高结果。我正在进行图像分割,因此我的输出预测形状为 (?, 473, 473, 3),我想获得最佳结果并以 b64 编码格式返回。我目前所拥有的只是返回整个预测:

sess = K.get_session()
g = sess.graph
g_def = graph_util.convert_variables_to_constants(sess, 
                      g.as_graph_def(),
                      [model.output.name.replace(':0','')])

with tf.Graph().as_default() as g_input:
    input_b64 = tf.placeholder(shape=(1,),
                               dtype=tf.string,
                               name='b64')
    tf.logging.info('input b64 {}'.format(input_b64))

    image = tf.image.decode_image(input_b64[0])#input_bytes)
    image_f = tf.image.convert_image_dtype(image, dtype=tf.float16)
    input_image = tf.expand_dims(image_f, 0)
    image_r = tf.image.resize_bilinear(input_image, [HEIGHT, WIDTH], align_corners=False)
    input_data = preprocess_image(image_r)
    output = tf.identity(input_data, name='input_image')




# Convert to GraphDef
g_input_def = g_input.as_graph_def()


with tf.Graph().as_default() as g_combined:
    x = tf.placeholder(tf.string, name="b64")

    im, = tf.import_graph_def(g_input_def,
                              input_map={'b64:0': x},
                              return_elements=["input_image:0"])

    pred, = tf.import_graph_def(g_def,
             input_map={model.input.name: im},
             return_elements=[model.output.name])

    with tf.Session() as session:
        inputs = {"image_bytes": tf.saved_model.utils.build_tensor_info(x)}
        outputs = {"output_bytes":tf.saved_model.utils.build_tensor_info(pred)}
        signature =tf.saved_model.signature_def_utils.build_signature_def(
                inputs=inputs,
                outputs=outputs,
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
            )


        """Convert the Keras HDF5 model into TensorFlow SavedModel."""

        if os.path.exists(export_path):
            shutil.rmtree(export_path)
        legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
        builder = saved_model_builder.SavedModelBuilder(export_path)
        builder.add_meta_graph_and_variables(
            sess=session,
            tags=[tag_constants.SERVING],
            signature_def_map={ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature },
        )
        builder.save()

我从我的工作中汲取了很多东西https://medium.com/google-cloud/serverless-transfer-learning-with-cloud-ml-engine-and-keras-335435f31e15 https://medium.com/google-cloud/serverless-transfer-learning-with-cloud-ml-engine-and-keras-335435f31e15以供参考。谢谢!


发布我自己的解决方案,以防其他人遇到这个问题。基本上,您只需执行输入函数的反函数即可。

def postprocess_image(img, in_shape):
    class_image = tf.argmax(img, axis=2)
    colored_class_image = utils.class_image_to_image_tensor(class_image, [HEIGHT,WIDTH])

    image_expand = tf.expand_dims(colored_class_image, 0)
    image_r = tf.image.resize_bilinear(image_expand, in_shape, align_corners=False)
    casted_data = tf.bitcast(tf.cast(image_r[0], tf.int8), tf.uint8)

    out_image = tf.image.encode_png(casted_data)

    return out_image

sess = K.get_session()
g = sess.graph
g_def = graph_util.convert_variables_to_constants(sess, 
                      g.as_graph_def(),
                      [model.output.name.replace(':0','')])


with tf.Graph().as_default() as g_input:
    input_b64 = tf.placeholder(shape=(1,),
                               dtype=tf.string,
                               name='b64')
    tf.logging.info('input b64 {}'.format(input_b64))

    image = tf.image.decode_image(input_b64[0])
    image_f = tf.image.convert_image_dtype(image, dtype=tf.uint8)
    input_image = tf.expand_dims(image_f, 0)

    image_r = tf.image.resize_bilinear(input_image, [HEIGHT, WIDTH], align_corners=False)
    input_data = preprocess_image(image_r[0])
    output = tf.identity(input_data, name='input_image')


with tf.Graph().as_default() as g_output:
    first = tf.placeholder(shape=[1,473,473,150],
                               dtype=tf.float32,
                               name='activation_58/div')
    i_shape = tf.placeholder(dtype=tf.int32, shape=[2], name='in_shape')


    post_image = postprocess_image(first[0], i_shape)

    output_data = tf.identity(post_image, name='out')


g_input_def = g_input.as_graph_def()
g_output_def = g_output.as_graph_def()

with tf.Graph().as_default() as g_combined:
    x = tf.placeholder(tf.string, name="b64")
    in_shape = tf.placeholder(tf.int32, shape=[1,2],name="original_shape")

    im, = tf.import_graph_def(g_input_def,
                              input_map={'b64:0': x},
                              return_elements=["input_image:0"])

    pred, = tf.import_graph_def(g_def,
         input_map={model.input.name: im},
         return_elements=[model.output.name])



    y, = tf.import_graph_def(g_output_def,
             input_map={model.output.name: pred,
             'in_shape:0':in_shape[0]},
             return_elements=["out:0"])

    with tf.Session() as session:
        inputs = {"image_bytes": tf.saved_model.utils.build_tensor_info(x),
                "original_shape":tf.saved_model.utils.build_tensor_info(in_shape)}
        outputs = {"output_bytes":tf.saved_model.utils.build_tensor_info(y)}
        signature =tf.saved_model.signature_def_utils.build_signature_def(
                inputs=inputs,
                outputs=outputs,
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
            )


        """Convert the Keras HDF5 model into TensorFlow SavedModel."""

        if os.path.exists(export_path):
            shutil.rmtree(export_path)
        legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
        builder = saved_model_builder.SavedModelBuilder(export_path)
        builder.add_meta_graph_and_variables(
            sess=session,
            tags=[tag_constants.SERVING],
            signature_def_map={ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature },
        )
        builder.save()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

张量流将预测作为 b64 输出顶部结果 的相关文章

随机推荐

  • Scala Futures 如何与 flatMap 链接在一起?

    我正在 Scala 中首次使用 Futures 并且正在研究使用 flatMap 组合器的示例 我一直在关注这个讨论 http docs scala lang org overviews core futures html http doc
  • 当构建系统已引用 System.Core 时,添加对 System.Core 的引用

    即使项目已生成 Visual Studio Intellisense 也无法识别动态关键字 我尝试添加对System Core来解决问题 我收到此错误 无法添加对 System Core 的引用 该组件是 已经被构建系统自动引用 我注意到我
  • 从 Eclipse 和命令行运行时,BufferedImage 字节具有不同的字节顺序

    我试图转换一个BufferedImage s byte 从 32 位 RGBA 到 24 位 RGB 根据这个答案 https stackoverflow com a 9470843 2581401最快的方式获得byte 从图像中可以看出
  • AWS - 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头

    我对 AWS 还很陌生 所以请耐心等待 我目前正在制作一个具有上传照片功能的网络应用程序 我想将这些照片保存在 S3 存储桶中 并将对它们的引用保存在我的数据库中 我目前正在遵循本指南 http docs aws amazon com sd
  • 生成所有可能的字符串组合

    我正在尝试生成字符串的所有可能组合 例如对于以下列表 a1q5z H9 b1q5z H9 c1q5z H9 d1q5z H9 a2q5z H9 等 我不想做很多嵌套循环 而是想用 MODULO 尝试一些聪明的东西 但碰壁了 这是我想出的 J
  • NHibernate Session.SetReadOnly

    我面临着其他人已经在 SO 上发布的同样问题 在从数据库读取对象时 NHibernate 会更新所有对象 因为数据库中一个字段的值不正确 详细来说 新添加的日期列在所有行中都包含 1 1 0001 因此在映射时 NHibernate 会替换
  • jQuery URL 分割和抓取

    所以我有一个 URL 并且我知道如何从 URL 获取 GET 但我的 URL 是http www example com edit 2695 有没有办法抓取网址并在之后吐出部分 我想要编辑和 ID 您可以使用此代码 var url http
  • Django 时间问题

    我在 django 中的应用程序需要告诉用户操作发生的时间 除了询问用户他 她所在的时区之外 我是否可以在客户端生成时间 在我的脑海中 是否有一个与时区无关的时间的特定表示 unix时间 然后我可以简单地将其粘贴到html中并让客户端 浏览
  • 如何为该月中的几天提供后缀?

    我需要一个函数在显示 等文本时返回几天的后缀th in Wednesday June 5th 2008 它只需要处理数字 1 到 31 不需要错误检查 和英语 这是一个也适用于更大数字的替代方案 static const char dayS
  • R - 从 URL/HTML 对象/HTML 响应写入 HTML 文件

    我想使用 R 中的 URL 保存 HTML 文件 我尝试在使用后保存响应对象GET and read html的功能httr and rvest分别打包到网站的 URL 上 我想保存 的 HTML 但这并不能保存网站的实际内容 url ht
  • 带有 async/await 的 try/catch 块

    我正在深入研究节点 7async await功能并不断绊倒这样的代码 function getQuote let quote Lorem ipsum dolor sit amet consectetur adipiscing elit la
  • 是否有获取最新 Microsoft Edge 版本号的链接?

    我正在寻找一个链接来获取 Microsoft Edge 的最新驱动程序版本号 类似于 Google Chrome 的链接 https chromedriver storage googleapis com LATEST RELEASE ht
  • Swift 3:在 collectionView 中缓存图像

    我目前正在开发我的应用程序 将其更新为与 Swift 3 兼容 但还剩下一个问题 以前 我的图像缓存工作得很好 但自从更新后UIImageView获取图像时不会填充 s 这是代码 在 cellForItemAt 功能 if let img
  • 资源未发现异常?

    我从 android 市场收到崩溃报告 android content res Resources NotFoundException Resource ID 0x 我每周收到大约 17 个这样的东西 它指出我的代码中的以下内容 conte
  • 如何将 JDK GregorianCalendar 对象日期与 Joda 一起使用

    我正在尝试使用 Joda 库 因为使用 Java 本机方法计算周期是一件令人头疼的事情 而且我所有的尝试都给出了不精确的结果 我看过这个样本 int n Days daysBetween start toLocalDate end toLo
  • 如何使用外部vue npm组件

    我是 Vue js 的新手 目前正在尝试在现有解决方案中使用它 我不可能使用 vue 文件 它是一个独立的系统 不使用 webpack 我需要本地文件才能使其正常工作 在下面的例子中 我在线使用了 js 我想使用这个日期选择器 https
  • 在 RAFT 中,是否有可能对某个日志条目达成多数共识,但该条目尚未提交?

    考虑一下官方的这个模拟筏网页 https raft github io Why is term 2 index 1尽管没有承诺S2 leader S3 and S4同意日志吗 我运行了几分钟以确保所有通信均已完成 奇怪的是 如果我再添加一个
  • 内容安全策略:“img-src'self'数据:”

    我有一个应用程序 用户可以在其中复制图像 URL 将其粘贴到输入中 然后图像将加载到框中 但我的应用程序不断触发此消息 拒绝加载图像 LOREM IPSUM URL 因为它违反了以下内容安全策略指令 img src self data 这是
  • Autohotkey 错误的击键发送到控制台

    我正在尝试理解这个错误并寻找解决方法 使用这个脚本 NoEnv SingleInstance force SendMode Input Alt t to send keystrokes t Send It send the correct
  • 张量流将预测作为 b64 输出顶部结果

    我有一个 Keras 模型 我将其转换为张量流服务模型 我可以成功地将预训练的 keras 模型转换为采用 b64 输入 预处理该输入并将其提供给我的模型 我的问题是我不知道如何获取我得到的预测数据 这是巨大的 并且只导出最高结果 我正在进