

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

# バッチ推論ジョブを実行する
<a name="autopilot-deploy-models-batch"></a>

バッチ推論はオフライン推論とも呼ばれ、複数の観測値に基づいてモデル予測を生成します。バッチ推論は、データセットが大きい場合や、モデル予測のリクエストにすぐに応答する必要がない場合に適しています。これとは対照的に、オンライン推論 ([リアルタイム推論](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-deploy-models.html#autopilot-deploy-models-realtime)) はリアルタイムで予測を生成します。[SageMaker Python SDK、Autopilot ユーザーインターフェイス (UI](https://sagemaker.readthedocs.io/en/stable/))、[AWS SDK for Python (boto3)、または () を使用して](https://aws.amazon.com/sdk-for-python/)、Autopilot モデルからバッチ推論を行うことができます[AWS CLI](https://docs.aws.amazon.com/cli/)。 AWS Command Line Interface 

以下のタブでは、モデルをデプロイするための 3 つのオプションを示しています。「API を使用する」、「Autopilot UI」、「API を使用して異なるアカウントからデプロイする」です。これらの手順は、Autopilot で既にモデルを作成していることを前提としています。モデルがない場合は、「[AutoML API を使用して表形式データのリグレッションジョブまたは分類ジョブを作成する](autopilot-automate-model-development-create-experiment.md)」を参照してください。各オプションの例を見るには、各タブを開いてください。

## Autopilot UI を使用してモデルをデプロイする
<a name="autopilot-deploy-models-batch-ui"></a>

Autopilot UI には、モデルのデプロイをナビゲートするのに役立つドロップダウンメニュー、トグル、ツールチップなどが含まれています。

以下の手順は、Autopilot 実験からバッチ予測用のモデルをデプロイする方法を示しています。

1. [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) にサインインし、ナビゲーションペインから **[Studio]** を選択します。

1. 左側のナビゲーションペインで、**[Studio]** を選択します。

1. **[使用を開始]** で、Studio アプリケーションを起動するドメインを選択します。ユーザープロファイルが 1 つのドメインにのみ属している場合、ドメインの選択オプションは表示されません。

1. Studio Classic アプリケーションを起動するユーザープロファイルを選択します。ドメインにユーザープロファイルがない場合は、**[ユーザープロファイルを作成]** を選択します。詳細については、「[Add user profiles](https://docs.aws.amazon.com/sagemaker/latest/dg/domain-user-profile-add.html)」を参照してください。

1. **[Studio を起動]** を選択します。ユーザープロファイルが共有スペースに属している場合は、**[オープンスペース]** を選択します。

1. SageMaker Studio Classic コンソールが開いたら、**[SageMaker Studio を起動]** ボタンを選択します。

1. 左のナビゲーションペインで **[AutoML]** を選択します。

1. **[名前]** で、デプロイするモデルに対応する Autopilot 実験を選択します。これにより、新しい **[Autopilot ジョブ]** タブが開きます。

1. **[モデル名]** セクションで、デプロイするモデルを選択します。

1. [**Deploy model (モデルのデプロイ)**] を選択します。これにより、新しいタブが開きます。

1. ページ上部の **[バッチ予測を行う]** を選択します。

1. **[バッチ変換ジョブの設定]** に、**[インスタンスタイプ]**、**[インスタンス数]**、その他のオプション情報を入力します。

1. **[入力データ設定]** セクションで、ドロップダウンメニューを開きます。

   1. **[S3 データタイプ]** には、**[マニフェストファイル]** または **[S3 プレフィックス]** を選択します。

   1. **[分割タイプ]** には、**[ライン]**、**[RecordIO]**、**[TFRecord]**、または **[なし]** を選択します。

   1. **[圧縮]** には、**[Gzip]** または **[なし]** を選択します。

1. **[S3 の場所]** には、入力データの Amazon S3 バケットの場所とそれ以外のオプション情報を入力します。

1. **[出力データ設定]** で、出力データの S3 バケットを入力し、ジョブの[出力をアセンブルする](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TransformOutput.html#sagemaker-Type-TransformOutput-AssembleWith)方法を選択します。

   1. **[追加設定 (オプション)]** では、MIME タイプと **[S3 暗号化キー]** を入力できます。

1. **[入力/出力フィルタリングとデータ結合 (オプション)]** では、JSONpath 式を入力して入力データをフィルタリングし、入力ソースデータを出力データと結合し、JSONpath 式を入力して出力データをフィルタリングします。

   1. 各タイプのフィルターの例については、「[DataProcessing API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataProcessing.html#sagemaker-Type-DataProcessing-InputFilter)」を参照してください。

1. 入力データセットのバッチ予測を実行するには、**[バッチ変換ジョブの作成]** を選択します。新しい **[バッチ変換ジョブ]** タブが表示されます。

1. **[バッチ変換ジョブ]** タブの、**[ステータス]** セクションでジョブの名前を見つけます。次に、ジョブの進行状況を確認します。

## SageMaker API を使用してデプロイする
<a name="autopilot-deploy-models-batch-steps"></a>

SageMaker API をバッチ推論に使用するには、次の 3 つのステップがあります。

1. **候補定義を入手する** 

   SageMaker AI モデルの作成には、[InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers) からの候補定義が使用されます。

   次の例は、[DescribeAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJob.html) API を使用して最適なモデル候補の候補定義を取得する方法を示しています。例として、次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker describe-auto-ml-job --auto-ml-job-name {{<job-name>}} --region {{<region>}}
   ```

   [ListCandidatesForAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListCandidatesForAutoMLJob.html) API を使用して、すべての候補を一覧表示します。次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker list-candidates-for-auto-ml-job --auto-ml-job-name {{<job-name>}} --region {{<region>}}
   ```

1. **SageMaker AI モデルを作成する**

   [CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API を使用して SageMaker AI モデルを作成するには、前のステップのコンテナ定義を使用します。例として、次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker create-model --model-name '{{<your-custom-model-name>}}' \
                       --containers ['{{<container-definition1}}>, {{<container-definition2>}}, {{<container-definition3>}}]' \
                       --execution-role-arn '{{<execution-role-arn>}}' --region '{{<region>}}
   ```

1. **SageMaker AI 変換ジョブを作成する** 

   次の例では、[CreateTransformJob](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-transform-job.html) API を使用して SageMaker AI 変換ジョブを作成します。例として、次の AWS CLI コマンドを参照してください。

   ```
   aws sagemaker create-transform-job --transform-job-name '{{<your-custom-transform-job-name>}}' --model-name '{{<your-custom-model-name-from-last-step>}}'\
   --transform-input '{
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix", 
                   "S3Uri": "{{<your-input-data>}}" 
               }
           },
           "ContentType": "{{text/csv}}",
           "SplitType": "Line"
       }'\
   --transform-output '{
           "S3OutputPath": "{{<your-output-path>}}",
           "AssembleWith": "Line" 
       }'\
   --transform-resources '{
           "InstanceType": "{{<instance-type>}}", 
           "InstanceCount": {{1}}
       }' --region '{{<region>}}'
   ```

[DescribeTransformJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTransformJob.html) API を使用して変換ジョブの進行状況を確認します。例として、次の AWS CLI コマンドを参照してください。

```
aws sagemaker describe-transform-job --transform-job-name '{{<your-custom-transform-job-name>}}' --region {{<region>}}
```

ジョブが終了すると、予測された結果が `<your-output-path>` で利用可能になります。

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

次のタブは、SageMaker Python SDK、 AWS SDK for Python (boto3)、および のコード例を示しています AWS CLI。

------
#### [ SageMaker Python SDK ]

次の例では、**[SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/overview.html)** を使用してバッチで予測を実行します。

```
from sagemaker import AutoML

sagemaker_session= sagemaker.session.Session()

job_name = '{{test-auto-ml-job}}' # your autopilot job name
automl = AutoML.attach(auto_ml_job_name=job_name)
output_path = '{{s3://test-auto-ml-job/output}}'
input_data = '{{s3://test-auto-ml-job/test_X.csv}}'

# call DescribeAutoMLJob API to get the best candidate definition
best_candidate = automl.describe_auto_ml_job()['BestCandidate']
best_candidate_name = best_candidate['CandidateName']

# create model
model = automl.create_model(name=best_candidate_name, 
               candidate=best_candidate)

# create transformer
transformer = model.transformer(instance_count={{1}}, 
    instance_type='{{ml.m5.2xlarge}}',
    assemble_with='Line',
    output_path=output_path)

# do batch transform
transformer.transform(data=input_data,
                      split_type='Line',
                       content_type='{{text/csv}}',
                       wait=True)
```

------
#### [ 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(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': 'Line'
    },
    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 --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": "Line"
       }'\
   --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": "Line"
       },
       "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` で推論結果を確認できます。

------

## 異なるアカウントからモデルをデプロイする
<a name="autopilot-deploy-models-batch-across-accounts"></a>

モデルを生成したアカウントとは別のアカウントでバッチ推論ジョブを作成するには、「[さまざまなアカウントからモデルをデプロイできます。](autopilot-deploy-models-realtime.md#autopilot-deploy-models-realtime-across-accounts)」の手順に従います。その後、「[SageMaker API を使用してデプロイする](#autopilot-deploy-models-batch-steps)」に従ってモデルを作成し、ジョブを変換できます。