

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

# 予測結果をチェックする
<a name="async-inference-check-predictions"></a>

非同期エンドポイントからの予測結果をチェックする方法は複数あります。一部のオプションは次のとおりです。

1. Amazon SNS トピック。

1. Amazon S3 バケット内の出力をチェックします。

## Amazon SNS トピック
<a name="async-inference-check-predictions-sns-topic"></a>

Amazon SNS は、メッセージング指向のアプリケーション向け通知サービスです。HTTP、Amazon SQS、メールなどのトランスポートプロトコルを選択することにより、複数のサブスクライバーがタイムクリティカルなメッセージの「プッシュ」通知を要求および受信します。[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) を使用してエンドポイントを作成し、Amazon SNS トピックを指定すると、Amazon SageMaker 非同期推論により通知が投稿されます。

**注記**  
Amazon SNS 通知を受信するには、IAM ロールに `sns:Publish` の許可が必要です。非同期推論を使用するために満たす必要がある要件については、「[の前提条件を満たす](async-inference-create-endpoint-prerequisites.md)」を参照してください。

Amazon SNS を使って非同期エンドポイントからの予測結果をチェックするには、まずトピックを作成してそのトピックをサブスクライブし、トピックのサブスクリプションを確認してから、そのトピックの Amazon リソースネーム (ARN) を把握しておく必要があります。Amazon SNS トピックの Amazon ARN を作成、サブスクライブ、発見する方法の詳細については、「[Amazon SNS を設定する](https://docs.aws.amazon.com/sns/latest/dg/sns-configuring.html)」を参照してください。

`CreateEndpointConfig` を使用してエンドポイント設定を作成する際に、`AsyncInferenceConfig` フィールドに Amazon SNS トピックの ARN を指定します。Amazon SNS `ErrorTopic` と `SuccessTopic` の両方を指定できます。

```
import boto3

sagemaker_client = boto3.client('sagemaker', region_name=<aws_region>)

sagemaker_client.create_endpoint_config(
    EndpointConfigName=<endpoint_config_name>, # You specify this name in a CreateEndpoint request.
    # List of ProductionVariant objects, one for each model that you want to host at this endpoint.
    ProductionVariants=[
        {
            "VariantName": "variant1", # The name of the production variant.
            "ModelName": "model_name", 
            "InstanceType": "ml.m5.xlarge", # Specify the compute instance type.
            "InitialInstanceCount": 1 # Number of instances to launch initially.
        }
    ],
    AsyncInferenceConfig={
        "OutputConfig": {
            # Location to upload response outputs when no location is provided in the request.
            "S3OutputPath": "s3://<bucket>/<output_directory>"
            "NotificationConfig": {
                "SuccessTopic": "arn:aws:sns:aws-region:account-id:topic-name",
                "ErrorTopic": "arn:aws:sns:aws-region:account-id:topic-name",
            }
        }
    }
)
```

エンドポイントを作成して呼び出すと、Amazon SNS トピックから通知を受け取ります。例えば、トピックから E メール通知を受信するようにサブスクライブした場合、エンドポイントを呼び出すたびに E メール通知を受け取ります。次の例は、正常な呼び出し E メール通知の JSON コンテンツを示しています。

```
{
   "awsRegion":"us-east-1",
   "eventTime":"2022-01-25T22:46:00.608Z",
   "receivedTime":"2022-01-25T22:46:00.455Z",
   "invocationStatus":"Completed",
   "requestParameters":{
      "contentType":"text/csv",
      "endpointName":"<example-endpoint>",
      "inputLocation":"s3://<bucket>/<input-directory>/input-data.csv"
   },
   "responseParameters":{
      "contentType":"text/csv; charset=utf-8",
      "outputLocation":"s3://<bucket>/<output_directory>/prediction.out"
   },
   "inferenceId":"11111111-2222-3333-4444-555555555555", 
   "eventVersion":"1.0",
   "eventSource":"aws:sagemaker",
   "eventName":"InferenceResult"
}
```

## S3 バケットをチェックする
<a name="async-inference-check-predictions-s3-bucket"></a>

`InvokeEndpointAsync` を使用してエンドポイントを呼び出すと、レスポンスオブジェクトが返されます。レスポンスオブジェクトを使用して、出力が保存されている Amazon S3 URI を取得できます。出力場所がわかることで、SageMaker Python SDK SageMaker AI セッションクラスを使って、出力をプログラムによりチェックできます。

次の例では、`InvokeEndpointAsync` の出力ディクショナリを response という名前の変数として保存します。レスポンス変数を使用して、Amazon S3 出力 URI を取得し、`output_location` という文字列変数として保存します。

```
import uuid
import boto3

sagemaker_runtime = boto3.client("sagemaker-runtime", region_name=<aws_region>)

# Specify the S3 URI of the input. Here, a single SVM sample
input_location = "s3://bucket-name/test_point_0.libsvm" 

response = sagemaker_runtime.invoke_endpoint_async(
    EndpointName='<endpoint-name>',
    InputLocation=input_location,
    InferenceId=str(uuid.uuid4()), 
    ContentType="text/libsvm" #Specify the content type of your data
)

output_location = response['OutputLocation']
print(f"OutputLocation: {output_location}")
```

サポートされるコンテンツタイプについては、「[推論の共通データ形式](cdf-inference.md)」を参照してください。

Amazon S3 出力場所を使って、[SageMaker Python SDK SageMaker AI セッションクラス](https://sagemaker.readthedocs.io/en/stable/api/utility/session.html?highlight=session)を使用して Amazon S3 ファイルを読み取ります。次のコード例は、Amazon S3 出力場所からファイルの読み取りを繰り返し試みる関数 (`get_ouput`) を作成する方法を示しています。

```
import sagemaker
import urllib, time
from botocore.exceptions import ClientError

sagemaker_session = sagemaker.session.Session()

def get_output(output_location):
    output_url = urllib.parse.urlparse(output_location)
    bucket = output_url.netloc
    key = output_url.path[1:]
    while True:
        try:
            return sagemaker_session.read_s3_file(
                                        bucket=output_url.netloc, 
                                        key_prefix=output_url.path[1:])
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchKey':
                print("waiting for output...")
                time.sleep(2)
                continue
            raise
            
output = get_output(output_location)
print(f"Output: {output}")
```