

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# マルチラベルの SageMaker AI Ground Truth マニフェストファイルの変換
<a name="md-gt-cl-transform"></a>

このトピックでは、マルチラベルの Amazon SageMaker AI Ground Truth マニフェストファイルを Amazon Rekognition Custom Labels 形式のマニフェストファイルに変換する方法について説明します。

マルチラベルジョブ用の SageMaker AI Ground Truth マニフェストファイルの形式は、Amazon Rekognition Custom Labels 形式のマニフェストファイルとは異なります。マルチラベル分類は、イメージを複数のクラスに分類しても同時に複数のクラスに属する場合もあります。この場合、イメージには *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)」を参照してください。

## 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 Custom Labels マニフェストファイルを作成します。

**注記**  
コードを実行するには、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. マニフェストファイルを保存するために使用する Amazon S3 バケットに[マニフェストファイルをアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)します。
**注記**  
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 では、**[マニフェストファイルの場所]** に、マニフェストファイルの場所として Amazon S3 URL を入力します。 AWS SDK を使用している場合、[SageMaker AI Ground Truth マニフェストファイル (SDK) を使用したデータセットの作成](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk) を実行してください。