

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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) 섹션을 참조하세요.
+ 이미지 감지를 위한 Mean Average Precision(mAP)**
+ 이미지 감지를 위한 Mean Average Recall(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"]
}
```
+ 버전**: 매니페스트 스냅샷에 있는 `rekognition-custom-labels-evaluation-details` 필드 형식의 버전입니다.
+ is-true-positive...** : 신뢰도 점수가 레이블의 최소 임계값에 비해서 어떤지를 기반으로 한 예측의 바이너리 분류입니다.
+ is-present-in-ground-truth**: 모델을 통해 예측한 내용이 훈련에 사용된 실측 정보에 포함되면 참이고, 그렇지 않으면 거짓입니다. 이 값은 신뢰 점수가 모델에서 계산한 최소 임계값을 초과하는지 여부를 기반으로 하지 않습니다.
+ 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) 예제 프로젝트의 오차 행렬입니다. 열 제목은 테스트 이미지에 할당된 레이블(실측 정보 레이블)입니다. 행 제목은 모델이 테스트 이미지에 대해 예측하는 레이블입니다. 각 셀은 실측 정보 레이블(열)이 되어야 하는 레이블(행)에 대한 예측의 백분율입니다. 예를 들어, 욕실에 대한 예측의 67%가 욕실로 올바르게 레이블 지정되었고, 욕실의 33%가 주방으로 잘못 레이블 지정되었을 수 있습니다. 성능이 높은 모델은 예측 레이블이 실측 정보 레이블과 일치하여 셀 값이 높습니다. 이를 첫 번째 예측 레이블부터 마지막 예측 레이블 및 실측 정보 레이블까지 대각선으로 볼 수 있습니다. 셀 값이 0인 경우 셀의 실측 정보 레이블이어야 하는 셀의 예측 레이블에 대한 예측은 수행되지 않았다는 뜻입니다.

**참고**  
모델은 비결정적이므로 Rooms 프로젝트를 훈련하여 얻은 오차 행렬 셀 값은 다음 표와 다를 수 있습니다.

오차 행렬은 집중해야 할 영역을 식별합니다. 예를 들어, 오차 행렬은 모델이 옷장을 침실과 혼동한 경우가 50%라는 것을 보여줍니다. 이 상황에서는 훈련 데이터 세트에 옷장과 침실 이미지를 더 추가해야 합니다. 또한 기존 옷장 및 침실 이미지에 레이블이 올바르게 지정되어 있는지도 확인해야 합니다. 이렇게 하면 모델이 두 레이블을 더 잘 구분할 수 있습니다. 데이터 세트에 이미지를 더 추가하려면 [데이터 세트에 더 많은 이미지 추가](md-add-images.md) 항목을 참조하세요.

오차 행렬도 유용하지만 다른 지표도 고려하는 것이 중요합니다. 예를 들어, 예측의 100%가 평면도 레이블을 올바르게 찾았는데, 이는 성능이 우수하다는 뜻입니다. 하지만 테스트 데이터 세트에는 평면도 레이블이 있는 이미지가 2개만 있습니다. 또한 거실 레이블이 지정된 11개의 이미지도 있습니다. 이러한 불균형은 훈련 데이터 세트(거실 이미지 13개, 옷장 이미지 2개)에도 있습니다. 더 정확하게 평가하려면 제대로 대표되지 않은 레이블의 이미지(이 예에서는 평면도)를 더 추가하여 훈련 데이터 세트와 테스트 데이터 세트의 균형을 맞추세요. 레이블당 테스트 이미지 수를 가져오려면 [평가 지표 액세스(콘솔)](im-access-training-results.md) 항목을 참조하세요.

다음 표는 예측된 레이블(y축)을 실제 레이블과 비교하는 샘플 오차 행렬입니다.


| 예측 레이블 | 뒷마당 | 욕실 | 침실 | 옷장 | 진입로 | 평면도 | 앞마당 | 주방 | 거실 | 파티오 | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 뒷마당 | 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% | 
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 거실 | 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()
   ```

# 참조: 훈련 결과 요약 파일
<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"
      },
    },
    ...
  ]
}
```