

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

# 在產生的容器設定推論輸出
<a name="autopilot-automate-model-development-container-output"></a>

Autopilot 產生一個有序的 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ContainerDefinition.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ContainerDefinition.html) 清單。這可用來建立要部署在機器學習管線的模型。此模型可用於線上託管與推論。

客戶可以使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListCandidateForAutoMLJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListCandidateForAutoMLJob.html) API 列出推論容器定義。代表最佳候選的推理容器定義清單也可在 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJob.html) 回應找到。

## 迴歸與分類問題類型的推論容器定義
<a name="autopilot-problem-type-container-output"></a>

Autopilot 會產生特定於[訓練模式](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-model-support-validation.html#autopilot-training-mode)及任務[問題類型](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-datasets-problem-types.html#autopilot-problem-types)的推論容器。

### 超參數最佳化 (HPO) 模式的容器定義
<a name="autopilot-problem-type-container-output-hpo"></a>
+ **迴歸**：HPO 會產生兩個容器：

  1. 可將原始特徵轉換為迴歸演算法可以訓練的特徵的特徵工程容器。

  1. 用於轉換特徵並產生資料集的迴歸分數演算法容器。
+ **分類**：HPO 產生三個容器：

  1. 可將原始特徵轉換為分類演算法可以訓練的特徵的特徵工程容器。

  1. 產生機率最高的 `predicted_label` 演算法容器。此容器也可以產生與推論回應中分類結果相關的各種機率。

  1. 執行演算法預測後處理的特徵工程容器。例如，它可以對預測的標籤執行逆轉換，並將其更改為原始標籤。

### 整合模式的容器定義
<a name="autopilot-problem-type-container-output-ensemble"></a>

在組合模式下，迴歸與分類問題類型都只有一個推論容器。此推論容器轉換特徵並根據問題類型產生預測。

## 每個問題類型的推論回應
<a name="autopilot-problem-type-inference-response"></a>

### 分類模型的推論回應
<a name="autopilot-problem-type-inference-response-classification"></a>

對於分類推論容器，您可以使用四個預先定義的機碼來選取推論回應的內容：
+ `predicted_label`: 具有最高可能性的標籤預測正確標籤的標籤，由 Autopilot 確定。
+ `probability`: 
  + **HPO 模型：**用於二進位分類的 `True` 類別的機率。`predicted_label` 用於多類分類的機率。
  + **整合模型：**二進位與多類別分類的機率。`predicted_label`
+ `probabilities`：所有對應類別的機率清單。
+ `labels`：所有標籤的清單。

例如，對於二進位分類問題，如果您傳遞推論回應機組 `['predicted_label', 'probability', 'probabilities', 'labels']`，且輸出回應顯示為 `[1, 0.1, "[0.9, 0.1]", "['1', '0']"]`，則應將其解釋如下：

1. `predicted_label` 等於 `1`， 因為標籤 “1” 的機率較高 (本例為 `0.9`)。

1. 對於 HPO 模型，`probability` 等於 `0.1`，這是 Autopilot 選擇 `positive_class` (本例為 `0`) 的機率。

   對於整合模型，`probability` 等於 `0.9`，即 `predicted_label` 的機率。

1. `probabilities` 列出了 `labels` 中每個標籤的 `probability`。

1. `labels` 是資料集的唯一標籤，其中第二個標籤 (在此例中為 “0”) 是由 Autopilot 選取的 `positive_class`。

依預設，推理容器設定為僅產生 `predicted_label`。若要選取其他推論內容，您可以更新 `inference_response_keys` 參數以包含最多下列三個環境變數：
+ `SAGEMAKER_INFERENCE_SUPPORTED`：這是為了向您提供有關每個容器支援哪些內容的提示。
+ `SAGEMAKER_INFERENCE_INPUT`：這應該設置為容器在輸入有效負載中期望的機碼。
+ `SAGEMAKER_INFERENCE_OUTPUT`：這應該填充容器輸出的一組機碼。

### HPO 模式下分類模型的推論回應
<a name="autopilot-problem-type-inference-response-classification-hpo"></a>

本節說明如何使用超參數最佳化 (HPO) 模式，從分類模型設定推論回應。

若要在 HPO 模式選擇推論回應內容，請將 `SAGEMAKER_INFERENCE_INPUT` 與 `SAGEMAKER_INFERENCE_OUTPUT` 變數新增至在 HPO 模式中針對分類問題產生的第二個和第三個容器。

第二個容器 (演算法) 支援的機碼是預測標籤、機率與可能性。請注意，故意不將 `labels` 新增至 `SAGEMAKER_INFERENCE_SUPPORTED`。

第三個分類模型容器支援的機碼為 `predicted_label`、`labels`、`probability` 與 `probabilities`。因此，`SAGEMAKER_INFERENCE_SUPPORTED` 環境會包含這些機碼的名稱。

若要更新推論容器的定義以接收 `predicted_label` 與 `probability`，請使用下列程式碼範例。

```
containers[1]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})
containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_INPUT': 'predicted_label, probability'})
containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})
```

下列程式碼範例會更新推論容器的定義，以接收 `predicted_label`、`probabilities`、與 `labels`。請勿將 `labels` 傳遞給第二個容器 (演算法容器)，因為它是由第三個容器所獨立產生。

```
containers[1]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label,probabilities'})
containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_INPUT': 'predicted_label,probabilities'})
containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probabilities,labels'})
```

下列可摺疊章節提供適用於 Python 的 SageMaker SDK 的 適用於 Python (Boto3) 的 AWS SDK 和 程式碼範例。每個區段都展示了如何在 HPO 模式為相對應的程式碼範例選擇推論回應的內容。

#### 適用於 Python (Boto3) 的 AWS SDK
<a name="autopilot-problem-type-inference-response-classification-hpo-boto3"></a>

```
import boto3

sm_client = boto3.client('sagemaker', region_name='{{<Region>}}')

role = '{{<IAM role>}}'
input_data = '{{<S3 input uri>}}'
output_path = '{{<S3 output uri>}}'

best_candidate = sm_client.describe_auto_ml_job(AutoMLJobName='{{<AutoML Job Name>}}')['BestCandidate']
best_candidate_containers = best_candidate['InferenceContainers']
best_candidate_name = best_candidate['{{CandidateName}}']

best_candidate_containers[1]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})
best_candidate_containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_INPUT': 'predicted_label, probability'})
best_candidate_containers[2]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})

# create model
reponse = sm_client.create_model(
    ModelName = '{{<Model Name>}}',
    ExecutionRoleArn = role,
    Containers = best_candidate_containers
)

# Lauch Transform Job
response = sm_client.create_transform_job(
    TransformJobName='{{<Transform Job Name>}}',
    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.m4.xlarge}}',
        'InstanceCount': 1,
    },
)
```

#### SageMaker SDK for Python
<a name="autopilot-problem-type-inference-response-classification-hpo-sdk"></a>

```
from sagemaker import AutoML

aml = AutoML.attach(auto_ml_job_name='{{<AutoML Job Name>}}')
aml_best_model = aml.create_model(name='{{<Model Name>}}',
                                  candidate=None,
                                  inference_response_keys**=['probabilities', 'labels'])

aml_transformer = aml_best_model.transformer(accept='text/csv',
                                            assemble_with='Line',
                                            instance_type='{{ml.m5.xlarge}}',
                                            instance_count=1,)

aml_transformer.transform('{{<S3 input uri>}}',
                          content_type='text/csv',
                          split_type='Line',
                          job_name='{{<Transform Job Name>}}',
                          wait=True)
```

### 整合模式下分類模型的推論回應
<a name="autopilot-problem-type-inference-response-classification-ensemble"></a>

本節說明如何使用整合模式設定分類模型的推論回應。

在**整合模式**，若要選擇推論回應的內容，請更新 `SAGEMAKER_INFERENCE_OUTPUT` 環境變數。

分類模型容器支援的機碼為 `predicted_label`、`labels`、`probability`、與 `probabilities`。這些機碼包含在 `SAGEMAKER_INFERENCE_SUPPORTED` 環境。

若要更新推論容器定義以接收 `predicted_label` 與 `probability`，請參閱下列程式碼範例。

```
containers[0]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})
```

下列可折疊部分提供了用於在整合模式選擇推論回應內容的程式碼範例。此範例使用 適用於 Python (Boto3) 的 AWS SDK。

#### 適用於 Python (Boto3) 的 AWS SDK
<a name="autopilot-problem-type-inference-response-classification-ensembling-boto3"></a>

```
import boto3
sm_client = boto3.client('sagemaker', region_name='{{<Region>}}')

role = '{{<IAM role>}}'
input_data = '{{<S3 input uri>}}'
output_path = '{{<S3 output uri>}}' 

best_candidate = sm_client.describe_auto_ml_job(AutoMLJobName='{{<AutoML Job Name>}}')['BestCandidate']
best_candidate_containers = best_candidate['InferenceContainers']
best_candidate_name = best_candidate['{{CandidateName}}']

*best_candidate_containers[0]['Environment'].update({'SAGEMAKER_INFERENCE_OUTPUT': 'predicted_label, probability'})
*
# create model
reponse = sm_client.create_model(
    ModelName = '{{<Model Name>}}',
    ExecutionRoleArn = role,
    Containers = best_candidate_containers
)

# Lauch Transform Job
response = sm_client.create_transform_job(
    TransformJobName='{{<Transform Job Name>}}',
    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.m4.xlarge}}',
        'InstanceCount': 1,
    },
)
```

以下可折疊部分提供了與 HPO 的 SageMaker SDK for Python 範例相同的程式碼範例。為方便起見，它包括在內。

#### SageMaker SDK for Python
<a name="autopilot-problem-type-inference-response-classification-ensembling-sdk"></a>

下列 HPO 程式碼範例使用適用於 SageMaker SDK for Python。

```
from sagemaker import AutoML

aml = AutoML.attach(auto_ml_job_name='<AutoML Job Name>')
aml_best_model = aml.create_model(name='<Model Name>',
                                  candidate=None,
                                  *inference_response_keys**=['probabilities', 'labels'])*

aml_transformer = aml_best_model.transformer(accept='text/csv',
                                            assemble_with='Line',
                                            instance_type='ml.m5.xlarge',
                                            instance_count=1,)

aml_transformer.transform('<S3 input uri>',
                          content_type='text/csv',
                          split_type='Line',
                          job_name='<Transform Job Name>',
                          wait=True)
```