通过已部署服务 (Boto3) 请求推理 - Amazon SageMaker
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

通过已部署服务 (Boto3) 请求推理

有了终端节点后,你可以使用 SageMaker 适用于 Python 的 SDK (Boto3) 客户端invoke_endpoint()和 API 提交推理请求。 SageMaker InService以下代码示例演示如何发送映像以进行推理:

PyTorch and MXNet
import boto3 import json endpoint = 'insert name of your endpoint here' runtime = boto3.Session().client('sagemaker-runtime') # Read image into memory with open(image, 'rb') as f: payload = f.read() # Send image via InvokeEndpoint API response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='application/x-image', Body=payload) # Unpack response result = json.loads(response['Body'].read().decode())
TensorFlow

用于 TensorFlow 提交内容类型的输入。application/json

from PIL import Image import numpy as np import json import boto3 client = boto3.client('sagemaker-runtime') input_file = 'path/to/image' image = Image.open(input_file) batch_size = 1 image = np.asarray(image.resize((224, 224))) image = image / 128 - 1 image = np.concatenate([image[np.newaxis, :, :]] * batch_size) body = json.dumps({"instances": image.tolist()}) ioc_predictor_endpoint_name = 'insert name of your endpoint here' content_type = 'application/json' ioc_response = client.invoke_endpoint( EndpointName=ioc_predictor_endpoint_name, Body=body, ContentType=content_type )
XGBoost

对于 XGBoost 应用程序,您应改为提交 CSV 文本:

import boto3 import json endpoint = 'insert your endpoint name here' runtime = boto3.Session().client('sagemaker-runtime') csv_text = '1,-1.0,1.0,1.5,2.6' # Send CSV text via InvokeEndpoint API response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='text/csv', Body=csv_text) # Unpack response result = json.loads(response['Body'].read().decode())

请注意,BYOM 允许自定义内容类型。有关更多信息,请参阅runtime_InvokeEndpoint