在 Amazon SageMaker 中进行预测之前预处理输入数据

nad*_*nad 3 python machine-learning keras tensorflow amazon-sagemaker

我有一个我们自己训练的 Keras/tensorflow 模型,它可以进行图像相关的预测。我已经按照这个训练有素的 keras 模型教程在 Sagemaker 中部署模型,并且可以调用端点进行预测。

现在在我的客户端代码中,在通过调用 Sagemaker 端点进行预测之前,我需要下载图像并进行一些预处理。我想在 SageMaker 中完成整个过程,而不是在客户端执行此操作。我怎么做?

看来我需要更新train.py这里提到的入口点python代码:

sagemaker_model = TensorFlowModel(model_data = 's3://' + sagemaker_session.default_bucket() + '/model/model.tar.gz',
                                  role = role,
                                  entry_point = 'train.py')
Run Code Online (Sandbox Code Playgroud)

其他文章表明我需要覆盖input_fn函数来捕获预处理。但是这些文章指的是使用 MXNet 框架时使用的步骤。但是我的模型是基于 Keras/tensorflow 框架的。

所以我不确定如何覆盖该input_fn功能。任何人都可以请建议吗?

ale*_*311 6

我遇到了同样的问题,终于想出了如何去做。

一旦你有你model_data准备好了,你可以用下面的行部署。

from sagemaker.tensorflow.model import TensorFlowModel
sagemaker_model = TensorFlowModel(
            model_data = 's3://path/to/model/model.tar.gz',
            role = role,
            framework_version = '1.12',
            entry_point = 'train.py',
            source_dir='my_src',
            env={'SAGEMAKER_REQUIREMENTS': 'requirements.txt'}
)

predictor = sagemaker_model.deploy(
    initial_instance_count=1,
    instance_type='ml.m4.xlarge', 
    endpoint_name='resnet-tensorflow-classifier'
)
Run Code Online (Sandbox Code Playgroud)

你的笔记本应该有一个my_src包含一个文件train.py和一个requirements.txt文件的目录。该train.py文件应该input_fn定义了一个函数。对我来说,该函数处理图像/jpeg 内容:

import io
import numpy as np
from PIL import Image
from keras.applications.resnet50 import preprocess_input
from keras.preprocessing import image

JPEG_CONTENT_TYPE = 'image/jpeg'

# Deserialize the Invoke request body into an object we can perform prediction on
def input_fn(request_body, content_type=JPEG_CONTENT_TYPE):
    # process an image uploaded to the endpoint
    if content_type == JPEG_CONTENT_TYPE:
        img = Image.open(io.BytesIO(request_body)).resize((300, 300))
        img_array = np.array(img)
        expanded_img_array = np.expand_dims(img_array, axis=0)
        x = preprocess_input(expanded_img_array)
        return x


    else: 
        raise errors.UnsupportedFormatError(content_type)
Run Code Online (Sandbox Code Playgroud)

您的处理代码将取决于您使用的模型架构。我正在使用 resnet50 进行迁移学习,所以我使用了preprocess_inputfrom keras.applications.resnet50.

请注意,由于我的train.py代码导入了一些模块,因此我必须提供requirements.txt定义这些模块的内容(这是我在文档中无法找到的部分)。

希望这对未来的人有所帮助。

我的requirements.txt

absl-py==0.7.1
astor==0.8.0
backports.weakref==1.0.post1
enum34==1.1.6
funcsigs==1.0.2
futures==3.2.0
gast==0.2.2
grpcio==1.20.1
h5py==2.9.0
Keras==2.2.4
Keras-Applications==1.0.7
Keras-Preprocessing==1.0.9
Markdown==3.1.1
mock==3.0.5
numpy==1.16.3
Pillow==6.0.0
protobuf==3.7.1
PyYAML==5.1
scipy==1.2.1
six==1.12.0
tensorboard==1.13.1
tensorflow==1.13.1
tensorflow-estimator==1.13.0
termcolor==1.1.0
virtualenv==16.5.0
Werkzeug==0.15.4
Run Code Online (Sandbox Code Playgroud)