

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# デプロイのためにモデルを準備する
<a name="edge-getting-started-step2"></a>

このセクションでは、SageMaker AI と AWS IoT クライアントオブジェクトの作成、事前トレーニング済みの機械学習モデルのダウンロード、Amazon S3 バケットへのモデルのアップロード、SageMaker Neo を使用したターゲットデバイスのモデルのコンパイル、 Edge Manager エージェントでデプロイできるようにモデルをパッケージ化します。

1. **ライブラリをインポートし、クライアントオブジェクトを作成します。**

   このチュートリアルでは AWS SDK for Python (Boto3) 、 を使用して、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 フレームワークによる MobileNet V2 モデルを保存することができます。MobileNet V2 はモバイルアプリケーション向けに最適化された画像分類モデルです。MobileNet V2 の詳細については、[MobileNet GitHub README](https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet) を参照してください。

   Jupyter Notebook に以下を入力し、事前トレーニング済みの 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 ファイル (\$1.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 でモデルをコンパイルする。**

   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、モデルの入力形状、フレームワークの名前、コンパイルしたモデルを保存する Amazon S3 URI、ターゲットエッジデバイスを指定します。

   ```
   # 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
                           }
                       )
   ```