

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 改善訓練過的 Amazon Rekognition 自訂標籤模型
<a name="improving-model"></a>

訓練完成後，您可以評估模型的效能。為了協助您，Amazon Rekognition 自訂標籤會針對每個標籤提供摘要指標和評估指標。如需有關可用指標的詳細資訊，請參閱 [用於評估模型的指標](im-metrics-use.md)。若要使用指標改善模型，請參閱 [改善 Amazon Rekognition 自訂標籤模型](tr-improve-model.md)。



如果對模型的準確性感到滿意，即可開始使用它。如需詳細資訊，請參閱[執行培訓過的 Amazon Rekognition 自訂標籤模型](running-model.md)。

**Topics**
+ [用於評估模型的指標](im-metrics-use.md)
+ [存取評估指標 (主控台)](im-access-training-results.md)
+ [存取 Amazon Rekognition 自訂標籤評估指標 (SDK)](im-metrics-api.md)
+ [改善 Amazon Rekognition 自訂標籤模型](tr-improve-model.md)

# 用於評估模型的指標
<a name="im-metrics-use"></a>

模型完成訓練後，Amazon Rekognition 自訂標籤會傳回模型測試的指標，您可將其用於評估模型的效能。本主題會說明您可以使用的指標，以及如何了解訓練過的模型是否成效良好。

Amazon Rekognition 自訂標籤主控台提供下列指標作為訓練結果摘要以及每個標籤的指標：
+ [精確度](#im-precision-metric)
+ [取回](#im-recall-metric)
+ [F1](#im-f1-metric)

我們提供的每個指標都是常用於評估機器學習模型效能的指標。Amazon Rekognition 自訂標籤會傳回整個測試資料集的測試結果指標，以及每個自訂標籤的指標。您也可以針對測試資料集中的每個影像檢閱訓練過的自訂模型效能。如需詳細資訊，請參閱[存取評估指標 (主控台)](im-access-training-results.md)。

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

在測試期間，Amazon Rekognition 自訂標籤會預測測試影像是否包含自訂標籤。可信度分數是量化模型預測確實性的值。

如果自訂標籤的可信度分數超過閾值，則模型輸出會包含此標籤。預測可以透過下列方式進行分類：
+ *相符* — Amazon Rekognition 自訂標籤模型會正確地預測出測試影像中存在自訂標籤。也就是說，預測的標籤也會是該影像的「Ground Truth」標籤。例如，當影像中存在足球時，Amazon Rekognition 自訂標籤即會正確地傳回足球標籤。
+ *誤報* — Amazon Rekognition 自訂標籤模型會錯誤地預測出測試影像中存在自訂標籤。也就是說，預測的標籤不是影像的 Ground Truth 標籤。例如，Amazon Rekognition 自訂標籤會傳回足球標籤，但該影像的 Ground Truth 中卻沒有足球標籤。
+ *漏報* — Amazon Rekognition 自訂標籤模型未預測出影像中存在自訂標籤，但該影像的「Ground Truth」包含此標籤。例如，Amazon Rekognition 自訂標籤不會針對包含足球的影像傳回「足球」自訂標籤。
+ *不相符* — Amazon Rekognition 自訂標籤模型會正確地預測出測試影像中不存在自訂標籤。例如，Amazon Rekognition 自訂標籤不會針對不包含足球的影像傳回足球標籤。

主控台會提供對測試資料集中每個影像的相符、不相符和漏報值的存取。如需詳細資訊，請參閱[存取評估指標 (主控台)](im-access-training-results.md)。

這些預測結果會用於計算每個標籤的下列指標，以及整個測試集的彙總。相同的定義適用於模型在週框方塊層級所做的預測，區別在於所有指標都會在每個測試影像中的每個週框方塊 (預測或 Ground Truth) 上面計算。

### 聯集上的交集 (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 自訂標籤會自動計算每個自訂標籤的假設閥值 (0-1)。您無法設定自訂標籤的假設閾值。就每個標籤的*假設閥值*的值而言，預測若高於該值，即會被計為相符或誤報。該值會根據您的測試資料集設定。假設閥值會根據模型訓練期間在測試資料集上達到的最佳 F1 分數來計算。

您可以從模型的培訓結果中取得標籤的假定臨界值。如需詳細資訊，請參閱[存取評估指標 (主控台)](im-access-training-results.md)。

對假設閥值的變更通常會用於提升型的精確度和取回率。如需詳細資訊，請參閱[改善 Amazon Rekognition 自訂標籤模型](tr-improve-model.md)。由於您無法針對標籤設定模型的假設閾值，因此可以透過分析具有 `DetectCustomLabels` 的影像並指定 `MinConfidence` 輸入參數來實現相同的結果。如需詳細資訊，請參閱[使用經過培訓的模型分析圖像](detecting-custom-labels.md)。

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

Amazon Rekognition 自訂標籤可提供每個標籤的精確度指標，以及整個測試資料集的平均精確度指標。

*精確度*指在個別標籤的假設閾值下，正確預測 (相符) 佔所有模型預測 (相符和誤報) 的比例。隨著閥值的增加，模型可能會進行較少的預測。但是，一般而言，與較低的閾值相比，其相符率會高於誤報率。精確度的可能值範圍為 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 自訂標籤可提供每個標籤的平均取回指標，以及整個測試資料集的平均取回指標。

*取回率*指在假設閾值之上，正確預測出的測試集標籤比例。這會測量模型在自訂標籤實際出現在測試集影像中時可正確預測自訂標籤的機率。取回率的範圍為 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 自訂標籤會使用 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 自訂標籤模型](tr-improve-model.md)。

**注意**  
`DetectCustomLabels` 會傳回範圍從 0 到 100 的預測值，這些預測值會對應 0 到 1 的指標範圍。

# 存取評估指標 (主控台)
<a name="im-access-training-results"></a>

在測試期間，會根據測試資料集評估模型的效能。測試資料集中的標籤會被視為「Ground Truth」，因為它們代表了實際影像所代表的內容。在測試期間，模型會使用測試資料集進行預測。預測的標籤會和 Ground Truth 標籤進行比較，並可在主控台評估頁面中取得結果。

Amazon Rekognition 自訂標籤主控台會顯示整個模型的摘要指標，以及個別標籤的指標。主控台中可用的指標包括精確度取回、F1 分數、可信度和可信度閾值。如需詳細資訊，請參閱[改善訓練過的 Amazon Rekognition 自訂標籤模型](improving-model.md)。

您可以使用主控台以專注於個別指標。例如，若要調查標籤的精確度問題，您可以依標籤和*誤報*結果篩選訓練結果。如需詳細資訊，請參閱[用於評估模型的指標](im-metrics-use.md)。

訓練後，訓練資料集會變成唯讀。如果您決定提升模型，可以將訓練資料集複製到新的資料集。您可以使用資料集的複本來訓練新版本的模型。

在此步驟中，您會使用主控台來存取主控台中的訓練結果。

**存取評估指標 (主控台)**

1. 開啟 Amazon Rekognition 主控台：[https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)。

1. 選擇**使用自訂標籤**。

1. 選擇**開始使用**。

1. 在左側導覽窗格中，選擇**專案**。

1. 在**專案**頁面中，選擇包含您要評估的訓練過模型的專案。

1. 在**模型**中，選擇您要評估的模型。

1. 選擇**評估**索引標籤，以查看評估結果。如需評估模型的資訊，請參閱 [改善訓練過的 Amazon Rekognition 自訂標籤模型](improving-model.md)。

1. 選擇**檢視測試結果**，以查看個別測試影像的結果。如需詳細資訊，請參閱[用於評估模型的指標](im-metrics-use.md)。模型評估摘要的下列螢幕擷取畫面顯示 6 個標籤的 F1 分數、平均精確度和整體召回，以及測試結果和效能指標。也會提供使用訓練模型的詳細資訊。  
![\[顯示 F1 分數、平均精確度和整體召回的模型評估摘要。\]](http://docs.aws.amazon.com/zh_tw/rekognition/latest/customlabels-dg/images/get-started-training-results.jpg)

1. 檢視測試結果後，請選擇專案名稱，以返回模型頁面。測試結果頁面顯示以後院和前院影像類別訓練之機器學習模型的預測標籤和可信度分數的影像。顯示兩個範例影像。  
![\[測試結果頁面顯示具有預測標籤和可信度分數的影像。\]](http://docs.aws.amazon.com/zh_tw/rekognition/latest/customlabels-dg/images/get-started-image-test-results.jpg)

1. 使用指標來評估模型的效能。如需詳細資訊，請參閱[改善 Amazon Rekognition 自訂標籤模型](tr-improve-model.md)。

# 存取 Amazon Rekognition 自訂標籤評估指標 (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)。

`DescribeProjectVersions` 會直接傳回彙總 F1 分數指標。其他指標可從 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-truth* — 如果模型所做的預測存在於用於訓練的 Ground Truth 資訊中，即為真，否則即為偽。此值的根據並非可信度分數是否超過模型所計算的最小閾值。
+ *ground-truth-labeling-jobs* — 清單檔案行中用於訓練的 Ground Truth 欄位清單。

如需 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` — 用於測試的評估清單檔案快照的位置。

在 `EvaluationResult` 中傳回 F1 分數和摘要檔案位置。例如：

```
"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 自訂標籤所傳回之指標的相關資訊，請參閱 [存取 Amazon Rekognition 自訂標籤評估指標 (SDK)](im-metrics-api.md)。

# 檢視模型的混淆矩陣
<a name="im-confusion-matrix"></a>

混淆矩陣可讓您查看模型與模型中其他標籤混淆的標籤。透過使用混淆矩陣，您可以將改進重點集中在模型上。

在模型評估期間，Amazon Rekognition 自訂標籤會使用測試影像來識別錯誤識別 (混淆) 的標籤，藉此建立混淆矩陣。Amazon Rekognition 自訂標籤只會建立分類模型的混淆矩陣。分類矩陣可以從 Amazon Rekognition 自訂標籤在模型訓練期間建立的摘要檔案存取。您無法在 Amazon Rekognition 自訂標籤主控台中檢視混淆矩陣。

**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 標籤。如果儲存格值為 0，則不會針對該儲存格的預測標籤進行預測，該標籤應為儲存格的 Ground Truth 標籤。

**注意**  
由於模型不具確定性，因此您從訓練 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 軸上） 與 Ground Truth 標籤：


| 預測標籤 | 後院 | 浴室 | 臥室 | 衣櫥 | 入口 | 建築平面圖 | 前院 | 廚房 | 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% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 入口 | 0% | 0% | 0% | 0% | 33% | 0% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 建築平面圖 | 0% | 0% | 0% | 0% | 0% | 100% | 0% | 0% | 0% | 0% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 前院 | 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 CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 4：設定 AWS CLI 和 AWS SDKs](su-awscli-sdk.md)。

1. 使用下列程式碼來顯示模型的混淆矩陣。提供下列命令列參數：
   + `project_name` — 您要使用的專案名稱。您可以從 Amazon Rekognition 自訂標籤主控台中的專案頁面取得專案名稱。
   + `version_name` — 您要使用的模型版本。您可以從 Amazon Rekognition 自訂標籤主控台中的專案詳細資料頁面取得版本名稱。

   ```
   # 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 自訂標籤模型
<a name="tr-improve-model"></a>

機器學習模型的效能大部分會依據多種因素而定，例如自訂標籤的複雜性和變化性 (您感興趣的特定物件和場景)、您提供的訓練資料集的品質和代表性能力，以及用於訓練模型的模型架構和機器學習方法。

Amazon Rekognition 自訂標籤讓這個程序更簡單，而且不需要機器學習專業知識。但是，建置良好模型的程序通常需要重複資料和模型改進，才能實現所需的效能。以下是有關如何改進模型的資訊。

## 資料
<a name="im-data"></a>

一般而言，您可以利用品質較佳的資料來提升模型的品質。使用訓練影像，清楚地顯示物體或場景，並且不會和不必要的物品雜亂地堆放在一起。對於物件周圍的週框方塊，請使用訓練影像，將物件顯示為完全可見並且不會被其他物件遮擋。

請確保您的訓練和測試資料集與您最終將執行推論的影像類型相符。對於只有一些訓練範例的物件 (例如標誌)，您應該在測試影像中的標誌周圍提供週框方塊。這些影像會代表或描繪您要在其中本地化物件的案例。

若要將更多影像新增至訓練或測試資料集，請參閱 [將更多圖像新增至資料集](md-add-images.md)。

## 減少誤報 (精確度更佳)
<a name="im-reduce-false-positives"></a>
+ 首先，檢查是否增加假設閾值可讓您保持正確的預測，同時減少誤報。在某些時候，由於特定模型的精確度和呼叫之間的取捨，這會減少效益。您無法設定標籤的假設閾值，但是可以透過指定 `MinConfidence` 輸入參數的高值至 `DetectCustomLabels` 來實現相同的結果。如需詳細資訊，請參閱[使用經過培訓的模型分析圖像](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>
+ 針對假設閾值使用較低的值。您無法設定標籤的假設閾值，但是可以透過指定 `MinConfidence` 輸入參數的較低值至 `DetectCustomLabels` 來實現相同的結果。如需詳細資訊，請參閱[使用經過培訓的模型分析圖像](detecting-custom-labels.md)。
+ 使用更佳的範例來模擬物件及在其中顯示物件的影像的變化。
+ 將您的標籤分割成兩個更容易學習的課程。例如，與其使用好的 cookie 和壞的 cookie，您可能需要好的 cookie、燒焦的 cookie 和破碎的 cookie 來協助模型更深入地學習每個獨特的概念。