

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

# 为部署模型做好准备
<a name="edge-getting-started-step2"></a>

在本节中，您将创建 SageMaker AI 和 Amazon IoT 客户端对象，下载预先训练的机器学习模型，将模型上传到 Amazon S3 存储桶，使用 SageMaker Neo 为目标设备编译模型，然后打包模型以便可以使用 Edge Manager 代理进行部署。

1. **导入库并创建客户端对象。**

   本教程使用创建用于与 SageMaker AI、Amazon S3 和进行交互的客户端 Amazon IoT。 适用于 Python (Boto3) 的 Amazon SDK 

   导入 Boto3，指定您的区域，然后初始化所需的客户端对象，如以下示例所示：

   ```
   import boto3
   import json
   import time
   
   AWS_REGION = 'us-west-2'# Specify your Region
   bucket = {{'bucket-name'}}
   
   sagemaker_client = boto3.client('sagemaker', region_name=AWS_REGION)
   iot_client = boto3.client('iot', region_name=AWS_REGION)
   ```

   定义变量，并将您 Amazon IoT 为 A SageMaker I 创建的角色 ARN 和字符串分配给它们：

   ```
   # Replace with the role ARN you created for SageMaker
   sagemaker_role_arn = "arn:aws:iam::{{<account>:role/*}}"
   
   # Replace with the role ARN you created for Amazon IoT. 
   # Note: The name must start with 'SageMaker'
   iot_role_arn = "arn:aws:iam::{{<account>:role/SageMaker*}}"
   ```

1. **训练机器学习模型。**

   有关如何[使用 A SageMaker I 训练机器学习模型 SageMaker的更多信息，请参阅使用 Amazon](https://docs.amazonaws.cn/sagemaker/latest/dg/how-it-works-training.html) 训练模型。您可以选择将在本地训练的模型直接上传到 Amazon S3 URI 存储桶中。

   如果您还没有模型，可以在本教程的后续步骤中使用预训练模型。例如，您可以从 TensorFlow 框架中保存 MobileNet V2 模型。 MobileNet V2 是一种针对移动应用程序进行了优化的图像分类模型。有关 MobileNet V2 的更多信息，请参阅[MobileNet GitHub 自述文件](https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet)。

   在 Jupyter 笔记本中键入以下内容以保存预训练 MobileNet 的 V2 模型：

   ```
   # Save the MobileNet V2 model to local storage
      import tensorflow as tf
      model = tf.keras.applications.MobileNetV2()
      model.save(“mobilenet_v2.h5”)
   ```
**注意**  
如果你还没有 TensorFlow 安装，你可以通过运行来安装 `pip install tensorflow=2.4`
本教程使用 2.4 或更低 TensorFlow 版本。

   模型将保存到 `mobilenet_v2.h5` 文件中。在打包模型之前，你需要先使用 SageMaker Neo 编译模型。请参阅[支持的框架、设备、系统和架构](neo-supported-devices-edge.md)，以检查 SageMaker Neo 当前是否支持您的版本 TensorFlow （或其他选择的框架）。

   SageMaker Neo 要求将模型存储为压缩的 TAR 文件。将其重新打包为压缩的 TAR 文件 (\*.tar.gz)：

   ```
   # Package MobileNet V2 model into a TAR file 
      import tarfile
      
      tarfile_name='mobilenet-v2.tar.gz'
      
      with tarfile.open(tarfile_name, mode='w:gz') as archive:
          archive.add('mobilenet-v2.h5')
   ```

1. **将您的模型上传到 Amazon S3。**

   有了机器学习模型后，请将其存储在 Amazon S3 存储桶中。*以下示例使用 Amazon CLI 命令将模型上传到您之前在名为 models 的目录中创建的 Amazon S3 存储桶。*在您的 Jupyter 笔记本中键入以下内容：

   ```
   !aws s3 cp mobilenet-v2.tar.gz s3://{bucket}/models/
   ```

1. **使用 SageMaker Neo 编译您的模型。**

   使用 SageMaker Neo 为边缘设备编译您的机器学习模型。您需要了解存储已训练模型的 Amazon S3 存储桶 URI、用于训练模型的机器学习框架、模型输入的形状以及目标设备。

   对于 MobileNet V2 型号，请使用以下内容：

   ```
   framework = 'tensorflow'
   target_device = 'jetson_nano'
   data_shape = '{"data":[1,3,224,224]}'
   ```

   SageMaker 根据您使用的深度学习框架，Neo 需要特定的模型输入形状和模型格式。有关如何保存模型的更多信息，请参阅[SageMaker Neo 期望什么样的输入数据形状？](neo-compilation-preparing-model.md#neo-job-compilation-expected-inputs)。有关 Neo 支持的设备和框架的更多信息，请参阅[支持的框架、设备、系统和架构](neo-supported-devices-edge.md)。

   使用 `CreateCompilationJob` API 通过 SageMaker Neo 创建编译任务。提供编译任务的名称、 SageMaker AI 角色 ARN、存储模型的 Amazon S3 URI、模型的输入形状、框架的名称、您希望 AI 存储已编译模型的 Amazon S3 UR SageMaker I 以及边缘设备目标。

   ```
   # Specify the path where your model is stored
   model_directory = 'models'
   s3_model_uri = 's3://{}/{}/{}'.format(bucket, model_directory, tarfile_name)
   
   # Store compiled model in S3 within the 'compiled-models' directory
   compilation_output_dir = 'compiled-models'
   s3_output_location = 's3://{}/{}/'.format(bucket, compilation_output_dir)
   
   # Give your compilation job a name
   compilation_job_name = 'getting-started-demo'
   
   sagemaker_client.create_compilation_job(CompilationJobName=compilation_job_name,
                                           RoleArn=sagemaker_role_arn,
                                           InputConfig={
                                               'S3Uri': s3_model_uri,
                                               'DataInputConfig': data_shape,
                                               'Framework' : framework.upper()},
                                           OutputConfig={
                                               'S3OutputLocation': s3_output_location,
                                               'TargetDevice': target_device},
                                           StoppingCondition={'MaxRuntimeInSeconds': 900})
   ```

1. **打包已编译的模型。**

   打包作业采用 SageMaker NEO 编译的模型，并进行必要的更改，以便使用推理引擎 Edge Manager 代理部署模型。要打包模型，请使用 `create_edge_packaging` API 或 SageMaker AI 控制台创建边缘打包作业。

   您需要提供用于 Neo 编译作业的名称、打包作业的名称、角色 ARN（请参阅[设置](edge-getting-started-step1.md)部分）、模型的名称、模型版本以及用于打包作业输出的 Amazon S3 存储桶 URI。请注意，Edge Manager 打包作业名称区分大小写。以下是介绍如何使用 API 创建打包作业的示例。

   ```
   edge_packaging_name='edge-packaging-demo'
   model_name="sample-model"
   model_version="1.1"
   ```

   定义要存储打包模型的 Amazon S3 URI。

   ```
   # Output directory where you want to store the output of the packaging job
   packaging_output_dir = 'packaged_models'
   packaging_s3_output = 's3://{}/{}'.format(bucket, packaging_output_dir)
   ```

   使用 `CreateEdgePackagingJob` 来打包通过 Neo 编译的模型。提供边缘打包作业的名称以及为编译作业提供的名称（在本例中，该名称存储在变量 `compilation_job_name` 中）。还要提供模型的名称、模型的版本（用于帮助您跟踪所使用的模型版本）以及您希望 SageMaker AI 存储打包模型的 S3 URI。

   ```
   sagemaker_client.create_edge_packaging_job(
                       EdgePackagingJobName=edge_packaging_name,
                       CompilationJobName=compilation_job_name,
                       RoleArn=sagemaker_role_arn,
                       ModelName=model_name,
                       ModelVersion=model_version,
                       OutputConfig={
                           "S3OutputLocation": packaging_s3_output
                           }
                       )
   ```