

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

# 準備您的模型以進行部署
<a name="edge-getting-started-step2"></a>

在本節中，您將建立 SageMaker AI 和 AWS IoT 用戶端物件、下載預先訓練的機器學習模型、將模型上傳至 Amazon S3 儲存貯體、使用 SageMaker Neo 編譯目標裝置的模型，以及封裝模型，以便使用 Edge Manager 代理程式進行部署。

1. **匯入程式庫並建立用戶端物件。**

   本教學課程使用 適用於 Python (Boto3) 的 AWS SDK 建立用戶端，以與 SageMaker AI、Amazon S3 和 互動 AWS IoT。

   導入 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)
   ```

   定義變數並將您為 SageMaker AI 和 AWS IoT 建立的角色 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 AWS IoT. 
   # Note: The name must start with 'SageMaker'
   iot_role_arn = "arn:aws:iam::{{<account>:role/SageMaker*}}"
   ```

1. **訓練機器學習模型。**

   如需有關如何使用 SageMaker AI 訓練機器學習模型的詳細資訊，請參閱[使用 Amazon SageMaker 訓練模型](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html)。您可以選擇性地將本機訓練的模型直接上傳到 Amazon S3 URI 儲存貯體。

   如果您還沒有模型，您可以使用預先訓練的模型來執行本教學課程的後續步驟。例如，您可以從 TensorFlow 架構中儲存行動網 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` 來完成
在本教學課程中，請使用 TensorFlow 2.4 或更低版本。

   模型將被儲存到 `mobilenet_v2.h5` 檔案中。在封裝模型之前，您必須先使用 SageMaker Neo 編譯模型。請參閱[支援的架構、裝置、系統和架構](neo-supported-devices-edge.md)以檢查您的 TensorFlow 版本 (或其他選擇的架構) 目前 SageMaker Neo 是否支援。

   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 儲存貯體中。下列範例使用 AWS CLI 命令，將模型上傳到您先前在稱為*模型*的目錄中建立的 Amazon S3 儲存貯體。在 Jupyter 筆記本中輸入以下內容：

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

1. **使用 SageMaker Neo 編譯您的模型。**

   使用適用於 Edge 裝置的 SageMaker Neo 編譯您的機器學習模型。您需要知道儲存訓練模型的 Amazon S3 儲存貯體 URI、用於訓練模型的機器學習架構、模型輸入的形狀以及目標裝置。

   對於移動網 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、模型的輸入形狀、架構的名稱、您要 SageMaker AI 儲存已編譯模型的 Amazon S3 URI，以及您的 Edge 裝置目標。

   ```
   # 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 主控台建立 Edge 封裝任務。

   您需要提供用於 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 編譯模型。提供 Edge 封裝任務的名稱，以及您為編譯任務提供的名稱 (在此範例中，它會儲存在變數 `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
                           }
                       )
   ```