

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

# 转换多标签 SageMaker AI Ground Truth 清单文件
<a name="md-gt-cl-transform"></a>

本主题向您展示如何将多标签 Amazon A SageMaker I Ground Truth 清单文件转换为亚马逊 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 Custom Labels 清单文件的信息，请参阅[为图像添加多个图像级标签](md-create-manifest-file-classification.md#md-dataset-purpose-classification-multiple-labels)。

## 获取 A SageMaker I Ground Truth 任务的清单文件
<a name="md-get-gt-manifest"></a>

以下过程向您展示了如何获取 Amazon A SageMaker I Ground Truth 任务的输出清单文件 (`output.manifest`)。您可以将 `output.manifest` 用作下一过程的输入。

**下载 A SageMaker I 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>

以下过程根据现有的多标签格式 AI 清单文件创建多标签格式 Amazon Rekognition 自定义标签清单文件。 SageMaker GroundTruth

**注意**  
要运行此代码，您需要使用 Python 版本 3 或更高版本。<a name="md-procedure-multi-label-transform"></a>

**转换多标签 SageMaker AI 清单文件**

1. 运行以下 Python 代码。提供您在[获取 A SageMaker I 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 Custom Labels 可以访问清单文件 JSON 行的 `source-ref` 字段中引用的 Amazon S3 存储桶。有关更多信息，请参阅 [访问外部 Amazon S3 存储桶](su-console-policy.md#su-external-buckets)。如果 Ground Truth 作业将图像存储在 Amazon Rekognition Custom Labels 控制台存储桶中，则无需添加权限。

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)。