

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

# 執行批次推論任務
<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](https://sagemaker.readthedocs.io/en/stable/)、Autopilot 使用者介面 (UI)、適用於 [AWS Python 的 SDK (boto3)](https://aws.amazon.com/sdk-for-python/) 或 AWS Command Line Interface ()，從 Autopilot 模型進行批次推論[AWS CLI](https://docs.aws.amazon.com/cli/)。

下列索引索引標籤顯示三個部署模型的選項：使用 API、Autopilot 使用者介面，或使用 API 從不同帳戶進行部署。這些指示假設您已在 Autopilot 中建立模型。如果您沒有模型，則請參閱[使用 AutoML API 建立表格式資料的迴歸或分類任務](autopilot-automate-model-development-create-experiment.md)。若要查看每個選項的範例，請開啟每個索引標籤。

## 使用 Autopilot 使用者介面部署模型
<a name="autopilot-deploy-models-batch-ui"></a>

Autopilot 使用者介面包含實用的下拉式功能表、切換、工具提示等，可協助您完成模型部署。

下列步驟顯示如何部署 Autopilot 實驗的模型進行批次預測。

1. 在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 登入，然後從導覽窗格選取 **Studio**。

1. 在左側導覽窗格上，選擇 **Studio**。

1. 在**開始使用**下，選取您要在其中啟動 Studio 應用程式的網域。如果您的使用者設定檔只屬於一個網域，您將看不到選取網域的選項。

1. 選取您要啟動 Studio Classic 應用程式的使用者設定檔。如果網域中沒有使用者設定檔，請選取**建立使用者設定檔**。如需更多詳細資訊，請參閱[新增使用者設定檔](https://docs.aws.amazon.com/sagemaker/latest/dg/domain-user-profile-add.html)。

1. 選擇**啟動 Studio**。如果使用者設定檔屬於共用空間，請選擇**開放空間**。

1. SageMaker Studio Classic 主控台開啟時，選擇**啟動 SageMaker Studio Classic** 按鈕。

1. 從左側導覽窗格選取 **AutoML**。

1. 在**名稱**下，選取與您要部署之模型對應的 Autopilot 實驗。隨即會開啟新的 ** Autopilot 任務**索引標籤。

1. 在**模型名稱**區段中，選取您要部署的模型。

1. 選擇**部署模型**。隨即開啟新索引索引標籤。

1. 選擇頁面最上方的**進行批次預測**。

1. 針對**批次轉換工作組態**，請輸入**執行個體類型**、**執行個體計數**和其他選用資訊。

1. 在**輸入資料組態**區段中，開啟下拉式功能表。

   1. 針對 **S3 資料類型**，請選擇 **ManifestFile** 或 **S3Prefix**。

   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 進行批次推論，有三個步驟：

1. **取得候選定義** 

   [InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers) 的候選定義可用來建立 SageMaker AI 模型。

   下列範例顯示如何使用 [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) ]

 下列範例使用**適用於 Python 的AWS SDK (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) 建立模型與轉換任務。