

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 具有所部署服務的推論請求
<a name="neo-requests"></a>

如已依照[部署模型](neo-deployment-hosting-services.md)中的指示作業，您應已設定並執行 SageMaker AI 端點。無論您如何部署 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 1.4 版或更新版本**，或使用 **MXNet 1.7.0 或更新版本**，而且您具備一個 Amazon SageMaker AI 端點 `InService`，就可以使用適用於 Python 的 SageMaker AI SDK `predictor` 套件提出推論請求。

**注意**  
API 會根據適用於 Python 版本的 SageMaker AI SDK 而有所不同：  
針對 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。

下列程式碼範例會示範如何使用這些 API 傳送映像進行推論：

------
#### [ 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 端點 `InService` 後，您就可以使用適用於 Python 的 SageMaker 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 來提交推論請求。下列程式碼範例會示範如何傳送映像進行推論：

------
#### [ 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>

具備 Amazon SageMaker AI 端點 `InService` 後，您就可以使用 [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) 提出推論請求。您可以使用 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
```