python - tensorflow 2.0 : Add image preprocessing step in a saved model

标签 python tensorflow keras tensorflow-serving tensorflow2.0

我是 TF 和 GCP 部署方面的新手。非常感谢您的帮助!

目前,我正在尝试使用 TensorFlow Serving 在 Google Cloud Platform(GCP) 上部署我的 Mnist 手写 Flask 应用程序。我已在 TF 服务上部署了我的模型,并使用自定义 MySimpleScaler 类来预处理图像并调整图像大小,然后再将其输入到我的模型中。我的问题是,是否有办法在我的保存模型中添加预处理和调整大小类,以便我的 Flask 应用程序没有任何 tensorflow 依赖项。原因是 TF 库对于应用程序引擎来说太大。

我的应用程序的流程如下:

1) 我的 Flask 应用程序部署在应用程序引擎上。它有一个 MySimpleScaler 类来调整从 Canvas 输入的图像大小。我允许用户从前端的 Canvas 上绘制 --> 使用 jquery 获取数据 --> 使用 parse_image 函数将其写入为 output.jpg --> 从本地驱动器读取 output.jpg 并提供给它到 MySimpleScaler 进行预处理

2) 我的模型使用 TF 服务部署在 AI 平台上。我在步骤 1 中使用 MysimpleScaler 的输出发送预测请求。然后将预测值推送到 Flask 后端,然后使用 Jinja 将其推送到前端

这是我用来获取和预处理数据的两个函数:

def parse_image(imgData):
    # imgData fetch img from canvas using request.get_data()
    imgstr = re.search(b"base64,(.*)", imgData).group(1)
    img_decode = base64.decodebytes(imgstr)
    with open("output.jpg", "wb") as file:
        file.write(img_decode)
    return img_decode
class MySimpleScaler(object):

    def preprocess_img(self, img_decode):
        # img_decode from parse_image
        img_raw = img_decode
        image = tf.image.decode_jpeg(img_raw, channels=1)
        image = tf.image.resize(image, [28, 28])
        image = (255 - image) / 255.0  # normalize to [0,1] range
        image = tf.reshape(image, (1, 28, 28, 1))

        return image

TL;DR:我想在将 preprocess_img 函数部署到 TF 服务之前将其添加为保存模型中的层之一。 非常感谢您的参与!

最佳答案

如果您同意batch_size=1,那么在图表中添加预处理函数应该很简单,这就是我的做法,

代码:

import tensorflow as tf
import numpy as np

print('TensorFlow:',tf.__version__)

def preprocess_single_image(image_bytes, h=299, w=299):
    image = tf.image.decode_jpeg(image_bytes[0], channels=3)
    image = tf.image.resize(image, size=[h, w])
    image = (image - 127.5) / 127.5
    image = tf.expand_dims(image, axis=0)
    return image

image_bytes = tf.keras.Input(shape=[], batch_size=1, name='image_bytes', dtype=tf.string)
preprocessed_image = preprocess_single_image(image_bytes)
model = tf.keras.applications.Xception(weights='imagenet')
predictions = model(preprocessed_image)
new_model = tf.keras.Model(image_bytes, predictions)
new_model.save('export/1', save_format='tf')
print('Model Input Shape:', new_model.input_shape)

### !wget -q -O "cat.jpg" "https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?cs=srgb&dl=adorable-animal-blur-cat-617278.jpg&fm=jpg"
loaded_model = tf.saved_model.load('export/1')
cat_bytes = tf.expand_dims(tf.io.read_file('cat.jpg'), axis=0)
preds = loaded_model(cat_bytes).numpy()
print(tf.keras.applications.xception.decode_predictions(preds, top=3)[0])

输出:

TensorFlow: 2.0.0
WARNING:tensorflow:From /tensorflow-2.0.0/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1781: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
INFO:tensorflow:Assets written to: export/1/assets

Model Input Shape: (1,)
[('n02123045', 'tabby', 0.5762127), ('n02123159', 'tiger_cat', 0.24783427), ('n02124075', 'Egyptian_cat', 0.09435685)]

PS:如果您想扩展它以支持,您可以使用tf.map_fn batch_size > 1

关于python - tensorflow 2.0 : Add image preprocessing step in a saved model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59344187/

相关文章:

python - 如何构建带有 @> 运算符过滤器的 sqlalchemy 查询?

python - 有什么方法可以仅使用 tensorflow.estimator.train_and_evaluate() 保存最佳模型吗?

python - 我安装了python 3.5.2(64位),pip版本是9.0.1,但是当我尝试安装tensorflow时,它说找不到版本,为什么是:(the

python - load_data() 在 PC (Windows 10) 上的哪个文件夹中保存 Keras 中的数据集?

python - 使用 tensorflow 2 实现梯度惩罚损失

python - Keras神经网络输出函数参数/如何构造损失函数?

python - 从 python 调用 c 函数是行不通的

python - 如何在直方图上设置轴并交换 x 轴和 y 轴?

python - apache beam python sdk 是否可以进行状态处理?

python - 在处理异常时,如何打印出现的任何错误声明?请参阅下面的更多细节