

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

# デプロイされた Autopilot モデルの予測
<a name="timeseries-forecasting-deploy-models"></a>

AutoML API を使用してモデルをトレーニングしたら、リアルタイムまたはバッチベースの予測用にデプロイできます。

AutoML API は、時系列データ用の複数のモデル候補をトレーニングし、ターゲットの目標メトリクスに基づいて最適な予測モデルを選択します。モデル候補がトレーニングされると、レスポンス [DescribeAutoMLJobV2](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJobV2.html) の [BestCandidate](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-CandidateName) で最適な候補メトリクスを見つけることができます。

この最もパフォーマンスの高いモデルをを使用して予測を取得するには、エンドポイントを設定して予測をインタラクティブに取得するか、バッチ予測を使用して一定の観測値に基づいて予測を行います。

**考慮事項**
+ 予測用の入力データを提供する場合、データのスキーマは、列数、列ヘッダー、データ型を含め、モデルのトレーニングに使用したものと同じにしておく必要があります。異なる期間を予測するために、同じまたは異なるタイムスタンプ範囲内の既存または新しいアイテム ID を予測することができます。
+ 予測モデルは、トレーニング時の入力リクエストで指定された将来の予測期間ポイント (ターゲット終了日からターゲット終了日 \$1 予測期間) を予測します。特定の日付を予測するためにモデルを使用するには、元の入力データと同じ形式で、指定されたターゲット終了日まで拡張したデータを提供する必要があります。このシナリオでは、モデルは新しいターゲット終了日から予測を開始します。

  例えば、データセットに 1 月から 6 月までの月次データがあり、予測期間が 2 の場合、モデルは次の 2 か月間、つまり 7 月と 8 月のターゲット値を予測します。8 月に次の 2 か月を予測する場合、今回は入力データを 1 月から 8 月までとし、モデルは次の 2 か月 (9 月、10 月) を予測します。
+ 将来のデータポイントを予測する場合、提供する履歴データの量に最小値は設定されません。時系列の季節的なパターンと反復的なパターンをキャプチャするのに十分なデータを含めます。

**Topics**
+ [リアルタイム予測](timeseries-forecasting-realtime.md)
+ [バッチ予測](timeseries-forecasting-batch.md)

# リアルタイム予測
<a name="timeseries-forecasting-realtime"></a>

リアルタイム予測は、即時応答を必要とするアプリケーションや個々のデータポイントの予測など、その場で予測を生成する必要がある場合に役立ちます。

AutoML モデルをリアルタイムエンドポイントとしてデプロイすることで、予測をオンデマンドで生成し、新しいデータを受信してから予測を取得するまでの間のレイテンシーを最小限に抑えることができます。このため、リアルタイム予測は、即時の、パーソナライズされた、またはイベント駆動型の予測機能を必要とするアプリケーションに適しています。

リアルタイム予測の場合、データセットは入力データセットのサブセットである必要があります。リアルタイムエンドポイントの入力データサイズは約 6 MB で、応答タイムアウトの制限は 60 秒です。一度に 1 つまたはいくつかの項目を取り込むことをお勧めします。

SageMaker API を使用して AutoML ジョブの最適な候補を取得し、その候補を使用して SageMaker AI エンドポイントを作成できます。

または、Autopilot 実験の作成時に自動デプロイオプションを選択することもできます。モデルの自動デプロイの設定については、「[自動デプロイを有効にする方法](autopilot-create-experiment-timeseries-forecasting.md#timeseries-forecasting-auto-model-deployment)」を参照してください。

**最適なモデル候補を使用して SageMaker AI エンドポイントを作成するには**

1. 

**AutoML ジョブの詳細を取得します。**

   次の AWS CLI コマンド例では、[DescribeAutoMLJobV2](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJobV2.html) API を使用して、最適なモデル候補に関する情報など、AutoML ジョブの詳細を取得します。

   ```
   aws sagemaker describe-auto-ml-job-v2 --auto-ml-job-name job-name --region region
   ```

1. 

**[InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers) から最適なモデル候補のコンテナ定義を抽出します。**

   コンテナ定義は、予測を実行するトレーニング済みの SageMaker AI モデルをホストするために使用されるコンテナ化された環境です。

   ```
   BEST_CANDIDATE=$(aws sagemaker describe-auto-ml-job-v2 \
     --auto-ml-job-name job-name 
     --region region \
     --query 'BestCandidate.InferenceContainers[0]' \
     --output json
   ```

   このコマンドは、最適なモデル候補のコンテナ定義を抽出して、`BEST_CANDIDATE` 変数に保存します。

1. 

**最適な候補のコンテナ定義を使用して SageMaker AI モデルを作成します。**

   前のステップのコンテナ定義を使用して、[CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API を使用して SageMaker AI モデルを作成します。

   ```
   aws sagemaker create-model \
               --model-name 'your-candidate-name>' \
               --primary-container "$BEST_CANDIDATE"
               --execution-role-arn 'execution-role-arn>' \
               --region 'region>
   ```

   `--execution-role-arn` パラメータは、モデルを推論に使用するときに SageMaker AI が引き受ける IAM ロールを指定します。このロールに必要なアクセス許可の詳細については、「[CreateModel API: Execution Role Permissions](https://docs.aws.amazon.com/)」を参照してください。

1. 

**モデルを使用して SageMaker AI エンドポイント設定を作成します。**

   次の AWS CLI コマンドは、[CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) API を使用してエンドポイント設定を作成します。

   ```
   aws sagemaker create-endpoint-config \
     --production-variants file://production-variants.json \
     --region 'region'
   ```

   `production-variants.json` ファイルには、モデル名とインスタンスタイプを含むモデル設定が含まれています。
**注記**  
リアルタイム予測には [m5.12xlarge](https://aws.amazon.com/ec2/instance-types/m5/) インスタンスを使用することをお勧めします。

   ```
   [
       {
         "VariantName": "variant-name",
         "ModelName": "model-name",
         "InitialInstanceCount": 1,
         "InstanceType": "m5.12xlarge"
       }
     ]
   }
   ```

1. 

**エンドポイント設定を使用し てSageMaker AI エンドポイントを作成します。**

   次の AWS CLI 例では、[CreateEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html) API を使用してエンドポイントを作成します。

   ```
   aws sagemaker create-endpoint \
               --endpoint-name 'endpoint-name>' \
               --endpoint-config-name 'endpoint-config-name' \
               --region 'region'
   ```

   [DescribeEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeEndpoint.html) API を使用して、リアルタイム推論エンドポイントのデプロイの進行状況を確認します。例として、次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker describe-endpoint \
               --endpoint-name 'endpoint-name' \
               --region 'region'
   ```

   `EndpointStatus` が `InService` に変更されると、エンドポイントはリアルタイム推論に使用できるようになります。

1. 

**SageMaker AI エンドポイントを呼び出して予測を行います。**

   ```
   aws sagemaker invoke-endpoint \
               --endpoint-name 'endpoint-name' \ 
               --region 'region' \
               --body file://input-data-in-bytes.json \
               --content-type 'application/json' outfile
   ```

   `input-data-in-bytes.json` ファイルには予測用の入力データが含まれます。

# バッチ予測
<a name="timeseries-forecasting-batch"></a>

バッチ予測は、オフライン推論とも呼ばれ、バッチ観測に基づいてモデル予測を生成します。バッチ推論は、データセットが大きい場合や、モデル予測のリクエストにすぐに応答する必要がない場合に適しています。

これとは対照的に、オンライン推論 (リアルタイム推論) はリアルタイムで予測を生成します。

SageMaker API を使用して AutoML ジョブの最適な候補を取得し、その候補を使用して推論用の入力データのバッチを送信できます。

1. 

**AutoML ジョブの詳細を取得します。**

   次の AWS CLI コマンド例では、[DescribeAutoMLJobV2](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJobV2.html) API を使用して、最適なモデル候補に関する情報など、AutoML ジョブの詳細を取得します。

   ```
   aws sagemaker describe-auto-ml-job-v2 --auto-ml-job-name job-name --region region
   ```

1. 

**[InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers) から最適なモデル候補のコンテナ定義を抽出します。**

   コンテナ定義は、予測を実行するトレーニング済みの SageMaker AI モデルをホストするために使用されるコンテナ化された環境です。

   ```
   BEST_CANDIDATE=$(aws sagemaker describe-auto-ml-job-v2 \
         --auto-ml-job-name job-name 
         --region region \
         --query 'BestCandidate.InferenceContainers[0]' \
         --output json
   ```

   このコマンドは、最適なモデル候補のコンテナ定義を抽出して、`BEST_CANDIDATE` 変数に保存します。

1. 

**最適な候補のコンテナ定義を使用して SageMaker AI モデルを作成します。**

   前のステップのコンテナ定義を使用して、[CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API を使用して SageMaker AI モデルを作成します。

   ```
   aws sagemaker create-model \
         --model-name 'model-name' \
         --primary-container "$BEST_CANDIDATE"
         --execution-role-arn 'execution-role-arn>' \
         --region 'region>
   ```

   `--execution-role-arn` パラメータは、モデルを推論に使用するときに SageMaker AI が引き受ける IAM ロールを指定します。このロールに必要なアクセス許可の詳細については、「[CreateModel API: Execution Role Permissions](https://docs.aws.amazon.com/)」を参照してください。

1. 

**バッチ変換ジョブを作成します。**

   次の例では、[CreateTransformJob](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-transform-job.html) API を使用して変換ジョブを作成します。

   ```
   aws sagemaker create-transform-job \ 
          --transform-job-name 'transform-job-name' \
          --model-name 'model-name'\
          --transform-input file://transform-input.json \
          --transform-output file://transform-output.json \
          --transform-resources file://transform-resources.json \
          --region 'region'
   ```

   入力、出力、リソースの詳細は、個別の JSON ファイルで定義されます。
   + `transform-input.json`:

     ```
     {
       "DataSource": {
         "S3DataSource": {
           "S3DataType": "S3Prefix",
           "S3Uri": "s3://my-input-data-bucket/path/to/input/data"
         }
       },
       "ContentType": "text/csv",
       "SplitType": "None"
     }
     ```
   + `transform-output.json`:

     ```
     {
       "S3OutputPath": "s3://my-output-bucket/path/to/output",
       "AssembleWith": "Line"
     }
     ```
   + `transform-resources.json`:
**注記**  
汎用ワークロードには [m5.12xlarge](https://aws.amazon.com/ec2/instance-types/m5/) インスタンスを使用し、ビッグデータ予測タスクには `m5.24xlarge` インスタンスを使用することをお勧めします。

     ```
     {
       "InstanceType": "instance-type",
       "InstanceCount": 1
     }
     ```

1. 

**[DescribeTransformJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTransformJob.html) API を使用して変換ジョブの進行状況を監視します。**

   例として、次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker describe-transform-job \
         --transform-job-name 'transform-job-name' \
         --region region
   ```

1. 

**バッチ変換出力を取得します。**

   ジョブが終了すると、予測された結果が `S3OutputPath` に表示されます。

   出力ファイル名は以下のの形式です。`input_data_file_name.out`例えば、入力ファイルが `text_x.csv` の場合、出力名は `text_x.csv.out` になります。

   ```
   aws s3 ls s3://my-output-bucket/path/to/output/
   ```

次のコード例は、 AWS SDK for Python (boto3) と をバッチ予測に使用する AWS CLI 方法を示しています。

------
#### [ AWS SDK for Python (boto3) ]

 以下の例では **AWS SDK for Python (boto3)** を使用してバッチで予測を行います。

```
import sagemaker 
import boto3

session = sagemaker.session.Session()

sm_client = boto3.client('sagemaker', region_name='us-west-2')
role = 'arn:aws:iam::1234567890:role/sagemaker-execution-role'
output_path = 's3://test-auto-ml-job/output'
input_data = 's3://test-auto-ml-job/test_X.csv'

best_candidate = sm_client.describe_auto_ml_job_v2(AutoMLJobName=job_name)['BestCandidate']
best_candidate_containers = best_candidate['InferenceContainers']
best_candidate_name = best_candidate['CandidateName']

# create model
reponse = sm_client.create_model(
    ModelName = best_candidate_name,
    ExecutionRoleArn = role,
    Containers = best_candidate_containers 
)

# Lauch Transform Job
response = sm_client.create_transform_job(
    TransformJobName=f'{best_candidate_name}-transform-job',
    ModelName=model_name,
    TransformInput={
        'DataSource': {
            'S3DataSource': {
                'S3DataType': 'S3Prefix',
                'S3Uri': input_data
            }
        },
        'ContentType': "text/csv",
        'SplitType': 'None'
    },
    TransformOutput={
        'S3OutputPath': output_path,
        'AssembleWith': 'Line',
    },
    TransformResources={
        'InstanceType': 'ml.m5.2xlarge',
        'InstanceCount': 1,
    },
)
```

バッチ推論ジョブは、以下の形式でレスポンスを返します。

```
{'TransformJobArn': 'arn:aws:sagemaker:us-west-2:1234567890:transform-job/test-transform-job',
 'ResponseMetadata': {'RequestId': '659f97fc-28c4-440b-b957-a49733f7c2f2',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '659f97fc-28c4-440b-b957-a49733f7c2f2',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '96',
   'date': 'Thu, 11 Aug 2022 22:23:49 GMT'},
  'RetryAttempts': 0}}
```

------
#### [ AWS Command Line Interface (AWS CLI) ]

1. **最適な候補のコンテナ定義を取得**します。

   ```
   aws sagemaker describe-auto-ml-job-v2 --auto-ml-job-name 'test-automl-job' --region us-west-2
   ```

1. **モデルを作成**します。

   ```
   aws sagemaker create-model --model-name 'test-sagemaker-model'
   --containers '[{
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3",
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/data-processor-models/test-job1-dpp0-1-e569ff7ad77f4e55a7e549a/output/model.tar.gz",
       "Environment": {
           "AUTOML_SPARSE_ENCODE_RECORDIO_PROTOBUF": "1",
           "AUTOML_TRANSFORM_MODE": "feature-transform",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "application/x-recordio-protobuf",
           "SAGEMAKER_PROGRAM": "sagemaker_serve",
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code"
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-xgboost:1.3-1-cpu-py3",
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/tuning/flicdf10v2-dpp0-xgb/test-job1E9-244-7490a1c0/output/model.tar.gz",
       "Environment": {
           "MAX_CONTENT_LENGTH": "20971520",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,probabilities" 
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3", 
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/data-processor-models/test-job1-dpp0-1-e569ff7ad77f4e55a7e549a/output/model.tar.gz", 
       "Environment": { 
           "AUTOML_TRANSFORM_MODE": "inverse-label-transform", 
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv", 
           "SAGEMAKER_INFERENCE_INPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,labels,probabilities", 
           "SAGEMAKER_PROGRAM": "sagemaker_serve", 
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code" 
       } 
   }]' \
   --execution-role-arn 'arn:aws:iam::1234567890:role/sagemaker-execution-role' \
   --region 'us-west-2'
   ```

1. **変換ジョブを作成**します。

   ```
   aws sagemaker create-transform-job --transform-job-name 'test-tranform-job'\
    --model-name 'test-sagemaker-model'\
    --transform-input '{
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix",
                   "S3Uri": "s3://amzn-s3-demo-bucket/data.csv"
               }
           },
           "ContentType": "text/csv",
           "SplitType": "None"
       }'\
   --transform-output '{
           "S3OutputPath": "s3://amzn-s3-demo-bucket/output/",
           "AssembleWith": "Line"
       }'\
   --transform-resources '{
           "InstanceType": "ml.m5.2xlarge",
           "InstanceCount": 1
       }'\
   --region 'us-west-2'
   ```

1. **変換ジョブの進行状況を確認**します。

   ```
   aws sagemaker describe-transform-job --transform-job-name  'test-tranform-job' --region us-west-2
   ```

   以下は、変換ジョブからのレスポンスです。

   ```
   {
       "TransformJobName": "test-tranform-job",
       "TransformJobArn": "arn:aws:sagemaker:us-west-2:1234567890:transform-job/test-tranform-job",
       "TransformJobStatus": "InProgress",
       "ModelName": "test-model",
       "TransformInput": {
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix",
                   "S3Uri": "s3://amzn-s3-demo-bucket/data.csv"
               }
           },
           "ContentType": "text/csv",
           "CompressionType": "None",
           "SplitType": "None"
       },
       "TransformOutput": {
           "S3OutputPath": "s3://amzn-s3-demo-bucket/output/",
           "AssembleWith": "Line",
           "KmsKeyId": ""
       },
       "TransformResources": {
           "InstanceType": "ml.m5.2xlarge",
           "InstanceCount": 1
       },
       "CreationTime": 1662495635.679,
       "TransformStartTime": 1662495847.496,
       "DataProcessing": {
           "InputFilter": "$",
           "OutputFilter": "$",
           "JoinSource": "None"
       }
   }
   ```

   `TransformJobStatus` を `Completed` に変更した後は、`S3OutputPath` で推論結果を確認できます。

------