

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

# Amazon Rekognition Custom Labels モデルの削除
<a name="tm-delete-model"></a>

Amazon Rekognition Custom Labels コンソールを使用するか、[DeleteProjectVersion API](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectVersion) を使用してモデルを削除できます。実行中またはトレーニング中の場合は、モデルを削除できません。実行中のモデルを停止するには、[StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API を使用します。詳細については、「[Amazon Rekognition Custom Labels モデル (SDK) の停止](rm-stop.md#rm-stop-sdk)」を参照してください。モデルがトレーニング中の場合は、モデルを削除する前に終了するまで待ちます。

削除したモデルを元に戻すことはできません。

**Topics**
+ [Amazon Rekognition Custom Labels モデルの削除 (コンソール)](#tm-delete-model-console)
+ [Amazon Rekognition Custom Labels モデルの削除 (SDK)](#tm-delete-model-sdk)

## Amazon Rekognition Custom Labels モデルの削除 (コンソール)
<a name="tm-delete-model-console"></a>

次の手順では、プロジェクトの詳細ページからモデルを削除する方法を示しています。モデルの詳細ページからモデルを削除することもできます。

**モデルを削除するには (コンソール)**

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

1. **[カスタムラベルを使用]** を選択します。

1. **[開始方法]** を選択します。

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

1. 削除するモデルを含むプロジェクトを選択します。プロジェクトの詳細ページが開きます。

1. **[モデル]** セクションで、削除するモデルを選択します。
**注記**  
モデルを選択できない場合、モデルは実行中またはトレーニング中であるため削除できません。**[ステータス]** フィールドを確認して、実行中のモデルを停止してから再試行するか、トレーニングが終了するまで待ちます。

1. **[モデルを削除]** を選択すると、**[モデルを削除] ダイアログボックスが表示されます**。

1. **[delete]** と入力して、削除を確定します。

1. [**削除**] を選択してモデルを削除します。モデルの削除が完了するまでに時間がかかる場合があります。
**注記**  
モデルの削除中にダイアログボックスを**閉じた**場合でも、モデルは削除されます。

## Amazon Rekognition Custom Labels モデルの削除 (SDK)
<a name="tm-delete-model-sdk"></a>

Amazon Rekognition Custom Labels モデルを削除するには、[deleteProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectVersion) を呼び出し、削除するモデルの Amazon リソースネーム (ARN) を指定します。モデル ARN は、Amazon Rekognition Custom Labels コンソールのモデルの詳細ページの **[モデルを使用する]** セクションから取得できます。または、[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) を呼び出して、次のものを指定します。
+ ジョブが関連付けられているプロジェクト (`ProjectArn`) の ARN。
+ モデルのバージョン名 (`VersionNames`)。

モデル ARN は、`DescribeProjectVersions` からのレスポンスで取得した [ProjectVersionDescription](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProjectVersionDescription) オブジェクト内の `ProjectVersionArn` フィールドです。

実行中またはトレーニング中の場合は、モデルを削除できません。モデルが実行中またはトレーニング中かを判断するには、[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) を呼び出し、モデルの [ProjectVersionDescription](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProjectVersionDescription) オブジェクトの `Status` フィールドを確認します。実行中のモデルを停止するには、[StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API を使用します。詳細については、「[Amazon Rekognition Custom Labels モデル (SDK) の停止](rm-stop.md#rm-stop-sdk)」を参照してください。モデルを削除するには、トレーニングが終了するまで待つ必要があります。

**モデルを削除するには (SDK)**

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

1. モデルを削除するには、次のコードを使用します。

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

   `project-version-arn` の値を削除するプロジェクトの名前に変更します。

   ```
   aws rekognition delete-project-version --project-version-arn {{model_arn}} \
     --profile custom-labels-access
   ```

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

   次のコマンドラインパラメータを指定します
   + `project_arn` - 削除するモデルを含むプロジェクトの ARN。
   + `model_arn` - 削除するモデルのバージョンの ARN。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to delete an existing Amazon Rekognition Custom Labels model.
   """
   
   
   import argparse
   import logging
   import time
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def find_forward_slash(input_string, n):
       """
       Returns the location of '/' after n number of occurences. 
       :param input_string: The string you want to search
       : n: the occurence that you want to find.
       """
       position = input_string.find('/')
       while position >= 0 and n > 1:
           position = input_string.find('/', position + 1)
           n -= 1
       return position
   
   
   def delete_model(rek_client, project_arn, model_arn):
       """
       Deletes an Amazon Rekognition Custom Labels model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param model_arn: The ARN of the model version that you want to delete.
       """
   
       try:
           # Delete the model
           logger.info("Deleting dataset: {%s}", model_arn)
   
           rek_client.delete_project_version(ProjectVersionArn=model_arn)
   
           # Get the model version name
           start = find_forward_slash(model_arn, 3) + 1
           end = find_forward_slash(model_arn, 4)
           version_name = model_arn[start:end]
   
           deleted = False
   
           # model might not be deleted yet, so wait deletion finishes.
           while deleted is False:
               describe_response = rek_client.describe_project_versions(ProjectArn=project_arn,
                                                                        VersionNames=[version_name])
               if len(describe_response['ProjectVersionDescriptions']) == 0:
                   deleted = True
               else:
                   logger.info("Waiting for model deletion %s", model_arn)
                   time.sleep(5)
   
           logger.info("model deleted: %s", model_arn)
   
           return True
   
       except ClientError as err:
           logger.exception("Couldn't delete model - %s: %s",
                            model_arn, 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 that contains the model that you want to delete."
       )
   
       parser.add_argument(
           "model_arn", help="The ARN of the model version that you want to delete."
       )
   
   
   def confirm_model_deletion(model_arn):
       """
       Confirms deletion of the model. Returns True if delete entered.
       :param model_arn: The ARN of the model that you want to delete.
       """
       print(f"Are you sure you wany to delete model {model_arn} ?\n", model_arn)
   
       start = input("Enter delete to delete your model: ")
       if start == "delete":
           return True
       else:
           return False
   
   
   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()
   
           if confirm_model_deletion(args.model_arn) is True:
               print(f"Deleting model: {args.model_arn}")
   
               # Delete the model.
               session = boto3.Session(profile_name='custom-labels-access')
               rekognition_client = session.client("rekognition")
   
               delete_model(rekognition_client,
                            args.project_arn,
                            args.model_arn)
   
               print(f"Finished deleting model: {args.model_arn}")
           else:
               print(f"Not deleting model {args.model_arn}")
   
       except ClientError as err:
           print(f"Problem deleting model: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]
   + `project_arn` - 削除するモデルを含むプロジェクトの ARN。
   + `model_arn` - 削除するモデルのバージョンの ARN。

   ```
   //Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-custom-labels-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import java.net.URI;
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   
   import software.amazon.awssdk.services.rekognition.model.DeleteProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.DeleteProjectVersionResponse;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   public class DeleteModel {
   
       public static final Logger logger = Logger.getLogger(DeleteModel.class.getName());
   
       public static int findForwardSlash(String modelArn, int n) {
   
           int start = modelArn.indexOf('/');
           while (start >= 0 && n > 1) {
               start = modelArn.indexOf('/', start + 1);
               n -= 1;
           }
           return start;
   
       }
   
       public static void deleteMyModel(RekognitionClient rekClient, String projectArn, String modelArn)
               throws InterruptedException {
   
           try {
   
               logger.log(Level.INFO, "Deleting model: {0}", projectArn);
   
               // Delete the model
   
               DeleteProjectVersionRequest deleteProjectVersionRequest = DeleteProjectVersionRequest.builder()
                       .projectVersionArn(modelArn).build();
   
               DeleteProjectVersionResponse response =
                       rekClient.deleteProjectVersion(deleteProjectVersionRequest);
   
               logger.log(Level.INFO, "Status: {0}", response.status());
   
               // Get the model version
   
               int start = findForwardSlash(modelArn, 3) + 1;
               int end = findForwardSlash(modelArn, 4);
   
               String versionName = modelArn.substring(start, end);
   
               Boolean deleted = false;
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                       .projectArn(projectArn).versionNames(versionName).build();
   
               // Wait until model is deleted.
   
               do {
   
                   DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                           .describeProjectVersions(describeProjectVersionsRequest);
   
                   if (describeProjectVersionsResponse.projectVersionDescriptions().size()==0) {
                       logger.log(Level.INFO, "Waiting for model deletion: {0}", modelArn);
                       Thread.sleep(5000);
                   } else {
                       deleted = true;
                       logger.log(Level.INFO, "Model deleted: {0}", modelArn);
                   }
                   
               } while (Boolean.FALSE.equals(deleted));
   
               logger.log(Level.INFO, "Model deleted: {0}", modelArn);
   
           } catch (
   
           RekognitionException e) {
               logger.log(Level.SEVERE, "Client error occurred: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> <model_arn>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the model that you want to delete.\n\n"
                   + "   model_version - The ARN of the model that you want to delete.\n\n";
   
           if (args.length != 2) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           String projectArn = args[0];
           String modelVersion = args[1];
   
           try {
   
               RekognitionClient rekClient = RekognitionClient.builder().build();
   
               // Delete the model
               deleteMyModel(rekClient, projectArn, modelVersion);
   
               System.out.println(String.format("model deleted: %s", modelVersion));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
           catch (InterruptedException intError) {
               logger.log(Level.SEVERE, "Exception while sleeping: {0}", intError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------