

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# Autopilot 模型部署和预测
<a name="autopilot-deploy-models"></a>

本 Amazon A SageMaker utopilot 指南包括模型部署、设置实时推理以及使用批处理作业运行推理的步骤。

在训练了 Autopilot 模型之后，您可以部署这些模型并通过两种方式之一来获取预测：

1. 使用 [为实时推理部署模型](autopilot-deploy-models-realtime.md) 设置端点并以交互方式获取预测。实时推理非常适合有实时、交互式、低延迟要求的推理工作负载。

1. 使用 [运行批量推理作业](autopilot-deploy-models-batch.md) 对整个数据集上的观察数据批次并行进行预测。对于大型数据集或者在您不需要立即响应模型预测请求时，批量推理是很好的选择。

**注意**  
避免产生不必要的费用：当您不再需要模型部署时创建的端点和资源时，可以删除这些资源。有关按地区划分的实例定价的信息，请参阅 [Amazon SageMaker 定价](https://aws.amazon.com/sagemaker/pricing/)。

# 为实时推理部署模型
<a name="autopilot-deploy-models-realtime"></a>

实时推理非常适合有实时、交互式、低延迟要求的推理工作负载。此部分演示如何使用实时推理，以交互方式从模型获取预测。

要部署在 Autopilot 实验中生成最佳验证指标的模型，您有多种选择。例如，在 SageMaker Studio Classic 中使用自动驾驶仪时，您可以自动或手动部署模型。您也可以 SageMaker APIs 使用手动部署自动驾驶模型。

以下选项卡显示了用于部署模型的三个选项。这些说明假定您已在 Autopilot 中创建了模型。如果您还没有模型，请参阅 [使用 AutoML API 为表格数据创建回归或分类作业](autopilot-automate-model-development-create-experiment.md)。要查看每个选项的示例，请打开各个选项卡。

## 使用 Autopilot 用户界面 (UI) 进行部署
<a name="autopilot-deploy-models-realtime-ui"></a>

Autopilot UI 包含有用的下拉菜单、切换开关、工具提示等，可帮助您浏览模型部署。您可以使用以下过程之一进行部署：自动或手动。
+ **自动部署**：自动将 Autopilot 实验中的最佳模型部署到端点

  1. 在 SageMaker Studio 经典版中@@ [创建实验](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development-create-experiment.html)。

  1. 将**自动部署**值切换为**是**。
**注意**  
**如果区域中端点实例的默认资源配额或您的客户配额过于有限，则自动部署会失败。**在超参数优化 (HPO) 模式下，您需要至少两个 ml.m5.2xlarge 实例。在组合模式下，您需要至少一个 ml.m5.12xlarge 实例。如果您遇到与配额相关的故障，可以[请求提高 SageMaker AI 终端节点实例的服务限制](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)。
+ **手动部署**：手动将 Autopilot 实验得到的最佳模型部署到端点

  1. 在 SageMaker Studio 经典版中@@ [创建实验](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development-create-experiment.html)。

  1. 将**自动部署**值切换为**否**。

  1. 在**模型名称**下选择要部署的模型。

  1. 选择排行榜右侧的橙色**部署和高级设置**按钮。这将打开一个新选项卡。

  1. 配置端点名称、实例类型和其他可选信息。

  1.  选择橙色的**部署模型**以部署到端点。

  1. [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)通过导航到终端节点部分，查看终端节点创建过程的进度。该部分位于导航面板的**推理**下拉菜单中。

  1. 在终端节点状态从 “**创建**中” 更改为（如下所示）后 **InService**，返回 Studio Classic 并调用该终端节点。  
![\[SageMaker AI 控制台：终端节点页面，用于创建终端节点或检查终端节点状态。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/autopilot/autopilot-check-progress.PNG)

## 使用部署 SageMaker APIs
<a name="autopilot-deploy-models-api"></a>

您还可以使用 **API 调用**部署模型来获得实时推理。本节使用 AWS Command Line Interface (AWS CLI) 代码片段展示了此过程的五个步骤。

有关 AWS CLI 命令和 AWS 适用于 Python 的 SDK (boto3) 的完整代码示例，请直接按照以下步骤打开选项卡。

1. **获取候选项定义**

   从中获取候选容器定义[InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers)。这些候选定义用于创建 A SageMaker I 模型。

   以下示例使用 [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>
   ```

1. **列出候选项**

   以下示例使用 [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. **创建 A SageMaker I 模型**

   使用前面步骤中的容器定义通过 [CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html)AP SageMaker I 创建 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. **创建端点配置** 

   以下示例使用 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html)API 创建终端节点配置。以以下 AWS CLI 命令为例。

   ```
   aws sagemaker create-endpoint-config --endpoint-config-name '<your-custom-endpoint-config-name>' \
                       --production-variants '<list-of-production-variants>' \
                       --region '<region>'
   ```

1. **创建端点** 

   以下 AWS CLI 示例使用 [CreateEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html)API 创建终端节点。

   ```
   aws sagemaker create-endpoint --endpoint-name '<your-custom-endpoint-name>' \
                       --endpoint-config-name '<endpoint-config-name-you-just-created>' \
                       --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. **调用端点** 

   以下命令结构调用端点以进行实时推理。

   ```
   aws sagemaker invoke-endpoint --endpoint-name '<endpoint-name>' \ 
                     --region '<region>' --body '<your-data>' [--content-type] '<content-type>' <outfile>
   ```

以下选项卡包含使用 AWS SDK for Python (boto3) 或 AWS CLI部署模型的完整代码示例。

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

1. 使用以下代码示例可**获取候选项定义**。

   ```
   import sagemaker 
   import boto3
   
   session = sagemaker.session.Session()
   
   sagemaker_client = boto3.client('sagemaker', region_name='us-west-2')
   job_name = 'test-auto-ml-job'
   
   describe_response = sm_client.describe_auto_ml_job(AutoMLJobName=job_name)
   # extract the best candidate definition from DescribeAutoMLJob response
   best_candidate = describe_response['BestCandidate']
   # extract the InferenceContainers definition from the caandidate definition
   inference_containers = best_candidate['InferenceContainers']
   ```

1. 使用以下代码示例可**创建模型**。

   ```
   # Create Model
   model_name = 'test-model' 
   sagemaker_role = 'arn:aws:iam:444455556666:role/sagemaker-execution-role'
   create_model_response = sagemaker_client.create_model(
      ModelName = model_name,
      ExecutionRoleArn = sagemaker_role,
      Containers = inference_containers 
   )
   ```

1. 使用以下代码示例可**创建端点配置**。

   ```
   endpoint_config_name = 'test-endpoint-config'
                                                           
   instance_type = 'ml.m5.2xlarge' 
   # for all supported instance types, see 
   # https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProductionVariant.html#sagemaker-Type-ProductionVariant-InstanceType    # Create endpoint config
   
   endpoint_config_response = sagemaker_client.create_endpoint_config(
      EndpointConfigName=endpoint_config_name, 
      ProductionVariants=[
          {
              "VariantName": "variant1",
              "ModelName": model_name, 
              "InstanceType": instance_type,
              "InitialInstanceCount": 1
          }
      ]
   )
   
   print(f"Created EndpointConfig: {endpoint_config_response['EndpointConfigArn']}")
   ```

1. 使用以下代码示例可**创建端点**并部署模型。

   ```
   # create endpoint and deploy the model
   endpoint_name = 'test-endpoint'
   create_endpoint_response = sagemaker_client.create_endpoint(
                                               EndpointName=endpoint_name, 
                                               EndpointConfigName=endpoint_config_name)
   print(create_endpoint_response)
   ```

   使用以下代码示例可**检查端点创建状态**。

   ```
   # describe endpoint creation status
   status = sagemaker_client.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"]
   ```

1. 使用以下命令结构可**调用端点**进行实时推理。

   ```
   # once endpoint status is InService, you can invoke the endpoint for inferencing
   if status == "InService":
     sm_runtime = boto3.Session().client('sagemaker-runtime')
     inference_result = sm_runtime.invoke_endpoint(EndpointName='test-endpoint', ContentType='text/csv', Body='1,2,3,4,class')
   ```

------
#### [ 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", amzn-s3-demo-bucket1
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/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/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", aws-region
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/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'
   ```

   有关详细信息，请参阅[创建模型](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker/create-model.html)。

   此 `create model` 命令会返回类似以下格式的响应：

   ```
   {
       "ModelArn": "arn:aws:sagemaker:us-west-2:1234567890:model/test-sagemaker-model"
   }
   ```

1. 使用以下代码示例可**创建端点配置**。

   ```
   aws sagemaker create-endpoint-config --endpoint-config-name 'test-endpoint-config' \
   --production-variants '[{"VariantName": "variant1", 
                           "ModelName": "test-sagemaker-model",
                           "InitialInstanceCount": 1,
                           "InstanceType": "ml.m5.2xlarge"
                          }]' \
   --region us-west-2
   ```

   `create endpoint` 配置命令会返回类似以下格式的响应：

   ```
   {
       "EndpointConfigArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint-config/test-endpoint-config"
   }
   ```

1. 使用以下代码示例**创建端点**。

   ```
   aws sagemaker create-endpoint --endpoint-name 'test-endpoint' \    
   --endpoint-config-name 'test-endpoint-config' \                 
   --region us-west-2
   ```

   `create endpoint` 命令会返回类似以下格式的响应：

   ```
   {
       "EndpointArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint/test-endpoint"
   }
   ```

   使用以下 [describe-endpoint](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/describe-endpoint.html) CLI 代码示例检查端点部署的进度。

   ```
   aws sagemaker describe-endpoint --endpoint-name 'test-endpoint' --region us-west-2
   ```

   上面的进度检查将返回以下格式的响应。

   ```
   {
       "EndpointName": "test-endpoint",
       "EndpointArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint/test-endpoint",
       "EndpointConfigName": "test-endpoint-config",
       "EndpointStatus": "Creating",
       "CreationTime": 1660251167.595,
       "LastModifiedTime": 1660251167.595
   }
   ```

   将 `EndpointStatus` 更改为 `InService` 后，端点即可用于实时推理。

1. 使用以下命令结构可**调用端点**进行实时推理。

   ```
   aws sagemaker-runtime invoke-endpoint --endpoint-name 'test-endpoint' \
   --region 'us-west-2' \
   --body '1,51,3.5,1.4,0.2' \
   --content-type 'text/csv' \
   '/tmp/inference_output'
   ```

   有关更多选项，请参阅[调用端点](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker-runtime/invoke-endpoint.html)。

------

## 部署来自不同账户的模型
<a name="autopilot-deploy-models-realtime-across-accounts"></a>

您可以从生成模型的原始账户之外的其他账户部署 Autopilot 模型。对于实施跨账户模型部署，本节介绍如何执行以下操作：   向所要部署模型所在的账户（生成账户）授予代入角色的权限。   从部署账户发出对 `DescribeAutoMLJob` 的调用以获取模型信息。   从生成账户授予对模型构件的访问权限。   

1. **向部署账户授予权限** 

   要代入生成账户中的角色，您必须向部署账户授予权限。这允许部署账户描述生成账户中的 Autopilot 作业。

   以下示例将生成账户与可信 `sagemaker-role` 实体结合使用。示例说明如何向 ID 为 111122223333 的部署账户授予，以便代入生成账户角色。

   ```
   "Statement": [
           {
               "Effect": "Allow",
               "Principal": {
                   "Service": [
                       "sagemaker.amazonaws.com"
                   ],
                   "AWS": [ "111122223333"]
               },
               "Action": "sts:AssumeRole"
           }
   ```

   ID 为 111122223333 的新账户现在可以代入生成账户的角色。

   接下来，从部署账户调用 `DescribeAutoMLJob` API 以获取生成账户创建的作业的描述。

   以下代码示例描述了部署账户中的模型。

   ```
   import sagemaker 
   import boto3
   session = sagemaker.session.Session()
   
   sts_client = boto3.client('sts')
   sts_client.assume_role
   
   role = 'arn:aws:iam::111122223333:role/sagemaker-role'
   role_session_name = "role-session-name"
   _assumed_role = sts_client.assume_role(RoleArn=role, RoleSessionName=role_session_name)
   
   credentials = _assumed_role["Credentials"]
   access_key = credentials["AccessKeyId"]
   secret_key = credentials["SecretAccessKey"]
   session_token = credentials["SessionToken"]
   
   session = boto3.session.Session()
           
   sm_client = session.client('sagemaker', region_name='us-west-2', 
                              aws_access_key_id=access_key,
                               aws_secret_access_key=secret_key,
                               aws_session_token=session_token)
   
   # now you can call describe automl job created in account A 
   
   job_name = "test-job"
   response= sm_client.describe_auto_ml_job(AutoMLJobName=job_name)
   ```

1. **向部署账户授予访问权限**，以访问生成账户中的模型构件。

   部署账户只需要访问生成账户中的模型构件以便进行部署。它们位于模型生成期间在原始 `CreateAutoMLJob` API 调用中指定的 [S3 OutputPath](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLOutputDataConfig.html#sagemaker-Type-AutoMLOutputDataConfig-S3OutputPath) 中。

   要向部署账户提供对模型构件的访问权限，请选择以下选项之一：

   1. 从生成账户向部署账户[授予访问权限](https://aws.amazon.com/premiumsupport/knowledge-center/cross-account-access-s3/)以访问 `ModelDataUrl`。

      接下来，您需要向部署账户授予代入角色的权限。请按照[实时推理步骤](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-deploy-models.html#autopilot-deploy-models-realtime)中的说明进行部署。

   1. [将模型工件从生成账户的原始 [S3](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLOutputDataConfig.html#sagemaker-Type-AutoMLOutputDataConfig-S3OutputPath) 复制](https://aws.amazon.com/premiumsupport/knowledge-center/copy-s3-objects-account/)OutputPath到生成账户。

      要授予对模型构件的访问权限，您必须定义 `best_candidate` 模型并将模型容器重新分配给新账户。

      以下示例说明如何定义 `best_candidate` 模型并重新分配 `ModelDataUrl`。

      ```
      best_candidate = automl.describe_auto_ml_job()['BestCandidate']
      
      # reassigning ModelDataUrl for best_candidate containers below
      new_model_locations = ['new-container-1-ModelDataUrl', 'new-container-2-ModelDataUrl', 'new-container-3-ModelDataUrl']
      new_model_locations_index = 0
      for container in best_candidate['InferenceContainers']:
          container['ModelDataUrl'] = new_model_locations[new_model_locations_index++]
      ```

      分配完容器后，请按照[使用部署 SageMaker APIs](#autopilot-deploy-models-api)中的步骤进行部署。

要在实时推理中构建负载，请参阅笔记本示例来[定义测试负载](https://aws.amazon.com/getting-started/hands-on/machine-learning-tutorial-automatically-create-models)。要从 CSV 文件创建负载并调用端点，请参阅[自动创建机器学习模型](https://aws.amazon.com/getting-started/hands-on/create-machine-learning-model-automatically-sagemaker-autopilot/#autopilot-cr-room)中的**使用模型进行预测**部分。

# 运行批量推理作业
<a name="autopilot-deploy-models-batch"></a>

批量预测也称为离线推理，可根据一批观察数据生成模型预测。对于大型数据集或者在您不需要立即响应模型预测请求时，批量推理是很好的选择。与之对比的是，在线推理（[实时推理](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-deploy-models.html#autopilot-deploy-models-realtime)）会实时生成预测。你可以使用 Python SDK、Autopilot 用户界面 (UI)、[SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/) ([boto3) 或 () 从自动驾驶模型中AWS 进行](https://aws.amazon.com/sdk-for-python/)批量推断。 AWS Command Line Interface [AWS CLI](https://docs.aws.amazon.com/cli/)

以下选项卡显示了部署模型的三个选项：使用 APIs、Autopilot UI 或使用从不同的账户 APIs 进行部署。这些说明假定您已在 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. 选择要为其启动 Studio Classic 应用程序的用户配置文件。如果域中没有用户配置文件，请选择**创建用户配置文件**。有关更多信息，请参阅[添加用户配置文件](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 数据类型**，请选择**ManifestFile**或 **S3** Prefix。

   1. **对于 “**分割” 类型**，选择 “**线路**”、“**录音**” **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 APIs
<a name="autopilot-deploy-models-batch-steps"></a>

要使用 SageMaker APIs 进行批量推理，需要三个步骤：

1. **获取候选项定义** 

   中的候选定义[InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers)用于创建 A SageMaker I 模型。

   以下示例说明如何使用 [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. **创建 A SageMaker I 模型**

   要使用 [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. **创建 A SageMaker I 转换作业** 

   以下示例使用 [CreateTransformJob](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-transform-job.html)AP SageMaker I 创建 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 SD AWS K、Python SDK (boto3) 和. AWS CLI

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

以下示例使用 **[SageMaker Python 开发工具包](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 APIs](#autopilot-deploy-models-batch-steps)中的步骤创建模型和转换作业。