はじめに
今回はSageMakerの組み込みアルゴリズムで作成したモデルのデプロイ、推論をローカルのJupyter notebook から実行したので、その内容を掲載します。
※今回私は ObjectDetection を利用したモデルで、デプロイ、推論を行います。
前提
S3 上に SageMaker の組み込みアルゴリズムで作成したモデルがある。
モデルのデプロイ
まず、aws 上のノートブックでで利用している boto3 と sagemaker をインストールします。
1pip install boto32pip install sagemakerIAMロールの取得
SageMaker と S3 へのアクセスを許可するロール名を入力する。
1role = 'ロール名'ロールは以下のコードで一覧表示できます。
1import boto323client = boto3.client('iam')45client.list_roles()モデルをデプロイ
デプロイ自体はSageMaker上のノートブックとコードは変わりません。
model_data : 先ほどモデルを保存したパス
image : 推論時に利用する Docker イメージ名
Docker イメージ名はこちらから参照してください。
1import sagemaker2from sagemaker import get_execution_role3from sagemaker.model import Model45import boto36import json78model = Model(model_data='s3://dog-face/model/model.tar.gz',9 image='501404015308.dkr.ecr.ap-northeast-1.amazonaws.com/object-detection:latest',10 role=role)1112model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')実行結果
– の後に ! がついたら、モデルのデプロイ完了です。
1----------------------------------------------------------------------------------------------------------------!推論
まず、作成したエンドポイント名を確認します。
1client = boto3.client('sagemaker')23client.list_endpoints()エンドポイント名を確認したら、推論を行います。
1#推論2file_name = '推論するファイル名'34with open(file_name, 'rb') as image:5 f = image.read()6 b = bytearray(f)78endpoint_response = boto3.client('sagemaker-runtime').invoke_endpoint(9 EndpointName='先ほど確認したエンドポイント名',10 Body=b,11 ContentType='image/jpeg'12)13results = endpoint_response['Body'].read()14detections = json.loads(results)15print(detections)エンドポイントの削除
エンドポイントは時間単位で課金が発生するので、使い終わったら削除しておきましょう。
1client.delete_endpoint(2 EndpointName='先ほど確認したエンドポイント名'3)最後に
今回は、ローカルのJupyter notebook からモデルのデプロイと、推論を行いました。
SageMaker 上で同じことをしたい、という方は こちら の記事で紹介していますので、参考にしてください。
SageMakerの導入ならナレコムにおまかせください。
日本のAPNコンサルティングパートナーとしては国内初である、Machine Learning コンピテンシー認定のナレコムが導入から活用方法までサポートします。お気軽にご相談ください。