

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

# 改进经过训练的 Amazon Rekognition Custom Labels 模型
<a name="improving-model"></a>

训练完成后，您将评估模型的性能。为了帮助您评估，Amazon Rekognition Custom Labels 会提供每个标签的摘要指标和评估指标。有关可用的指标的信息，请参阅[评估模型的指标](im-metrics-use.md)。要使用指标改进模型，请参阅[改进 Amazon Rekognition Custom Labels 模型](tr-improve-model.md)。



如果对模型的准确性感到满意，则可以开始使用它。有关更多信息，请参阅 [运行经过训练的 Amazon Rekognition Custom Labels 模型](running-model.md)。

**Topics**
+ [评估模型的指标](im-metrics-use.md)
+ [获取评估指标（控制台）](im-access-training-results.md)
+ [获取 Amazon Rekognition Custom Labels 评估指标 (SDK)](im-metrics-api.md)
+ [改进 Amazon Rekognition Custom Labels 模型](tr-improve-model.md)

# 评估模型的指标
<a name="im-metrics-use"></a>

模型训练完毕后，Amazon Rekognition Custom Labels 会返回模型测试的指标，您可以使用这些指标来评估模型的性能。本主题介绍可供您使用的指标，以及如何了解您训练的模型是否运行良好。

Amazon Rekognition Custom Labels 控制台提供以下指标作为训练结果摘要和每个标签的指标：
+ [精度](#im-precision-metric)
+ [召回率](#im-recall-metric)
+ [F1](#im-f1-metric)

我们提供的每个指标都是评估机器学习模型性能的常用指标。Amazon Rekognition Custom Labels 会返回整个测试数据集的测试结果指标，以及每个自定义标签的指标。您还可以查看训练后的自定义模型在测试数据集中每张图像上的表现。有关更多信息，请参阅 [获取评估指标（控制台）](im-access-training-results.md)。

## 评估模型性能
<a name="tr-evaluate-performance"></a>

在测试期间，Amazon Rekognition Custom Labels 会预测测试图像中是否包含自定义标签。置信度分数是一个量化模型预测确定性的值。

如果自定义标签的置信度分数超过阈值，则模型输出将包含此标签。预测可以按以下方式进行分类：
+ *真正例*：Amazon Rekognition Custom Labels 模型可以正确预测测试图像中是否存在自定义标签。也就是说，预测的标签也是该图像的“ground truth”标签。例如，当图像中存在足球时，Amazon Rekognition Custom Labels 会正确返回 soccer ball 标签。
+ *假正例*：Amazon Rekognition Custom Labels 模型无法正确预测测试图像中是否存在自定义标签。也就是说，预测的标签不是该图像的“ground truth”标签。例如，Amazon Rekognition Custom Labels 会返回一个 soccer ball 标签，但该图像的 ground truth 中不包含 soccer ball 标签。
+ *假负例*：Amazon Rekognition Custom Labels 模型并不能预测图像中存在某个自定义标签，但该图像的“ground truth”包含此标签。例如，Amazon Rekognition Custom Labels 不会为包含足球的图像返回“soccer ball”自定义标签。
+ *真负例*：Amazon Rekognition Custom Labels 模型可以正确预测测试图像中不存在某个自定义标签。例如，对于不包含足球的图像，Amazon Rekognition Custom Labels 不会返回 soccer ball 标签。

可通过控制台获取测试数据集中每张图像的真正例、假正例和假负例值。有关更多信息，请参阅 [获取评估指标（控制台）](im-access-training-results.md)。

这些预测结果会用于计算每个标签的以下指标，以及整个测试集的汇总。相同的定义适用于模型在边界框级做出的预测，不同之处在于，所有指标都是针对每个测试图像中的每个边界框（预测或 ground truth）计算得出的。

### 交并比（Intersection over Union，IoU）和物体检测
<a name="tr-evaluate-performance-object-detection"></a>

IoU 用于测量两个物体边界框的重叠部分占其合并区域的百分比。范围为 0（最低重叠）到 1（完全重叠）。在测试过程中，当 ground truth 边界框与预测的边界框的 IoU 不低于 0.5 时，即表示预测的边界框是正确的。

## 假设阈值
<a name="im-assumed-threshold"></a>

Amazon Rekognition Custom Labels 会自动为您的每个自定义标签计算一个假设阈值 (0-1)。无法为自定义标签设置假设阈值。每个标签的*假设阈值*都是预测被计为真正例或假正例的阈值。该阈值根据您的测试数据集设置。假设阈值是根据模型训练期间在测试数据集上获得的最佳 F1 分数计算得出的。

可以从模型的训练结果中获取标签的假设阈值。有关更多信息，请参阅 [获取评估指标（控制台）](im-access-training-results.md)。

更改假设阈值通常用于提高模型的精度和召回率。有关更多信息，请参阅 [改进 Amazon Rekognition Custom Labels 模型](tr-improve-model.md)。虽然无法设置模型对于标签的假设阈值，但可以通过使用 `DetectCustomLabels` 分析图像并指定 `MinConfidence` 输入参数来达到相同的效果。有关更多信息，请参阅 [使用经过训练的模型分析图像](detecting-custom-labels.md)。

## 精度
<a name="im-precision-metric"></a>

Amazon Rekognition Custom Labels 提供每个标签的精度指标，以及整个测试数据集的平均精度指标。

*精度*是指在单个标签的假设阈值下，正确预测（真正例）数量占所有模型预测（真正例与假正例之和）数量的比例。随着阈值的增加，模型做出的预测可能会减少。但是，总的来说，与较低的阈值相比，更高的阈值下，真正例与假正例数量之比会更高。可能的精度值介于 0-1 之间，值越高表示精度越高。

例如，当模型预测图像中有足球时，预测正确的概率是多少？ 假设有一张包含 8 个足球和 5 个石头的图像。如果模型预测有 9 个足球（8 个正确预测，1 个假正例），则此示例的精度为 0.89。但是，如果模型预测图像中有 13 个足球，其中有 8 个正确预测，5 个错误，则产生的精度会更低。

有关更多信息，请参阅[精度和召回率](https://en.wikipedia.org/wiki/Precision_and_recall)。

## 召回率
<a name="im-recall-metric"></a>

Amazon Rekognition Custom Labels 提供每个标签的平均召回率指标，以及整个测试数据集的平均召回率指标。

*召回率*是指正确预测的假设阈值之上的测试集标签所占的比例。该指标可以衡量当测试集图像中确实存在自定义标签时，模型可以正确预测该自定义标签的频率。召回率介于 0-1 之间。值越高表示召回率越高。

例如，如果一张图像包含 8 个足球，其中有多少被正确检测到？ 在此示例中，图像中包含 8 个足球和 5 个石头，如果模型检测到 5 个足球，则召回率为 0.62。如果在重新训练后，新模型检测到 9 个足球，包含了图像中存在的所有 8 个足球，则召回率为 1.0。

有关更多信息，请参阅[精度和召回率](https://en.wikipedia.org/wiki/Precision_and_recall)。

## F1
<a name="im-f1-metric"></a>

Amazon Rekognition Custom Labels 使用 F1 分数指标来衡量每个标签的平均模型性能和整个测试数据集的平均模型性能。

*模型性能*是一个综合衡量指标，它考虑了所有标签的精度和召回率。（例如，F1 分数或平均精度）。模型性能分数是介于 0 和 1 之间的值。该值越高，表明模型在召回率和精度方面的表现越好。具体而言，分类任务的模型性能通常由 F1 分数衡量。该分数是假设阈值下的精度和召回率分数的调和平均数。例如，对于精度为 0.9、召回率为 1.0 的模型，F1 分数为 0.947。

较高的 F1 分数值表示模型在精度和召回率方面都表现良好。如果模型表现不佳，例如精度低至 0.30，召回率高达 1.0，则 F1 分数为 0.46。同样，如果精度较高 (0.95)，而召回率较低 (0.20)，则 F1 分数为 0.33。这两种情况下，F1 分数都较低，表明模型存在问题。

有关更多信息，请参阅 [F1 分数](https://en.wikipedia.org/wiki/F1_score)。

## 使用指标
<a name="im-using-metrics"></a>

对于经过训练的给定模型，根据应用程序的不同，可以使用 `DetectCustomLabels` 的 `MinConfidence` 输入参数在*精度*和*召回率*之间进行平衡。`MinConfidence` 值越高，通常会获得更高的*精度*（正确预测的足球数量更多），但*召回率*越低（会漏掉更多实际的足球）。`MinConfidence` 值越低，*召回率*越高（正确预测的实际足球更多），但*精度*越低（这些预测中出错情况的更多）。有关更多信息，请参阅 [使用经过训练的模型分析图像](detecting-custom-labels.md)。

这些指标还会告知您，如果需要，您可以采取哪些步骤来改进模型性能。有关更多信息，请参阅 [改进 Amazon Rekognition Custom Labels 模型](tr-improve-model.md)。

**注意**  
`DetectCustomLabels` 会返回介于 0 到 100 之间的预测值，对应于 0-1 的指标范围。

# 获取评估指标（控制台）
<a name="im-access-training-results"></a>

在测试期间，将根据测试数据集评估模型的性能。测试数据集中的标签被视为“ground truth”，因为它们代表了实际图像所代表的内容。在测试期间，模型使用测试数据集进行预测。将预测的标签与“ground truth”标签进行比较，结果可在控制台评估页面中找到。

Amazon Rekognition Custom Labels 控制台会显示整个模型的摘要指标和单个标签的指标。控制台中提供的指标包括精度、召回率、F1 分数、置信度和置信度阈值。有关更多信息，请参阅 [改进经过训练的 Amazon Rekognition Custom Labels 模型](improving-model.md)。

您可以通过控制台重点关注单个指标。例如，要调查标签的精度问题，可以按标签和*假正例*结果筛选训练结果。有关更多信息，请参阅 [评估模型的指标](im-metrics-use.md)。

训练完成后，训练数据集为只读状态。如果决定改进模型，可以将训练数据集复制到新的数据集中。您可以使用该数据集的副本来训练模型的新版本。

在此步骤中，您将通过控制台获取训练结果。

**获取评估指标（控制台）**

1. 打开亚马逊 Rekognition 控制台，网址为[https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)。

1. 选择**使用自定义标签**。

1. 选择**开始**。

1. 在左侧导航窗格中，选择**项目**。

1. 在**项目**页面上，选择包含要评估的已训练模型的项目。

1. 在**模型**部分，选择要评估的模型。

1. 选择**评估**选项卡，以查看评估结果。有关评估模型的信息，请参阅[改进经过训练的 Amazon Rekognition Custom Labels 模型](improving-model.md)。

1. 选择**查看测试结果**，以查看单个测试图像的结果。有关更多信息，请参阅 [评估模型的指标](im-metrics-use.md)。以下模型评测摘要的屏幕截图显示 6 个标签的 F1 分数、平均精度和总体召回率，以及测试结果和性能指标。还提供了有关使用经过训练的模型的详细信息。  
![\[模型评测摘要显示 F1 分数、平均精度和总体召回率。\]](http://docs.aws.amazon.com/zh_cn/rekognition/latest/customlabels-dg/images/get-started-training-results.jpg)

1. 查看测试结果后，选择项目名称返回模型页面。测试结果页面显示包含机器学习模型的预测标签和置信度分数的图像，该模型针对后院和前院图像类别进行了训练。显示两张示例图像。  
![\[测试结果页面显示包含预测标签和置信度分数的图像。\]](http://docs.aws.amazon.com/zh_cn/rekognition/latest/customlabels-dg/images/get-started-image-test-results.jpg)

1. 使用这些指标来评估模型的性能。有关更多信息，请参阅 [改进 Amazon Rekognition Custom Labels 模型](tr-improve-model.md)。

# 获取 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"
      },
    },
    ...
  ]
}
```

# 改进 Amazon Rekognition Custom Labels 模型
<a name="tr-improve-model"></a>

机器学习模型的性能在很大程度上取决于诸如以下的因素：您的自定义标签（您感兴趣的特定物体和场景）的复杂性和可变性、您提供的训练数据集的质量和代表性，以及用于训练模型的模型框架和机器学习方法。

Amazon Rekognition Custom Labels 简化了这个过程，而且不要求您具备任何机器学习专业知识。但是，构建优质模型的过程通常涉及数据迭代和模型改进，以实现所需的性能。以下是有关如何改进模型的信息。

## 数据
<a name="im-data"></a>

通常，可以使用更多更优质的数据来提高模型的质量。使用清晰显示物体或场景且不包含不需要的杂乱物品的训练图像。对于物体周围的边界框，请使用所包含的物体完全可见且未被其他物体遮挡的训练图像。

确保您的训练和测试数据集与您最终要对其运行推理的图像的类型匹配。对于只有几个训练示例的物体（例如徽标），则应在测试图像中的徽标周围提供边界框。这些图像代表或描绘了您想要在其中定位物体的场景。

要向训练或测试数据集中添加更多图像，请参阅[向数据集中添加更多图像](md-add-images.md)。

## 减少假正例（更高的精度）
<a name="im-reduce-false-positives"></a>
+ 首先，检查提高假设阈值是否可以保持正确的预测，同时减少假正例。在某个时刻，由于给定模型的精度和召回率之间的权衡，这种做法的收益会递减。您无法为标签设置假设阈值，但可以通过为 `DetectCustomLabels` 的 `MinConfidence` 输入参数指定一个较高的值来达到相同的效果。有关更多信息，请参阅 [使用经过训练的模型分析图像](detecting-custom-labels.md)。
+ 您可能会看到一个或多个您感兴趣的自定义标签 (A) 一直与同一类物体（但不是您感兴趣的标签）(B) 混淆。为了帮助改进此问题，请将 B 作为物体类别标签添加到训练数据集（以及获得假正例的图像）。实际上，您是在通过新的训练图像帮助模型学会预测 B 而不是 A。要向训练数据集中添加图像，请参阅[向数据集中添加更多图像](md-add-images.md)。
+ 您可能会发现模型被两个自定义标签（A 和 B）所混淆：具有标签 A 的测试图像被预测为具有标签 B，反之亦然。在这种情况下，请先检查训练集和测试集中是否有错误标注的图像。使用数据集库管理分配给数据集的标签。有关更多信息，请参阅 [管理标签](md-labels.md)。此外，添加更多与此类混淆相关的训练图像将有助于重新训练的模型更好地区分 A 和 B。要向训练数据集添加图像，请参阅[向数据集中添加更多图像](md-add-images.md)。

## 减少假负例（更好的召回率）
<a name="im-reduce-false-negatives"></a>
+ 使用较低的假设阈值。您无法为标签设置假设阈值，但可以通过为 `DetectCustomLabels` 指定一个较低的 `MinConfidence` 输入参数来达到相同的效果。有关更多信息，请参阅 [使用经过训练的模型分析图像](detecting-custom-labels.md)。
+ 使用更好的示例对物体及其出现的图像的多样性进行建模。
+ 将标签分成两个更容易学习的类别。例如，您可能想要的不是好饼干和坏饼干，而是好饼干、烧焦的饼干和碎了的饼干，以帮助模型更好地学习每个独特的概念。