2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SageMakerの組み込みアルゴリズムで作成したモデルのデプロイと推論を、ローカルのJupyter notebookから実行

Last updated at Posted at 2019-07-22

はじめに

今回はSageMakerの組み込みアルゴリズムで作成したモデルのデプロイ、推論をローカルのJupyter notebook から実行したので、その内容を掲載します。

※今回私は ObjectDetection を利用したモデルで、デプロイ、推論を行います。

前提

  • S3 上に SageMaker の組み込みアルゴリズムで作成したモデルがある。

モデルのデプロイ

まず、aws 上のノートブックでで利用している boto3 と sagemaker をインストールします。

pip install boto3
pip install sagemaker

IAMロールの取得

  • SageMaker と S3 へのアクセスを許可するロール名を入力する。
role = 'ロール名'
  • ロールは以下のコードで一覧表示できます。
import boto3

client = boto3.client('iam')

client.list_roles()

モデルをデプロイ

  • デプロイ自体はSageMaker上のノートブックとコードは変わりません。
  • model_data : 先ほどモデルを保存したパス
  • image : 推論時に利用する Docker イメージ名
    Docker イメージ名は**こちら**から参照してください。
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')

実行結果

    • の後に ! がついたら、モデルのデプロイ完了です。
----------------------------------------------------------------------------------------------------------------!

推論

  • まず、作成したエンドポイント名を確認します。
client = boto3.client('sagemaker')

client.list_endpoints()
  • エンドポイント名を確認したら、推論を行います。
# 推論
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)

エンドポイントの削除

  • エンドポイントは時間単位で課金が発生するので、使い終わったら削除しておきましょう。
client.delete_endpoint(
    EndpointName='先ほど確認したエンドポイント名'
)

最後に

今回は、ローカルのJupyter notebook からモデルのデプロイと、推論を行いました。
SageMaker 上で同じことをしたい、という方はこちらの記事で紹介していますので、参考にしてください。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?