问题摘要
我正在使用 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
但是能够使用装饰器会很好,这样最终用户也可以从漂亮的警告消息中受益。