Amazon Lookout for Visionで異常検出 その2(Python3.6)

はじめに

Amazon AI by ナレコム アドベントカレンダー 2020 の20日目の記事です。

前回の Amazon Lookout for Visionで異常検出 その1 では、AWSコンソール上でAmazon Lookout for Visionの異常検出プロジェクトを作成し、学習とトライアル検出を行いました。

今回は、boto3を用いて作成したモデルをホスティングし、推論を行ってみましょう。

開発環境

  • AWS CLI 2.1.13
  • boto3 1.16.40
  • Python 3.6
  • Windows PC

導入

IAMユーザーの作成、 AWS CLI & SDKs の設定 、AmazonLookoutVisionFullAccessのアクセス権限を与えます。AmazonLookoutVisionFullAccessポリシーが見つからなかったので、作成しました。

image.png
AWS CLIとboto3を更新しておきましょう。

Windows での AWS CLI バージョン 2 のインストール、更新、アンインストール

1pip install -U boto3

Start

作成したモデルを開始します。プロジェクト名(test)とモデルのバージョン(1)を指定します。

1start_model.py2#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.34import boto356def start_model(project_name, model_version, min_inference_units):78    client=boto3.client('lookoutvision')910    try:1112# Start the model1314        print('Starting model version ' + model_version  + ' for project ' + project_name )15        response=client.start_model(ProjectName=project_name,16            ModelVersion=model_version,17            MinInferenceUnits=min_inference_units)18        print('Status: ' + response['Status'])1920    except Exception as e:21        print(e)2223    print('Done...')2425def main():26    project='test'27    model_version='1'28    min_inference_units=1 29    start_model(project, model_version, min_inference_units)3031if __name__ == "__main__":32    main()

状態が「STARTING_HOSTING」となります。

1$ python start_model.py2Starting model version 1 for project test3Status: STARTING_HOSTING4Done...

Describe

モデルを開始したら、状態を確認しましょう。

1describe_model.py2#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.34import boto35import json67def describe_models(project_name):89    client=boto3.client('lookoutvision')1011    try:12        #list models13        response=client.list_models(ProjectName=project_name)14        print('Project: ' + project_name)15        for model in response['Models']:16            print('Version: ' + model['ModelVersion'])17            print('ARN: ' + model['ModelArn'])18            if 'Description' in model:19                print('Description: ' + model['Description'])20            print('Status: ' + model['Status'])21            print('Status Message: ' + model['StatusMessage'])2223# get model description2425            model_description=client.describe_model(ProjectName=project_name,ModelVersion=model['ModelVersion'])26            print('Status: ' + model_description['ModelDescription']['Status'])27            print('Message: ' + model_description['ModelDescription']['StatusMessage'])2829            if 'Performance' in model_description['ModelDescription']:30                print('Recall: ' + str(model_description['ModelDescription']['Performance']['Recall']))31                print('Precision: ' + str(model_description['ModelDescription']['Performance']['Precision']))3233            if 'OutputConfig' in model_description['ModelDescription']:34                print('Output config: ' + str(model_description['ModelDescription']['OutputConfig']))35            print()3637        print('Done...')3839    except Exception as e:40        print(e)        4142def main():43    project_name='test'44    describe_models(project_name)4546if __name__ == "__main__":47    main()

状態が「STARTING_HOSTING」となっています。

1$ python describe_model.py2Project: test3Version: 14ARN: arn:aws:lookoutvision:us-east-1:xxxxxxxxxxxx:model/test/15Status: STARTING_HOSTING6Status Message: Hosting starting.7Status: STARTING_HOSTING8Message: Hosting starting.9Recall: 0.909090936183929410Precision: 0.90909093618392941112Output config: {'S3Location': {'Bucket': 'lookoutvision-us-east-1-xxxxxxxxxx', 'Prefix': 'project/test/model/'}}1314Done...

「HOSTED」になれば使用可能です。

1Project: test2Version: 13ARN: arn:aws:lookoutvision:us-east-1:xxxxxxxxxxxx:model/test/14Status: HOSTED5Status Message: The model is running6Status: HOSTED7Message: The model is running8Recall: 0.90909093618392949Precision: 0.90909093618392941011Output config: {'S3Location': {'Bucket': 'lookoutvision-us-east-1-xxxxxxxxxx', 'Prefix': 'project/test/model/'}}1213Done...

もしモデルが停止していた場合は、「TRAINED」となっています。

1$ python describe_model.py2Project: test3Version: 14ARN: arn:aws:lookoutvision:us-east-1:xxxxxxxxxxxx:model/test/15Status: TRAINED6Status Message: The model is ready for hosting7Status: TRAINED8Message: The model is ready for hosting9Recall: 0.909090936183929410Precision: 0.90909093618392941112Output config: {'S3Location': {'Bucket': 'lookoutvision-us-east-1-xxxxxxxxxx', 'Prefix': 'project/test/model/'}}1314Done...

Detect

モデルの状態が「HOSTED」になったら、推論してみましょう。これらの画像をテストしました。

異常(capsule/test/squeeze/001.png) 正常(capsule/test/good/022.png)
000.png 022.png
1detect.py2#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.34import boto356def detect_anomalies(project_name,model_version,photo):78    client=boto3.client('lookoutvision')910    #Call DetectAnomalies 1112    with open(photo, 'rb') as image:13        response = client.detect_anomalies(ProjectName=project_name, 1415# ContentType='image/jpeg',1617        ContentType='image/png',18        Body=image.read(),19        ModelVersion=model_version)20    print ('Anomalous?: ' + str(response['DetectAnomalyResult']['IsAnomalous']))21    print ('Confidence: ' + str(response['DetectAnomalyResult']['Confidence']))2223def main():24    project_name='test'25    photo="capsule/test/squeeze/000.png"26    model_version='1'2728    anomalous=detect_anomalies(project_name,model_version,photo)2930if __name__ == "__main__":31    main()

正しい予測結果が出ています。

1$ python detect.py2Anomalous?: True3Confidence: 0.9995505213737488
1$ python detect.py2Anomalous?: False3Confidence: 0.9181729555130005

モデルが「STARTING_HOSTING」の状態のときに推論した場合、以下のようなエラーが出ます。

1botocore.errorfactory.ConflictException: An error occurred (ConflictException) when calling the DetectAnomalies operation: Detect cannot be performed when the resource is in STARTING_HOSTING. The resource must be in HOSTED to perform this action

また、AWSコンソールのLookout for Visionのダッシュボードで検出結果を見ることができます。

最初に異常画像を推論した結果です。

image.png

次に正常画像を推論した結果です。ダッシュボードはすぐに更新されます。

image.png

Stop

モデルを停止します。停止するまで料金かかるので注意しましょう。

1stop_model.py2#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.34import boto356def stop_model(project_name, model_version):78    client=boto3.client('lookoutvision')910    try:1112# Stop the model1314        print('Stopping model version ' + model_version  + ' for project ' + project_name )15        response=client.stop_model(ProjectName=project_name,16            ModelVersion=model_version)17        print('Status: ' + response['Status'])1819    except Exception as e:20        print(e)2122    print('Done...')2324def main():25    project='test'26    model_version='1'27    stop_model(project, model_version)2829if __name__ == "__main__":30    main()
1$ python stop_model.py2Stopping model version 1 for project test3Status: STOPPING_HOSTING4Done...

まとめ

前回作ったモデルをboto3を用いてホスティングし、推論してみました。これで運用できそうです。

参考

この記事を書いた人

aws-recipe-user