

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

# 轉換多標籤 SageMaker AI Ground Truth 資訊清單檔案
<a name="md-gt-cl-transform"></a>

本主題說明如何將多標籤 Amazon SageMaker AI Ground Truth 資訊清單檔案轉換為 Amazon Rekognition 自訂標籤格式資訊清單檔案。

多標籤任務的 SageMaker AI Ground Truth 資訊清單檔案的格式與 Amazon Rekognition 自訂標籤格式資訊清單檔案不同。多標籤分類指將影像分類為一組類別，但可能同時屬於多個類別。在這種情況下，影像可能有多個標籤 (多標籤)，例如 *football* 和 *ball*。

如需多標籤 SageMaker AI Ground Truth 任務的詳細資訊，請參閱[影像分類 （多標籤）](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-image-classification-multilabel.html)。如需多標籤格式 Amazon Rekognition 自訂標籤清單檔案的相關資訊，請參閱 [對影像新增多個影像層級標籤](md-create-manifest-file-classification.md#md-dataset-purpose-classification-multiple-labels)。

## 取得 SageMaker AI Ground Truth 任務的資訊清單檔案
<a name="md-get-gt-manifest"></a>

下列程序說明如何取得 Amazon SageMaker AI Ground Truth 任務的輸出資訊清單檔案 (`output.manifest`)。將 `output.manifest` 用為下個程序的輸入。

**下載 SageMaker AI Ground Truth 任務清單檔案**

1. 開啟 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)。

1. 在導覽窗格中，選擇 **Ground Truth**，然後選擇**標記任務**。

1. 選擇包含您要使用之清單檔案的標記任務。

1. 在詳細資訊頁面上，選擇**輸出資料集位置**下方的連結。Amazon S3 主控台會在資料集位置開啟。

1. 選擇 `Manifests`、`output`，然後選擇 `output.manifest`。

1. 若要下載清單檔案，請選擇**物件動作**，然後選擇**下載**。

## 轉換多標籤 SageMaker AI 資訊清單檔案
<a name="md-transform-ml-gt"></a>

下列程序會從現有的多標籤格式 SageMaker AI GroundTruth 資訊清單檔案建立多標籤格式的 Amazon Rekognition 自訂標籤資訊清單檔案。

**注意**  
若要執行程式碼，您需要 Python 版本 3 或更高版本。<a name="md-procedure-multi-label-transform"></a>

**轉換多標籤 SageMaker AI 資訊清單檔案**

1. 使用以下 Python 程式碼。提供您在 [取得 SageMaker AI Ground Truth 任務的資訊清單檔案](#md-get-gt-manifest) 中建立的清單檔案名稱作為命令列引數。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier:  Apache-2.0
   """
   Purpose
   Shows how to create and Amazon Rekognition Custom Labels format
   manifest file from an Amazon SageMaker Ground Truth Image
   Classification (Multi-label) format manifest file.
   """
   import json
   import logging
   import argparse
   import os.path
   
   logger = logging.getLogger(__name__)
   
   def create_manifest_file(ground_truth_manifest_file):
       """
       Creates an Amazon Rekognition Custom Labels format manifest file from
       an Amazon SageMaker Ground Truth Image Classification (Multi-label) format
       manifest file.
       :param: ground_truth_manifest_file: The name of the Ground Truth manifest file,
       including the relative path.
       :return: The name of the new Custom Labels manifest file.
       """
   
       logger.info('Creating manifest file from %s', ground_truth_manifest_file)
       new_manifest_file = f'custom_labels_{os.path.basename(ground_truth_manifest_file)}'
   
       # Read the SageMaker Ground Truth manifest file into memory.
       with open(ground_truth_manifest_file) as gt_file:
           lines = gt_file.readlines()
   
       #Iterate through the lines one at a time to generate the
       #new lines for the Custom Labels manifest file.
       with open(new_manifest_file, 'w') as the_new_file:
           for line in lines:
               #job_name - The of the Amazon Sagemaker Ground Truth job.
               job_name = ''
               # Load in the old json item from the Ground Truth manifest file
               old_json = json.loads(line)
   
               # Get the job name
               keys = old_json.keys()
               for key in keys:
                   if 'source-ref' not in key and '-metadata' not in key:
                       job_name = key
   
               new_json = {}
               # Set the location of the image
               new_json['source-ref'] = old_json['source-ref']
   
               # Temporarily store the list of labels
               labels = old_json[job_name]
   
               # Iterate through the labels and reformat to Custom Labels format
               for index, label in enumerate(labels):
                   new_json[f'{job_name}{index}'] = index
                   metadata = {}
                   metadata['class-name'] = old_json[f'{job_name}-metadata']['class-map'][str(label)]
                   metadata['confidence'] = old_json[f'{job_name}-metadata']['confidence-map'][str(label)]
                   metadata['type'] = 'groundtruth/image-classification'
                   metadata['job-name'] = old_json[f'{job_name}-metadata']['job-name']
                   metadata['human-annotated'] = old_json[f'{job_name}-metadata']['human-annotated']
                   metadata['creation-date'] = old_json[f'{job_name}-metadata']['creation-date']
                   # Add the metadata to new json line
                   new_json[f'{job_name}{index}-metadata'] = metadata
               # Write the current line to the json file
               the_new_file.write(json.dumps(new_json))
               the_new_file.write('\n')
   
       logger.info('Created %s', new_manifest_file)
       return  new_manifest_file
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "manifest_file", help="The Amazon SageMaker Ground Truth manifest file"
           "that you want to use."
       )
   
   
   def main():
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
       try:
           # get command line arguments
           parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
           add_arguments(parser)
           args = parser.parse_args()
           # Create the manifest file
           manifest_file = create_manifest_file(args.manifest_file)
           print(f'Manifest file created: {manifest_file}')
       except FileNotFoundError as err:
           logger.exception('File not found: %s', err)
           print(f'File not found: {err}. Check your manifest file.')
   
   if __name__ == "__main__":
       main()
   ```

1. 記下指令碼顯示的新清單檔案的名稱。在下一個步驟中用得到。

1. [將清單檔案上傳](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)到您要用於存放清單檔案的 Amazon S3 儲存貯體。
**注意**  
請確保 Amazon Rekognition 自訂標籤可存取清單檔案 JSON Lines 的 `source-ref` 欄位中參考的 Amazon S3 儲存貯體。如需詳細資訊，請參閱[存取外部 Amazon S3 儲存貯體](su-console-policy.md#su-external-buckets)。如果您的 Ground Truth 任務將影像存放在 Amazon Rekognition 自訂標籤主控台儲存貯體中，則不需要新增權限。

1. 請遵循 [使用 SageMaker AI Ground Truth 資訊清單檔案 （主控台） 建立資料集](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-console) 中的指示，使用上傳的資訊清單檔案建立資料集。對於步驟 8，請在 **.manifest 檔案位置**，輸入清單檔案位置的 Amazon S3 URL。如果您使用 AWS SDK，請執行 [使用 SageMaker AI Ground Truth 資訊清單檔案 (SDK) 建立資料集](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk)。