Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门。本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
请求从已部署服务推理 (Boto3)
您可以使用适用于 Python 的 SageMaker 开发工具包 (Boto3) 客户端和invoke_endpoint()
拥有 SageMaker 终端节点后的 APIInService
. 下面的代码示例演示了如何发送图像进行推理:
- 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
。