

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

# データセットをプロジェクトに追加する
<a name="md-add-dataset"></a>

トレーニングデータセットまたはテストデータセットは、既存のデータセットプロジェクトに追加できます。既存のデータセットを置き換える場合は、最初に既存のデータセットを削除します。詳細については、「[データセットの削除](md-delete-dataset.md)」を参照してください。次に、新しいデータセットを追加します。

**Topics**
+ [データセットをプロジェクトに追加する (コンソール)](#md-add-dataset-console)
+ [データセットをプロジェクトに追加する (SDK)](#md-add-dataset-sdk)

## データセットをプロジェクトに追加する (コンソール)
<a name="md-add-dataset-console"></a>

Amazon Rekognition Custom Labels コンソールを使用して、トレーニングデータセットまたはテストデータセットをプロジェクトに追加できます。

**データセットをプロジェクトに追加するには**

1. Amazon Rekognition コンソールを [https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/) で開きます。

1. 左側のペインで、**[カスタムラベルを使用]** を選択します。Amazon Rekognition Custom Labels のランディングページが表示されます。

1. 左側のナビゲーションペインで、**[プロジェクト]** を選択します。プロジェクトビューが表示されます。

1. データセットを追加するプロジェクトを選択します。

1. 左側のナビゲーションペインで、プロジェクト名の下にある **[データセット]** を選択します。

1. プロジェクトに既存のデータセットがない場合は、**[データセットを作成]** ページが表示されます。以下の操作を実行します。

   1. **[データセットを作成]** ページで、イメージソース情報を入力します。詳細については、「[イメージ付きのトレーニングデータセットとテストデータセットの作成](md-create-dataset.md)」を参照してください。

   1. **[データセットを作成]** を選択します。

1. プロジェクトに既存のデータセット (トレーニングまたはテスト) がある場合は、プロジェクトの詳細ページが表示されます。以下の操作を実行します。

   1. プロジェクトの詳細ページで **[アクション]** を選択します。

   1. トレーニングデータセットを追加する場合は、**[トレーニングデータセットを作成]** を選択します。

   1. テストデータセットを追加する場合は、**[テストデータセットを作成]** を選択します。

   1. **[データセットを作成]** ページで、イメージソース情報を入力します。詳細については、「[イメージ付きのトレーニングデータセットとテストデータセットの作成](md-create-dataset.md)」を参照してください。

   1. **[データセットを作成]** を選択します。

1. データセットにイメージを追加します。詳細については、「[イメージの追加 (コンソール)](md-add-images.md#md-add-images-console)」を参照してください。

1. データセットにラベルを追加します。詳細については、「[新しいラベルの追加 (コンソール)](md-labels.md#md-add-new-labels)」を参照してください。

1. イメージにラベルを追加します。イメージレベルのラベルを追加する場合は、「[イメージにイメージレベルのラベルを割り当てる](md-assign-image-level-labels.md)」を参照してください。境界ボックスを追加する場合は、「[境界ボックスによるオブジェクトのラベル付け](md-localize-objects.md)」を参照してください。詳細については、「[データセットの目的の設定](md-dataset-purpose.md)」を参照してください。

## データセットをプロジェクトに追加する (SDK)
<a name="md-add-dataset-sdk"></a>

次の方法で、トレーニングデータセットまたはテストデータセットを既存のデータセットプロジェクトに追加できます。
+ マニフェストファイルを使用したデータセットの作成 詳細については、「[SageMaker AI Ground Truth マニフェストファイル (SDK) を使用したデータセットの作成](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk)」を参照してください。
+ 空のデータセットを作成し、そのデータセットにデータを入力します。次の例は、空のデータセットを作成する方法を示しています。空のデータセットを作成した後でエントリを追加する方法については、「[データセットへのイメージの追加](md-add-images.md)」を参照してください。

**Topics**

**データセットをプロジェクトに追加するには (SDK)**

1. まだインストールしていない場合は、 と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 4: AWS CLI と AWS SDKsを設定する](su-awscli-sdk.md)」を参照してください。

1. 次の例を使用して JSON 行をデータセットに追加します。

------
#### [ CLI ]

   `project_arn` を、データセットを追加するプロジェクトに置き換えます。`dataset_type` を `TRAIN` に置き換えてトレーニングデータセットを作成するか、`TEST` に置き換えてテストデータセットを作成します。

   ```
   aws rekognition create-dataset --project-arn project_arn \
     --dataset-type dataset_type \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   次のコードを使用してデータセットを作成します。次のコマンドラインオプションを指定します。
   + `project_arn` - テストデータセットを追加するプロジェクトの ARN。
   + `type` - 作成するデータセットのタイプ (トレーニングまたはテスト)

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   import argparse
   import logging
   import time
   import boto3
   
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   def create_empty_dataset(rek_client, project_arn, dataset_type):
       """
       Creates an empty Amazon Rekognition Custom Labels dataset.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_arn: The ARN of the project in which you want to create a dataset.
       :param dataset_type: The type of the dataset that you want to create (train or test).
       """
   
       try:
           #Create the dataset.
           logger.info("Creating empty %s dataset for project %s",
               dataset_type, project_arn)
   
           dataset_type=dataset_type.upper()
   
           response = rek_client.create_dataset(
               ProjectArn=project_arn, DatasetType=dataset_type
           )
   
           dataset_arn=response['DatasetArn']
   
           logger.info("dataset ARN: %s", dataset_arn)
   
           finished=False
           while finished is False:
   
               dataset=rek_client.describe_dataset(DatasetArn=dataset_arn)
   
               status=dataset['DatasetDescription']['Status']
               
               if status == "CREATE_IN_PROGRESS":
                   
                   logger.info(("Creating dataset: %s ", dataset_arn))
                   time.sleep(5)
                   continue
   
               if status == "CREATE_COMPLETE":
                   logger.info("Dataset created: %s", dataset_arn)
                   finished=True
                   continue
   
               if status == "CREATE_FAILED":
                   error_message = f"Dataset creation failed: {status} : {dataset_arn}"
                   logger.exception(error_message)
                   raise Exception(error_message)
                   
               error_message = f"Failed. Unexpected state for dataset creation: {status} : {dataset_arn}"
               logger.exception(error_message)
               raise Exception(error_message)
               
           return dataset_arn
          
       except ClientError as err:  
           logger.exception("Couldn't create dataset: %s", err.response['Error']['Message'])
           raise
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_arn", help="The ARN of the project in which you want to create the empty dataset."
       )
   
       parser.add_argument(
           "dataset_type", help="The type of the empty dataset that you want to create (train or test)."
       )
   
   
   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()
   
           print(f"Creating empty {args.dataset_type} dataset for project {args.project_arn}")
   
           # Create the empty dataset.
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           dataset_arn=create_empty_dataset(rekognition_client, 
               args.project_arn,
               args.dataset_type.lower())
   
           print(f"Finished creating empty dataset: {dataset_arn}")
   
   
       except ClientError as err:
           logger.exception("Problem creating empty dataset: %s", err)
           print(f"Problem creating empty dataset: {err}")
       except Exception as err:
           logger.exception("Problem creating empty dataset: %s", err)
           print(f"Problem creating empty dataset: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   次のコードを使用してデータセットを作成します。次のコマンドラインオプションを指定します。
   + `project_arn` - テストデータセットを追加するプロジェクトの ARN。
   + `type` - 作成するデータセットのタイプ (トレーニングまたはテスト)

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   package com.example.rekognition;
   
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.CreateDatasetRequest;
   import software.amazon.awssdk.services.rekognition.model.CreateDatasetResponse;
   import software.amazon.awssdk.services.rekognition.model.DatasetDescription;
   import software.amazon.awssdk.services.rekognition.model.DatasetStatus;
   import software.amazon.awssdk.services.rekognition.model.DatasetType;
   import software.amazon.awssdk.services.rekognition.model.DescribeDatasetRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeDatasetResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   import java.net.URI;
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class CreateEmptyDataset {
   
       public static final Logger logger = Logger.getLogger(CreateEmptyDataset.class.getName());
   
       public static String createMyEmptyDataset(RekognitionClient rekClient, String projectArn, String datasetType)
               throws Exception, RekognitionException {
   
           try {
   
               logger.log(Level.INFO, "Creating empty {0} dataset for project : {1}",
                       new Object[] { datasetType.toString(), projectArn });
   
               DatasetType requestDatasetType = null;
   
               switch (datasetType) {
               case "train":
                   requestDatasetType = DatasetType.TRAIN;
                   break;
               case "test":
                   requestDatasetType = DatasetType.TEST;
                   break;
               default:
                   logger.log(Level.SEVERE, "Unrecognized dataset type: {0}", datasetType);
                   throw new Exception("Unrecognized dataset type: " + datasetType);
   
               }
   
               CreateDatasetRequest createDatasetRequest = CreateDatasetRequest.builder().projectArn(projectArn)
                       .datasetType(requestDatasetType).build();
   
               CreateDatasetResponse response = rekClient.createDataset(createDatasetRequest);
   
               boolean created = false;
               
               //Wait until updates finishes
   
               do {
   
                   DescribeDatasetRequest describeDatasetRequest = DescribeDatasetRequest.builder()
                           .datasetArn(response.datasetArn()).build();
                   DescribeDatasetResponse describeDatasetResponse = rekClient.describeDataset(describeDatasetRequest);
   
                   DatasetDescription datasetDescription = describeDatasetResponse.datasetDescription();
   
                   DatasetStatus status = datasetDescription.status();
   
                   logger.log(Level.INFO, "Creating dataset ARN: {0} ", response.datasetArn());
   
                   switch (status) {
   
                   case CREATE_COMPLETE:
                       logger.log(Level.INFO, "Dataset created");
                       created = true;
                       break;
   
                   case CREATE_IN_PROGRESS:
                       Thread.sleep(5000);
                       break;
   
                   case CREATE_FAILED:
                       String error = "Dataset creation failed: " + datasetDescription.statusAsString() + " "
                               + datasetDescription.statusMessage() + " " + response.datasetArn();
                       logger.log(Level.SEVERE, error);
                       throw new Exception(error);
   
                   default:
                       String unexpectedError = "Unexpected creation state: " + datasetDescription.statusAsString() + " "
                               + datasetDescription.statusMessage() + " " + response.datasetArn();
                       logger.log(Level.SEVERE, unexpectedError);
                       throw new Exception(unexpectedError);
                   }
   
               } while (created == false);
   
               return response.datasetArn();
   
           } catch (RekognitionException e) {
               logger.log(Level.SEVERE, "Could not create dataset: {0}", e.getMessage());
               throw e;
           }
   
       }
   
   
       public static void main(String args[]) {
   
           String datasetType = null;
           String datasetArn = null;
           String projectArn = null;
   
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> <dataset_type>\n\n" + "Where:\n"
                   + "   project_arn - the ARN of the project that you want to add copy the datast to.\n\n"
                   + "   dataset_type - the type of the empty dataset that you want to create (train or test).\n\n";
                 
   
           if (args.length != 2) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           projectArn = args[0];
           datasetType = args[1];
           
           try {
   
               // Get the Rekognition client
               RekognitionClient rekClient = RekognitionClient.builder()
                   .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
                   .region(Region.US_WEST_2)
                   .build();
   
               // Create the dataset
               datasetArn = createMyEmptyDataset(rekClient, projectArn, datasetType);
   
               System.out.println(String.format("Created dataset: %s", datasetArn));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           } catch (Exception rekError) {
               logger.log(Level.SEVERE, "Error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

1. データセットにイメージを追加します。詳細については、「[イメージの追加 (SDK)](md-add-images.md#md-add-images-sdk)」を参照してください。