

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 获取 Amazon Rekognition Custom Labels 评估指标 (SDK)
<a name="im-metrics-api"></a>

该[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions)操作允许访问控制台中提供的指标以外的指标。

与控制台一样，通过 `DescribeProjectVersions` 可获取以下指标，这些指标作为测试结果的摘要信息以及每个标签的测试结果：
+ [精度](im-metrics-use.md#im-precision-metric)
+ [召回率](im-metrics-use.md#im-recall-metric)
+ [F1](im-metrics-use.md#im-f1-metric)

系统会返回所有标签的平均阈值和单个标签的阈值。

通过 `DescribeProjectVersions` 还可获取以下用于分类和图像检测（图像上的物体位置）的指标。
+ 用于图像分类的*混淆矩阵*。有关更多信息，请参阅 [查看模型的混淆矩阵](im-confusion-matrix.md)。
+ 用于图像检测的*平均精度均值 (mAP)*。
+ 用于图像检测的*平均召回率均值 (mAR)*。

通过 `DescribeProjectVersions` 还可获取真正例、假正例、假负例和真负例值。有关更多信息，请参阅 [评估模型的指标](im-metrics-use.md)。

F1 总分指标由 `DescribeProjectVersions` 直接返回。其他指标可从存储在 Amazon S3 存储桶中的[访问模型摘要文件](im-summary-file-api.md)和[解释评测清单快照](im-evaluation-manifest-snapshot-api.md)文件获取。有关更多信息，请参阅 [获取摘要文件和评估清单快照 (SDK)](im-access-summary-evaluation-manifest.md)。

**Topics**
+ [访问模型摘要文件](im-summary-file-api.md)
+ [解释评测清单快照](im-evaluation-manifest-snapshot-api.md)
+ [获取摘要文件和评估清单快照 (SDK)](im-access-summary-evaluation-manifest.md)
+ [查看模型的混淆矩阵](im-confusion-matrix.md)
+ [参考：训练结果摘要文件](im-summary-file.md)

# 访问模型摘要文件
<a name="im-summary-file-api"></a>

摘要文件包含有关整个模型的评估结果信息以及每个标签的指标。这些指标包括精度、召回率、F1 分数。此外，还提供了模型的阈值。可从 `DescribeProjectVersions` 返回的 `EvaluationResult` 对象获取摘要文件的位置。有关更多信息，请参阅 [参考：训练结果摘要文件](im-summary-file.md)。

下面是一个示例摘要文件。

```
{
  "Version": 1,
  "AggregatedEvaluationResults": {
    "ConfusionMatrix": [
      {
        "GroundTruthLabel": "CAP",
        "PredictedLabel": "CAP",
        "Value": 0.9948717948717949
      },
      {
        "GroundTruthLabel": "CAP",
        "PredictedLabel": "WATCH",
        "Value": 0.008547008547008548
      },
      {
        "GroundTruthLabel": "WATCH",
        "PredictedLabel": "CAP",
        "Value": 0.1794871794871795
      },
      {
        "GroundTruthLabel": "WATCH",
        "PredictedLabel": "WATCH",
        "Value": 0.7008547008547008
      }
    ],
    "F1Score": 0.9726959470546408,
    "Precision": 0.9719115848331294,
    "Recall": 0.9735042735042735
  },
  "EvaluationDetails": {
    "EvaluationEndTimestamp": "2019-11-21T07:30:23.910943",
    "Labels": [
      "CAP",
      "WATCH"
    ],
    "NumberOfTestingImages": 624,
    "NumberOfTrainingImages": 5216,
    "ProjectVersionArn": "arn:aws:rekognition:us-east-1:nnnnnnnnn:project/my-project/version/v0/1574317227432"
  },
  "LabelEvaluationResults": [
    {
      "Label": "CAP",
      "Metrics": {
        "F1Score": 0.9794344473007711,
        "Precision": 0.9819587628865979,
        "Recall": 0.9769230769230769,
        "Threshold": 0.9879502058029175
      },
      "NumberOfTestingImages": 390
    },
    {
      "Label": "WATCH",
      "Metrics": {
        "F1Score": 0.9659574468085106,
        "Precision": 0.961864406779661,
        "Recall": 0.9700854700854701,
        "Threshold": 0.014450683258473873
      },
      "NumberOfTestingImages": 234
    }
  ]
}
```

# 解释评测清单快照
<a name="im-evaluation-manifest-snapshot-api"></a>

评估清单快照包含有关测试结果的详细信息。快照包含每个预测的置信度评级。此外，还包含图像的实际分类与预测分类的比较（真正例、真负例、假正例或假负例）。

这些文件是快照，因为只包含可用于测试和训练的图像。无法验证的图像（例如格式错误的图像）不包含在清单中。可从 `DescribeProjectVersions` 返回的 `TestingDataResult` 对象获取测试快照的位置。可从 `DescribeProjectVersions` 返回的 `TrainingDataResult` 对象获取训练快照的位置。

快照采用 SageMaker AI Ground Truth 清单输出格式，添加了字段以提供其他信息，例如检测的二进制分类结果。以下代码段显示了其他字段。

```
"rekognition-custom-labels-evaluation-details": {
    "version": 1,
    "is-true-positive": true,
    "is-true-negative": false,
    "is-false-positive": false,
    "is-false-negative": false,
    "is-present-in-ground-truth": true
    "ground-truth-labelling-jobs": ["rekognition-custom-labels-training-job"]
}
```
+ *version*：清单快照中 `rekognition-custom-labels-evaluation-details` 字段格式的版本。
+ *is-true-positive...* — 根据置信度分数与标签的最低阈值的比较结果对预测进行二进制分类。
+ *is-present-in-ground-trut* h — 如果模型所做的预测存在于用于训练的地面真相信息中，则为 True，否则为 false。该值不是基于置信度分数是否超过模型计算的最小阈值确定的。
+ *ground-truth-labeling-jobs*— 清单行中用于训练的地面真相字段列表。

有关 SageMaker AI Ground Truth 清单格式的信息，请参阅[输出](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-data-output.html)。

下面是一个示例测试清单快照，其中显示了用于图像分类和物体检测的指标。

```
// For image classification
{
  "source-ref": "s3://amzn-s3-demo-bucket/dataset/beckham.jpeg",
  "rekognition-custom-labels-training-0": 1,
  "rekognition-custom-labels-training-0-metadata": {
    "confidence": 1.0,
    "job-name": "rekognition-custom-labels-training-job",
    "class-name": "Football",
    "human-annotated": "yes",
    "creation-date": "2019-09-06T00:07:25.488243",
    "type": "groundtruth/image-classification"
  },
  "rekognition-custom-labels-evaluation-0": 1,
  "rekognition-custom-labels-evaluation-0-metadata": {
    "confidence": 0.95,
    "job-name": "rekognition-custom-labels-evaluation-job",
    "class-name": "Football",
    "human-annotated": "no",
    "creation-date": "2019-09-06T00:07:25.488243",
    "type": "groundtruth/image-classification",
    "rekognition-custom-labels-evaluation-details": {
      "version": 1,
      "ground-truth-labelling-jobs": ["rekognition-custom-labels-training-job"],
      "is-true-positive": true,
      "is-true-negative": false,
      "is-false-positive": false,
      "is-false-negative": false,
      "is-present-in-ground-truth": true
    }
  }
}


// For object detection
{
  "source-ref": "s3://amzn-s3-demo-bucket/dataset/beckham.jpeg",
  "rekognition-custom-labels-training-0": {
    "annotations": [
      {
        "class_id": 0,
        "width": 39,
        "top": 409,
        "height": 63,
        "left": 712
      },
      ...
    ],
    "image_size": [
      {
        "width": 1024,
        "depth": 3,
        "height": 768
      }
    ]
  },
  "rekognition-custom-labels-training-0-metadata": {
    "job-name": "rekognition-custom-labels-training-job",
    "class-map": {
      "0": "Cap",
      ...
    },
    "human-annotated": "yes",
    "objects": [
      {
        "confidence": 1.0
      },
      ...
    ],
    "creation-date": "2019-10-21T22:02:18.432644",
    "type": "groundtruth/object-detection"
  },
  "rekognition-custom-labels-evaluation": {
    "annotations": [
      {
        "class_id": 0,
        "width": 39,
        "top": 409,
        "height": 63,
        "left": 712
      },
      ...
    ],
    "image_size": [
      {
        "width": 1024,
        "depth": 3,
        "height": 768
      }
    ]
  },
  "rekognition-custom-labels-evaluation-metadata": {
    "confidence": 0.95,
    "job-name": "rekognition-custom-labels-evaluation-job",
    "class-map": {
      "0": "Cap",
      ...
    },
    "human-annotated": "no",
    "objects": [
      {
        "confidence": 0.95,
        "rekognition-custom-labels-evaluation-details": {
          "version": 1,
          "ground-truth-labelling-jobs": ["rekognition-custom-labels-training-job"],
          "is-true-positive": true,
          "is-true-negative": false,
          "is-false-positive": false,
          "is-false-negative": false,
          "is-present-in-ground-truth": true
        }
      },
      ...
    ],
    "creation-date": "2019-10-21T22:02:18.432644",
    "type": "groundtruth/object-detection"
  }
}
```

# 获取摘要文件和评估清单快照 (SDK)
<a name="im-access-summary-evaluation-manifest"></a>

要获得训练结果，请致电[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions)。有关示例代码，请参阅[描述模型 (SDK)](md-describing-model-sdk.md)。

这些指标的位置将在 `DescribeProjectVersions` 的 `ProjectVersionDescription` 响应中返回。
+ `EvaluationResult`：摘要文件的位置。
+ `TestingDataResult`：用于测试的评估清单快照的位置。

F1 分数和摘要文件位置将在 `EvaluationResult` 中返回。例如：

```
"EvaluationResult": {
                "F1Score": 1.0,
                "Summary": {
                    "S3Object": {
                        "Bucket": "echo-dot-scans",
                        "Name": "test-output/EvaluationResultSummary-my-echo-dots-project-v2.json"
                    }
                }
            }
```

评估清单快照存储在您在[训练模型（SDK）](training-model.md#tm-sdk)中指定的 ` --output-config` 输入参数中指定的位置。

**注意**  
`BillableTrainingTimeInSeconds` 中会返回您需要付费的训练时长（以秒为单位）。

有关 Amazon Rekognition Custom Labels 返回的指标的信息，请参阅[获取 Amazon Rekognition Custom Labels 评估指标 (SDK)](im-metrics-api.md)。

# 查看模型的混淆矩阵
<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>

下表是 Rooms [图像分类](getting-started.md#gs-image-classification-example)示例项目的混淆矩阵。列标题是分配给测试图像的标签（ground truth 标签）。行标题是模型为测试图像预测的标签。每个单元格是对标签（行）应为 ground truth 标签（列）的预测的百分比。例如，对浴室的预测有 67% 被正确地标注为浴室。33% 的浴室被错误地标注为厨房。当预测的标签与 ground truth 标签匹配时，高性能模型具有高单元格值。可以将这些看作是从第一个预测和 ground truth 标签到最后一个预测和 ground truth 标签的对角线。如果单元格值为 0，则表示对单元格的预测标签应为单元格的 ground truth 标签的预测为 0。

**注意**  
由于模型是不确定的，您通过训练 Rooms 项目获得的混淆矩阵单元格值可能与下表不同。

混淆矩阵确定了需要关注的领域。例如，混淆矩阵显示，模型有 50% 的时间将衣柜与卧室混淆。在这种情况下，您就应该在训练数据集中添加更多衣柜和卧室的图像。此外，还要检查现有的衣柜和卧室图像是否被正确标注。这应该有助于模型更好地区分这两个标签。要向数据集中添加更多图像，请参阅[向数据集中添加更多图像](md-add-images.md)。

虽然混淆矩阵很有帮助，但考虑其他指标也很重要。例如，100% 的预测正确找到了 floor\$1plan 标签，这表明性能优异。但是，测试数据集只有 2 张带有 floor\$1plan 标签的图像。它还有 11 张带有 living\$1space 标签的图像。这种不平衡也存在于训练数据集中（13 张 living\$1space 图像和 2 张衣柜图像）。要获得更准确的评估，请通过添加更多代表不足的标签的图像（本示例中的平面图）来平衡训练和测试数据集。要获取每个标签的测试图像数量，请参阅[获取评估指标（控制台）](im-access-training-results.md)。

下表是一个示例混淆矩阵，将预测标签（在 y 轴上）与实际情况标签进行了比较：


| 预测标签 | backyard | bathroom | bedroom | closet | entry\$1way | floor\$1plan | front\$1yard | kitchen | living\$1space | patio | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| backyard | 75% | 0% | 0% | 0% | 0% | 0% | 33% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| bathroom | 0% | 67% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| bedroom | 0% | 0% | 82% | 50% | 0% | 0% | 0% | 0% | 9% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| closet | 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% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| kitchen | 0% | 33% | 0% | 0% | 0% | 0% | 0% | 88% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| living\$1space | 0% | 0% | 18% | 0% | 67% | 0% | 0% | 12% | 91% | 33% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| patio | 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 CLI 和 AWS SDKs。有关更多信息，请参阅 [步骤 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()
   ```

# 参考：训练结果摘要文件
<a name="im-summary-file"></a>

训练结果摘要包含可用于评估模型的指标。该摘要文件还用于在控制台训练结果页面中显示指标。训练结束后，该摘要文件存储在 Amazon S3 存储桶中。要获取摘要文件，请调用 `DescribeProjectVersion`。有关示例代码，请参阅[获取摘要文件和评估清单快照 (SDK)](im-access-summary-evaluation-manifest.md)。

## 摘要文件
<a name="im-summary-reference"></a>

以下 JSON 采用摘要文件的格式。



**EvaluationDetails （第 3 节）**  
有关训练任务的概要信息。其中包括模型所属项目的 ARN (`ProjectVersionArn)`、训练结束的日期和时间、评估的模型版本 (`EvaluationEndTimestamp`) 以及训练期间检测到的标签列表 (`Labels`)。此外，还包括用于训练 (`NumberOfTrainingImages`) 和评估 (`NumberOfTestingImages`) 的图像数量。

**AggregatedEvaluationResults （第 1 节）**  
可以结合使用 `AggregatedEvaluationResults` 与测试数据集来评估经过训练的模型的整体性能。包括 `Precision`、`Recall` 和 `F1Score` 指标的汇总指标。对于物体检测（图像上的物体位置），将返回 `AverageRecall` (mAR) 和 `AveragePrecision` (mAP) 指标。对于分类（图像中物体的类型），将返回混淆矩阵指标。

**LabelEvaluationResults （第 2 节）**  
可以使用 `labelEvaluationResults` 来评估单个标签的性能。这些标签按各标签的 F1 分数排序。包含的指标有 `Precision`、`Recall`、`F1Score` 和 `Threshold`（用于分类）。

文件名格式如下：`EvaluationSummary-ProjectName-VersionName.json`。

```
{
  "Version": "integer",
  // section-3
  "EvaluationDetails": {
    "ProjectVersionArn": "string",
    "EvaluationEndTimestamp": "string",
    "Labels": "[string]",
    "NumberOfTrainingImages": "int",
    "NumberOfTestingImages": "int"
  },
  // section-1
  "AggregatedEvaluationResults": {
    "Metrics": {
      "Precision": "float",
      "Recall": "float",
      "F1Score": "float",
      // The following 2 fields are only applicable to object detection
      "AveragePrecision": "float",
      "AverageRecall": "float",
      // The following field is only applicable to classification
      "ConfusionMatrix":[
        {
          "GroundTruthLabel": "string",
          "PredictedLabel": "string",
          "Value": "float"
        },
        ...
      ],
    }
  },
  // section-2
  "LabelEvaluationResults": [
    {
      "Label": "string",
      "NumberOfTestingImages", "int",
      "Metrics": {
        "Threshold": "float",
        "Precision": "float",
        "Recall": "float",
        "F1Score": "float"
      },
    },
    ...
  ]
}
```