

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# デプロイされたサービスから推論をリクエストする (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 以降**を使用していて、Amazon SageMaker AI エンドポイント がある場合は`InService`、SageMaker Python SDK の `predictor`パッケージを使用して推論リクエストを行うことができます。

**注記**  
API は SageMaker Python SDK のバージョンによって異なります。  
バージョン 1.x の場合は、[`RealTimePredictor`](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor) API と [`Predict`](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict) API を使用します。
バージョン 3.x の場合は、 [`Endpoint`](https://sagemaker.readthedocs.io/en/stable/api/sagemaker_serve.html)と [`invoke`](https://sagemaker.readthedocs.io/en/stable/api/sagemaker_core.html) API を使用します。

次のコード例は、これらの API を使って推論用のイメージを送信する方法を示しています。

```
from sagemaker.core.resources import Endpoint

endpoint_name = {{'insert name of your endpoint here'}}

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

endpoint = Endpoint(endpoint_name=endpoint_name)
inference_response = endpoint.invoke(body=payload, content_type='application/x-image')
print(inference_response.body.read().decode('utf-8'))
```

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

次のコード例は、SageMaker Python SDK API を使って推論用のイメージを送信する方法を示しています。

```
from sagemaker.core.resources import Endpoint
from PIL import Image
import numpy as np
import json

endpoint_name = {{'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()})

endpoint = Endpoint(endpoint_name=endpoint_name)
inference_response = endpoint.invoke(body=body, content_type='application/json')
print(inference_response)
```