

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

# 已部署服务的推理请求
<a name="neo-requests"></a>

如果您已按照中的说明进行操作[部署模型](neo-deployment-hosting-services.md)，则应设置并运行 A SageMaker I 终端节点。无论您如何部署 Neo 编译的模型，都可以通过三种方式提交推理请求：

**Topics**
+ [从已部署的服务（Amazon SageMaker SDK）请求推断](neo-requests-sdk.md)
+ [通过已部署服务 (Boto3) 请求推理](neo-requests-boto3.md)
+ [从已部署的服务 (AWS CLI) 请求推断](neo-requests-cli.md)

# 从已部署的服务（Amazon SageMaker SDK）请求推断
<a name="neo-requests-sdk"></a>

使用以下代码示例，根据用于训练模型的框架，通过已部署的服务请求推理。不同框架的代码示例类似。主要区别在于 TensorFlow 要求`application/json`作为内容类型。

 

## PyTorch 和 MXNet
<a name="neo-requests-sdk-py-mxnet"></a>

 如果您使用的是 **PyTorch v1.4 或更高版本或 MXNet 1.7.0 或更****高版本**，并且拥有亚马逊 A SageMaker I 终端节点`InService`，则可以使用适用于 Python 的 AI SageMaker 开发工具`predictor`包进行推理请求。

**注意**  
API 因适用于 Python SageMaker 的人工智能开发工具包版本而异：  
对于版本 1.x，请使用 [https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor) 和 [https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict) API。
对于版本 2.x，请使用 [https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor) 和 [https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor.predict](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor.predict) API。

以下代码示例显示了如何使用它们发送图像 APIs 以进行推理：

------
#### [ SageMaker Python SDK v1.x ]

```
from sagemaker.predictor import RealTimePredictor

endpoint = 'insert name of your endpoint here'

# Read image into memory
payload = None
with open("image.jpg", 'rb') as f:
    payload = f.read()

predictor = RealTimePredictor(endpoint=endpoint, content_type='application/x-image')
inference_response = predictor.predict(data=payload)
print (inference_response)
```

------
#### [ SageMaker Python SDK v2.x ]

```
from sagemaker.predictor import Predictor

endpoint = 'insert name of your endpoint here'

# Read image into memory
payload = None
with open("image.jpg", 'rb') as f:
    payload = f.read()
    
predictor = Predictor(endpoint)
inference_response = predictor.predict(data=payload)
print (inference_response)
```

------

## TensorFlow
<a name="neo-requests-sdk-py-tf"></a>

以下代码示例展示了如何使用 SageMaker Python SDK API 发送用于推理的图像：

```
from sagemaker.predictor import Predictor
from PIL import Image
import numpy as np
import json

endpoint = 'insert the name of your endpoint here'

# Read image into memory
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()})
    
predictor = Predictor(endpoint)
inference_response = predictor.predict(data=body)
print(inference_response)
```

# 通过已部署服务 (Boto3) 请求推理
<a name="neo-requests-boto3"></a>

 有了 SageMaker 人工智能终端节点后，你可以使用适用于 Python 的 AI SDK (Boto3) 客户端[https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html#SageMakerRuntime.Client.invoke_endpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html#SageMakerRuntime.Client.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 允许自定义内容类型。有关更多信息，请参阅 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html)。

# 从已部署的服务 (AWS CLI) 请求推断
<a name="neo-requests-cli"></a>

[https://docs.aws.amazon.com/cli/latest/reference/sagemaker-runtime/invoke-endpoint.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker-runtime/invoke-endpoint.html)一旦您拥有 Amazon A SageMaker I 终端节点，即可使用该终端节点`InService`发出推理请求。您可以使用 AWS Command Line Interface (AWS CLI) 提出推理请求。以下示例演示如何发送映像以进行推理：

```
aws sagemaker-runtime invoke-endpoint --endpoint-name 'insert name of your endpoint here' --body fileb://image.jpg --content-type=application/x-image output_file.txt
```

如果推理成功，会生成包含有关您的推理请求的信息的 `output_file.txt`。

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

```
aws sagemaker-runtime invoke-endpoint --endpoint-name 'insert name of your endpoint here' --body fileb://input.json --content-type=application/json output_file.txt
```