【问题标题】:Using `inference_schema.schema_decorators` with dynamic `numpy` array shape使用带有动态 numpy 数组形状的 inference_schema.schema_decorators
【发布时间】:2019-10-02 14:11:24
【问题描述】:

问题摘要

我正在使用 Azure 机器学习服务 API 将模型部署到 Azure 容器实例。具体来说,该模型是一个 PyTorch (fastai) 模型,用于对不同形状的图像进行分类。

Microsoft 提供了一些不错的装饰器来处理评分脚本中的输入和输出数据模式。但是,我无法弄清楚是否可以将NumpyParameterType 与动态形状一起用于输入。

评分脚本

评分脚本示例:

import pickle
import json
import numpy as np
import time
import os

from PIL import Image as PilImage
from azureml.core.model import Model
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType

def preprocess_inference(img):
    # Preprocessing handled here

def make_prediction(data_preprocessed):
    # Model prediction handled here

def init():
    global model

    model_path = Model.get_model_path(model_name='my_pytorch_model',
                                      version=1)

    # Get paths
    split_path = model_path.split('/')

    model = fastai.load_learner(path = '/'.join(split_path[:-1]), file = split_path[-1])

# How to use the schema decoraters with dynamic size?
input_sample = np.array(PilImage.open('src/deployment/test/test_image.png'))
output_sample = np.array([0, None], dtype=np.object)

@input_schema('raw_data', NumpyParameterType(input_sample))
@output_schema(NumpyParameterType(output_sample))
def run(raw_data):

    try:

        data_preprocessed = preprocess_inference(raw_data)

        prediction = make_prediction(data_preprocessed)

        return prediction

    except Exception as e:
        error = str(e)
        print (error + time.strftime("%H:%M:%S"))
        return error

仅当上传的图像具有与“src/deployment/test/test_image.png”完全相同的形状时才有效。现在我的解决方案是避免使用装饰器并自己进行数据解释。


def run(raw_data):

    try:

        img = np.array(json.loads(raw_data)['raw_data'], dtype=np.uint8)
        img = np.expand_dims(img, axis=2)

        data_preprocessed = preprocess_inference(img)

        prediction = make_prediction(data_preprocessed)

        return prediction

    except Exception as e:
        error = str(e)
        print (error + time.strftime("%H:%M:%S"))
        return error

但如果能够使用装饰器就太好了,这样最终用户也可以从漂亮的警告消息中受益。

【问题讨论】:

    标签: azure-machine-learning-service


    【解决方案1】:

    NumpyParameterType 类的构造函数有一个enforce_shape 参数,可以将其设置为 False 以允许动态数组大小:

    @input_schema('raw_data', NumpyParameterType(input_sample, enforce_shape=False))

    但是,这可能仍然会有一些奇怪的交互,具体取决于您将图像数据传递到服务的方式。我们正在研究一种可用于更好地处理图像的参数类型,但还没有。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多