本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
通过已部署服务 (Boto3) 请求推理
有了 SageMaker 人工智能终端节点后,你可以使用适用于 Python 的 AI SDK (Boto3) 客户端invoke_endpoint()
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
。
从已部署的服务(Amazon SageMaker SDK)请求推断
从已部署的服务 (AWS CLI) 请求推断