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