

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

# モデルの混同行列の表示
<a name="im-confusion-matrix"></a>

混同行列を使用すると、モデル内の他のラベルと混同されているラベルを確認できます。混同行列を使用すれば、モデルの改善点に集中することができます。

モデルの評価中、Amazon Rekognition Custom Labels はテストイメージを使用して誤認された (混同した) ラベルを識別することにより、混同行列を作成します。Amazon Rekognition Custom Labels は分類モデルの混同行列のみを作成します。分類行列には、Amazon Rekognition Custom Labels がモデルトレーニング中に作成する概要ファイルからアクセスできます。Amazon Rekognition Custom Labels コンソールでは混同行列を表示できません。

**Topics**
+ [混同行列の使用](#im-using-confusion-matrix)
+ [モデルの混同行列の取得](#im-getting-confusion-matrix)

## 混同行列の使用
<a name="im-using-confusion-matrix"></a>

次の表は、[ルームイメージ分類](getting-started.md#gs-image-classification-example)プロジェクト例の混同行列です。列見出しは、テストイメージに割り当てられたラベル (グラウンドトゥルースラベル) です。行見出しは、テストイメージについてモデルが予測するラベルです。各セルは、グラウンドトゥルースラベル (列) にすべき、ラベル (行) に対する予測のパーセンテージです。例えば、バスルームの予測の 67% はバスルームとして正しくラベル付けされていました。バスルームの 33% はキッチンと誤ってラベル付けされていました。予測ラベルがグラウンドトゥルースラベルと一致する場合、パフォーマンスの高いモデルではセル値が高くなります。これらは、最初から最後の予測ラベルとグラウンドトゥルースラベルを結ぶ対角線として見ることができます。セル値が 0 の場合、セルのグラウンドトゥルースラベルとなる、セルの予測ラベルに対する予測は行われていません。

**注記**  
モデルは確定的ではないため、ルームプロジェクトのトレーニングから得られる混同行列のセル値は、次の表と異なる場合があります。

混同行列は焦点を当てる領域を特定します。例えば、混同行列では、50% の期間にクローゼットがベッドルームと混同されていることが示されています。このような場合は、クローゼットとベッドルームのイメージをトレーニングデータセットにさらに追加する必要があります。また、既存のクローゼットとベッドルームのイメージに正しいラベルが付けられていることも確認してください。これにより、2 つのラベルをモデルが区別しやすくなるはずです。データセットにイメージを追加する方法については、「[データセットへのイメージの追加](md-add-images.md)」を参照してください。

混同行列も役立ちますが、他のメトリクスも考慮することも重要です。例えば、予測の 100% が floor\$1plan ラベルを正しく見つけており、これはパフォーマンスが優れていることを示しています。ただし、テストデータセットには floor\$1plan ラベルの付いたイメージが 2 つしかありません。また、living\$1space というラベルの付いたイメージが 11 個あります。この不均衡はトレーニングデータセット (living\$1space イメージ 13 枚とクローゼットイメージ 2 枚) にもあります。より正確な評価を行うには、過小評価されているラベル (この例ではフロアプラン) のイメージをさらに追加して、トレーニングデータセットとテストデータセットのバランスを取ります。ラベルごとのテストイメージの数を取得するには、「[評価メトリクスへのアクセス (コンソール)](im-access-training-results.md)」を参照してください。

以下の表は、予測ラベル (y 軸) と正解ラベルを比較した混同行列のサンプルです。


| 予測ラベル | 裏庭 | バスルーム | ベッドルーム | クローゼット | entry\$1way | floor\$1plan | front\$1yard | キッチン | living\$1space | パティオ | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 裏庭 | 75% | 0% | 0% | 0% | 0% | 0% | 33% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| バスルーム | 0% | 67% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| ベッドルーム | 0% | 0% | 82% | 50% | 0% | 0% | 0% | 0% | 9% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| クローゼット | 0% | 0% | 0% | 50% | 0% | 0% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| entry\$1way | 0% | 0% | 0% | 0% | 33% | 0% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| floor\$1plan | 0% | 0% | 0% | 0% | 0% | 100% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| front\$1yard | 25% | 0% | 0% | 0% | 0% | 0% | 67% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| キッチン | 0% | 33% | 0% | 0% | 0% | 0% | 0% | 88% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| living\$1space | 0% | 0% | 18% | 0% | 67% | 0% | 0% | 12% | 91% | 33% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| パティオ | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 67% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |

## モデルの混同行列の取得
<a name="im-getting-confusion-matrix"></a>

次のコードでは、[DescribeProjects](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjects) オペレーションと [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) オペレーションを使用してモデルの[概要ファイル](im-summary-file-api.md)を取得しています。次に、概要ファイルを使用してモデルの混同行列を表示します。

**モデル (SDK) の混同行列を表示する方法**

1. まだインストールしていない場合は、 と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 4: AWS CLI と AWS SDKsを設定する](su-awscli-sdk.md)」を参照してください。

1. 次のコードを使用してモデルの混同行列を表示します。次のコマンドライン引数を指定します。
   + `project_name` - 使用するプロジェクトの名前。プロジェクト名は、Amazon Rekognition Custom Labels コンソールのプロジェクトページから取得できます。
   + `version_name` - 使用するモデルのバージョン。バージョン名は、Amazon Rekognition Custom Labels コンソールのプロジェクト詳細ページから取得できます。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   
   Shows how to display the confusion matrix for an Amazon Rekognition Custom labels image
   classification model.
   """
   
   
   import json
   import argparse
   import logging
   import boto3
   import pandas as pd
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def get_model_summary_location(rek_client, project_name, version_name):
       """
       Get the summary file location for a model.
   
       :param rek_client: A Boto3 Rekognition client.
       :param project_arn: The Amazon Resource Name (ARN) of the project that contains the model.
       :param model_arn: The Amazon Resource Name (ARN) of the model.
       :return: The location of the model summary file.
       """
   
       try:
           logger.info(
               "Getting summary file for model %s in project %s.", version_name, project_name)
   
           summary_location = ""
   
           # Get the project ARN from the project name.
           response = rek_client.describe_projects(ProjectNames=[project_name])
   
           assert len(response['ProjectDescriptions']) > 0, \
               f"Project {project_name} not found."
   
           project_arn = response['ProjectDescriptions'][0]['ProjectArn']
   
           # Get the summary file location for the model.
           describe_response = rek_client.describe_project_versions(ProjectArn=project_arn,
                                                                    VersionNames=[version_name])
           assert len(describe_response['ProjectVersionDescriptions']) > 0, \
               f"Model {version_name} not found."
   
           model=describe_response['ProjectVersionDescriptions'][0]
   
           evaluation_results=model['EvaluationResult']
   
           summary_location=(f"s3://{evaluation_results['Summary']['S3Object']['Bucket']}"
                               f"/{evaluation_results['Summary']['S3Object']['Name']}")
   
           return summary_location
   
       except ClientError as err:
           logger.exception(
               "Couldn't get summary file location: %s", err.response['Error']['Message'])
           raise
   
   
   def show_confusion_matrix(summary):
       """
       Shows the confusion matrix for an Amazon Rekognition Custom Labels
       image classification model.
       :param summary: The summary file JSON object.
       """
       pd.options.display.float_format = '{:.0%}'.format
   
       # Load the model summary JSON into a DataFrame.
   
       summary_df = pd.DataFrame(
           summary['AggregatedEvaluationResults']['ConfusionMatrix'])
   
       # Get the confusion matrix.
       confusion_matrix = summary_df.pivot_table(index='PredictedLabel',
                                                 columns='GroundTruthLabel',
                                                 fill_value=0.0).astype(float)
   
       # Display the confusion matrix.
       print(confusion_matrix)
   
   
   def get_summary(s3_resource, summary):
       """
       Gets the summary file.
       : return: The summary file in bytes.
       """
       try:
           summary_bucket, summary_key = summary.replace(
               "s3://", "").split("/", 1)
   
           bucket = s3_resource.Bucket(summary_bucket)
           obj = bucket.Object(summary_key)
           body = obj.get()['Body'].read()
           logger.info(
               "Got summary file '%s' from bucket '%s'.",
               obj.key, obj.bucket_name)
       except ClientError:
           logger.exception(
               "Couldn't get summary file '%s' from bucket '%s'.",
               obj.key, obj.bucket_name)
           raise
       else:
           return body
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       : param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_name", help="The ARN of the project in which the model resides."
       )
       parser.add_argument(
           "version_name", help="The version of the model that you want to describe."
       )
   
   
   def main():
       """
       Entry point for script.
       """
   
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
   
       try:
   
           # Get the command line arguments.
           parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
           add_arguments(parser)
           args = parser.parse_args()
   
           print(
               f"Showing confusion matrix for: {args.version_name} for project {args.project_name}.")
   
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
           s3_resource = session.resource('s3')
   
           # Get the summary file for the model.
           summary_location = get_model_summary_location(rekognition_client, args.project_name,
                                                         args.version_name
                                                         )
           summary = json.loads(get_summary(s3_resource, summary_location))
   
           # Check that the confusion matrix is available.
           assert 'ConfusionMatrix' in summary['AggregatedEvaluationResults'], \
               "Confusion matrix not found in summary. Is the model a classification model?"
   
           # Show the confusion matrix.
           show_confusion_matrix(summary)
           print("Done")
   
       except ClientError as err:
           logger.exception("Problem showing confusion matrix: %s", err)
           print(f"Problem describing model: {err}")
   
       except AssertionError as err:
           logger.exception(
               "Error: %s.\n", err)
           print(
               f"Error: {err}\n")
   
   
   if __name__ == "__main__":
       main()
   ```