

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

# トレーニング済み Amazon Rekognition Custom Labels の実行
<a name="running-model"></a>

モデルのパフォーマンスに満足している場合は、使用を開始できます。コンソールまたは AWS SDK を使用して、モデルを開始および停止できます。コンソールには、使用可能な SDK オペレーションの例も含まれています。

**Topics**
+ [推論単位](#running-model-inference-units)
+ [アベイラビリティーゾーン](#running-model-availability-zones)
+ [Amazon Rekognition Custom Labels モデルを開始する](rm-start.md)
+ [Amazon Rekognition Custom Labels モデルの停止](rm-stop.md)
+ [実行時間と使用された推論単位のレポート](rm-model-usage.md)

## 推論単位
<a name="running-model-inference-units"></a>

モデルの開始時に、モデルが使用する推論単位と呼ばれるコンピューティングリソースの数を指定します。

**重要**  
モデルの実行の設定方法に基づいて、モデルの実行時間数と、モデルの実行中にモデルが使用する推論単位の数に対して課金されます。例えば、モデルを 2 推論単位で開始し、モデルを 8 時間使用すると、16 推論時間 (8 時間実行時間 × 2 推論単位) に対して課金されます。詳細については、「[推論時間](https://aws.amazon.com/rekognition/pricing/#Amazon_Rekognition_Custom_Labels_pricing)」を参照してください。明示的に[モデルを停止](rm-stop.md)しないと、モデルでイメージをアクティブに分析していない場合でも課金されます。

1 つの推論単位がサポートする 1 秒あたりのトランザクション (TPS) は、次の影響を受けます。
+ 一般に、イメージレベルのラベルを検出するモデル (分類) は、境界ボックスでオブジェクトを検出してローカライズするモデル (オブジェクト検出) よりも TPS が高くなります。
+ モデルの複雑さ。
+ 高解像度のイメージでは、分析に時間がかかります。
+ イメージ内のオブジェクトが多いほど、分析に時間がかかります。
+ 小さなイメージは、大きなイメージよりも速く分析されます。
+ イメージバイトとして渡されたイメージは、最初に Amazon S3 バケットにアップロードしてからアップロードされたイメージを参照するよりも速く分析されます。イメージバイトとして渡されるイメージは 4.0 MB 未満である必要があります。イメージをほぼリアルタイムで処理する場合や、イメージサイズが 4.0 MB 未満の場合は、イメージバイトを使用することをお勧めします。例えば、IP カメラからキャプチャされたイメージなど。
+ Amazon S3 バケットに保存されたイメージの処理は、イメージをダウンロードしてイメージバイトに変換し、分析用にイメージバイトを渡すよりも高速です。
+ Amazon S3 バケットに既に保存されたイメージの分析は、イメージバイトとして渡されたイメージを分析するよりも高速です。これは特にイメージサイズが大きい場合に当てはまります。

`DetectCustomLabels` への呼び出し数が、モデルが使用する推論単位の合計でサポートされる最大 TPS を超えると、Amazon Rekognition Custom Labels は `ProvisionedThroughputExceededException` 例外を返します。

### 推論単位によるスループットの管理
<a name="running-model-manage-throughput"></a>

アプリケーションの要求に応じて、モデルのスループットを増やしたり減らしたりすることができます。スループットを増やすには、追加の推論ユニットを使用します。推論ユニットを追加するたびに、処理速度が 1 推論ユニット増加します。必要な推論ユニット数の計算方法については、「[Amazon Rekognition Custom Labels と Amazon Lookout for Vision モデルの推論単を計算する](https://aws.amazon.com/blogs/machine-learning/calculate-inference-units-for-an-amazon-rekognition-custom-labels-model/)」を参照してください。モデルのサポート対象スループットを変更する場合は、次の 2 つのオプションがあります: 

#### 手動で推論ユニットを追加または削除する
<a name="running-model-manual-inference-units"></a>

モデルを[停止](rm-stop.md)し、必要な推論ユニット数で[再開](rm-start.md)します。この方法の欠点は、再開中はモデルがリクエストを受け取ることができず、需要の急増に対処できないことです。モデルのスループットが安定していて、ユースケースが 10 ～ 20 分のダウンタイムを許容できる場合は、このアプローチを使用してください。例としては、週ユニットのスケジュールを使用してモデルへの呼び出しをバッチ処理する場合などが挙げられます。

#### 推論単位の自動スケーリング
<a name="running-model-auto-scale-inference-units"></a>

モデルの需要の急増に対応する必要がある場合、Amazon Rekognition Custom Labels はモデルが使用する推論単位の数を自動的にスケールできます。需要が増加すると、Amazon Rekognition Custom Labels はモデルに追加の推論単位を追加し、需要が減少するとそれらを削除します。

Amazon Rekognition Custom Labels がモデルの推論単位を自動的にスケールできるようにするには、モデルを[開始し](rm-start.md)、`MaxInferenceUnits` パラメータを使用して使用できる推論単位の最大数を設定します。推論単位の最大数を設定すると、使用可能な推論単位の数を制限することにより、モデルの実行コストを管理できます。最大単位数を指定しない場合、Amazon Rekognition Custom Labels はモデルを自動的にスケールせず、最初に使用した推論単位数のみを使用します。推論単位の最大数については、「[Service Quotas](https://docs.aws.amazon.com/general/latest/gr/rekognition.html#limits_rekognition)」を参照してください。

`MinInferenceUnits` パラメータを使用して推論ユニットの最小数も指定できます。これにより、モデルの最小スループットを指定できます。1 つの推論単位は 1 時間の処理時間を表します。

**注記**  
Amazon Rekognition Custom Labels では、推論単位の最大数を設定することはできません。代わりに、`StartProjectVersion` オペレーションに `MaxInferenceUnits` 入力パラメータを指定してください。

Amazon Rekognition Custom Labels には、モデルの現在の自動スケーリングステータスを判断するために使用できる次の Amazon CloudWatch Logs メトリクスが用意されています。


| メトリクス | 説明 | 
| --- | --- | 
|  `DesiredInferenceUnits`  |  Amazon Rekognition Custom Labels がスケールアップまたはスケールダウンの対象となる推論単位の数。  | 
|  `InServiceInferenceUnits`  |  モデルが使用している推論単位の数。  | 

`DesiredInferenceUnits` = `InServiceInferenceUnits` の場合、Amazon Rekognition Custom Labels は現在、推論単位の数をスケールしていません。

`DesiredInferenceUnits` > `InServiceInferenceUnits` の場合、Amazon Rekognition Custom Labels は `DesiredInferenceUnits` の値までスケールアップされます。

`DesiredInferenceUnits` < `InServiceInferenceUnits` の場合、Amazon Rekognition Custom Labels は `DesiredInferenceUnits` の値にスケールダウンされます。

 Amazon Rekognition Custom Labels によって返されるメトリクスとフィルタリングディメンションの詳細については、「[CloudWatch metrics for Rekognition](https://docs.aws.amazon.com/rekognition/latest/dg/cloudwatch-metricsdim.html)」を参照してください。

モデルにリクエストした推論単位の最大数を確認するには、`DescribeProjectsVersion` を呼び出して応答の `MaxInferenceUnits` フィールドを確認します。サンプルコードについては、「[モデルの記述 (SDK)](md-describing-model-sdk.md)」を参照してください。

## アベイラビリティーゾーン
<a name="running-model-availability-zones"></a>

Amazon Rekognition Custom Labels は、 AWS リージョン内の複数のアベイラビリティーゾーンに推論単位を分散させ、可用性を高めています。詳細については、「[アベイラビリティーゾーン](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/#Availability_Zones)」を参照してください。アベイラビリティーゾーンの停止や推論ユニットの障害から量産モデルを保護するために、少なくとも 2 つの推論ユニットを使用して量産モデルを開始することを強くお勧めします。

アベイラビリティーゾーンの停止が発生すると、アベイラビリティーゾーン内のすべての推論単位が使用できなくなり、モデルの容量が削減されます。[DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels) への呼び出しは、残りの推論単位に再配分されます。このような呼び出しは、残りの推論単位のサポートされる TPS (Transactions Per Seconds) を超えていなければ成功します。AWS がアベイラビリティーゾーンを修復した後、推論単位が再起動され、フルキャパシティが復元されます。

1 つの推論単位に障害が発生すると、Amazon Rekognition Custom Labels は同じアベイラビリティーゾーンで新しい推論単位を自動的に開始します。新しい推論単位が始まるまで、モデル容量は減少します。

# Amazon Rekognition Custom Labels モデルを開始する
<a name="rm-start"></a>

Amazon Rekognition Custom Labels モデルの実行を開始するには、コンソールを使用するか [StartProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion) オペレーションを使用します。

**重要**  
モデルを停止するモデルの稼働時間数と、モデルの実行中にモデルが使用する推論単位の数に対して課金されます。詳細については、「[トレーニング済み Amazon Rekognition Custom Labels の実行](running-model.md)」を参照してください。

モデルの開始には数分かかることがあります。モデルの準備状況の現在の状態を確認するには、プロジェクトの詳細ページを確認するか、[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) を使用してください。

モデルを開始したら、[DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels) を使用して、モデルを使用してイメージを解析します。詳細については、「[トレーニングされたモデルによるイメージの分析](detecting-custom-labels.md)」を参照してください。コンソールには `DetectCustomLabels` を呼び出すサンプルコードも用意されています。

**Topics**
+ [Amazon Rekognition Custom Labels モデルの開始 (コンソール)](#rm-start-console)
+ [Amazon Rekognition Custom Labels モデル (SDK) を開始します。](#rm-start-sdk)

## Amazon Rekognition Custom Labels モデルの開始 (コンソール)
<a name="rm-start-console"></a>

以下の手順を使用して、コンソールで Amazon Rekognition Custom Labels モデルの実行を開始します。モデルをコンソールから直接開始することも、コンソールが提供する AWS SDK コードを使用することもできます。

**モデル (コンソール) を開始するには**

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

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

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

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

1. **[プロジェクト]** リソースページで、開始するモデルを含むプロジェクトを選択します。

1. **[モデル]** セクションで、開始するモデルを選択します。

1. **[モデルを使用]** タブを選択します。

1. 次のいずれかを行います。

------
#### [ Start model using the console ]

   **[モデルの開始または停止]** セクションで、次の操作を行います。

   1. 使用する推論単位の数を選択します。詳細については、「[トレーニング済み Amazon Rekognition Custom Labels の実行](running-model.md)」を参照してください。

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

   1. **[モデルを開始]** ダイアログボックスで、**[開始]** を選択します。

------
#### [ Start model using the AWS SDK ]

   **[自分のモデルを使用]** セクションで、次の操作を行います。

   1. **[API コード]** を選択します。

   1. **[AWS CLI]** または **[Python]** のいずれかを選択します。

   1. **[モデルを開始]** で、サンプルコードをコピーします。

   1. このサンプルコードを使用して、モデルを開始します。詳細については、「[Amazon Rekognition Custom Labels モデル (SDK) を開始します。](#rm-start-sdk)」を参照してください。

------

1. プロジェクトの概要ページに戻るには、ページの上部でプロジェクト名を選択します。

1. **[モデル]** セクションで、モデルのステータスを確認します。モデルのステータスが **RUNNING** の場合、モデルを使用してイメージを分析できます。詳細については、「[トレーニングされたモデルによるイメージの分析](detecting-custom-labels.md)」を参照してください。

## Amazon Rekognition Custom Labels モデル (SDK) を開始します。
<a name="rm-start-sdk"></a>

モデルを開始するには、[StartProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion) API を呼び出し、モデルの Amazon リソースネーム (ARN) を `ProjectVersionArn` 入力パラメータに渡します。使用する推論単位の数も指定します。詳細については、「[トレーニング済み Amazon Rekognition Custom Labels の実行](running-model.md)」を参照してください。

モデルの開始までに時間がかかる場合があります。このトピックの Python と Java の例では、ウェーターを使用してモデルの開始を待ちます。ウェーターは、発生する特定の状態をポーリングするユーティリティメソッドです。[DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) を呼び出して現在のステータスを確認することもできます。

**モデル (SDK) を開始するには**

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

1. 次のサンプルコードを使用して、モデルを開始します。

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

   `project-version-arn` の値を開始するモデルの ARN に変更します。`--min-inference-units` の値を使用する推論単位の数に変更します。必要に応じて、`--max-inference-units` を Amazon Rekognition Custom Labels がモデルを自動的にスケールするために使用できる推論単位の最大数に変更します。

   ```
   aws rekognition start-project-version  --project-version-arn model_arn \
      --min-inference-units minimum number of units \
      --max-inference-units maximum number of units \
      --profile custom-labels-access
   ```

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

   次のコマンドラインパラメータを指定します。
   + `project_arn` - 開始するモデルを含むプロジェクトの ARN。
   + `model_arn` - 開始するモデルの ARN。
   + `min_inference_units` - 使用する推論単位の数。
   + (オプション) `--max_inference_units` Amazon Rekognition Custom Labels がモデルの自動スケーリングに使用できる推論単位の最大数。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to start running an Amazon Lookout for Vision model.
   """
   
   import argparse
   import logging
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def get_model_status(rek_client, project_arn, model_arn):
       """
       Gets the current status of an Amazon Rekognition Custom Labels model
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_name:  The name of the project that you want to use.
       :param model_arn:  The name of the model that you want the status for.
       :return: The model status
       """
   
       logger.info("Getting status for %s.", model_arn)
   
       # Extract the model version from the model arn.
       version_name = (model_arn.split("version/", 1)[1]).rpartition('/')[0]
   
       models = rek_client.describe_project_versions(ProjectArn=project_arn,
                                                     VersionNames=[version_name])
   
       for model in models['ProjectVersionDescriptions']:
   
           logger.info("Status: %s", model['StatusMessage'])
           return model["Status"]
   
       error_message = f"Model {model_arn} not found."
       logger.exception(error_message)
       raise Exception(error_message)
   
   
   def start_model(rek_client, project_arn, model_arn, min_inference_units, max_inference_units=None):
       """
       Starts the hosting of an Amazon Rekognition Custom Labels model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_name:  The name of the project that contains the
       model that you want to start hosting.
       :param min_inference_units: The number of inference units to use for hosting.
       :param max_inference_units: The number of inference units to use for auto-scaling
       the model. If not supplied, auto-scaling does not happen.
       """
   
       try:
           # Start the model
           logger.info(f"Starting model: {model_arn}. Please wait....")
   
           if max_inference_units is None:
               rek_client.start_project_version(ProjectVersionArn=model_arn,
                                                MinInferenceUnits=int(min_inference_units))
           else:
               rek_client.start_project_version(ProjectVersionArn=model_arn,
                                                MinInferenceUnits=int(
                                                    min_inference_units),
                                                MaxInferenceUnits=int(max_inference_units))
   
           # Wait for the model to be in the running state
           version_name = (model_arn.split("version/", 1)[1]).rpartition('/')[0]
           project_version_running_waiter = rek_client.get_waiter(
               'project_version_running')
           project_version_running_waiter.wait(
               ProjectArn=project_arn, VersionNames=[version_name])
   
           # Get the running status
           return get_model_status(rek_client, project_arn, model_arn)
   
       except ClientError as err:
           logger.exception("Client error: Problem starting model: %s", err)
           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 that the model you want to start."
       )
       parser.add_argument(
           "model_arn", help="The ARN of the model that you want to start."
       )
       parser.add_argument(
           "min_inference_units", help="The minimum number of inference units to use."
       )
       parser.add_argument(
           "--max_inference_units",  help="The maximum number of inference units to use for auto-scaling the model.", required=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()
   
           # Start the model.
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
           
           status = start_model(rekognition_client,
                                args.project_arn, args.model_arn,
                                args.min_inference_units,
                                args.max_inference_units)
   
           print(f"Finished starting model: {args.model_arn}")
           print(f"Status: {status}")
   
       except ClientError as err:
           error_message = f"Client error: Problem starting model: {err}"
           logger.exception(error_message)
           print(error_message)
   
       except Exception as err:
           error_message = f"Problem starting model:{err}"
           logger.exception(error_message)
           print(error_message)
   
   
   if __name__ == "__main__":
       main()
   ```

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

   次のコマンドラインパラメータを指定します。
   + `project_arn` - 開始するモデルを含むプロジェクトの ARN。
   + `model_arn` - 開始するモデルの ARN。
   + `min_inference_units` - 使用する推論単位の数。
   + (オプション) `max_inference_units` - Amazon Rekognition Custom Labels がモデルを自動的にスケールするために使用できる推論単位の最大数。値を指定しない場合、自動スケーリングは行われません。

   ```
   /*
      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.core.waiters.WaiterResponse;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionDescription;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionStatus;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.StartProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.StartProjectVersionResponse;
   import software.amazon.awssdk.services.rekognition.waiters.RekognitionWaiter;
   
   import java.util.Optional;
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class StartModel {
   
       public static final Logger logger = Logger.getLogger(StartModel.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 startMyModel(RekognitionClient rekClient, String projectArn, String modelArn,
               Integer minInferenceUnits, Integer maxInferenceUnits
               ) throws Exception, RekognitionException {
   
           try {
               
               logger.log(Level.INFO, "Starting model: {0}", modelArn);
               
               StartProjectVersionRequest startProjectVersionRequest = null;
               
               if (maxInferenceUnits == null) {
                   startProjectVersionRequest = StartProjectVersionRequest.builder()
                       .projectVersionArn(modelArn)
                       .minInferenceUnits(minInferenceUnits)
                       .build();
               }
               else {
                   startProjectVersionRequest = StartProjectVersionRequest.builder()
                           .projectVersionArn(modelArn)
                           .minInferenceUnits(minInferenceUnits)
                           .maxInferenceUnits(maxInferenceUnits)
                           .build();
                   
               }
   
               StartProjectVersionResponse response = rekClient.startProjectVersion(startProjectVersionRequest);
   
               logger.log(Level.INFO, "Status: {0}", response.statusAsString() );
               
               
               // Get the model version
   
               int start = findForwardSlash(modelArn, 3) + 1;
               int end = findForwardSlash(modelArn, 4);
   
               String versionName = modelArn.substring(start, end);
   
   
               // wait until model starts
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                       .versionNames(versionName)
                       .projectArn(projectArn)
                       .build();
   
               RekognitionWaiter waiter = rekClient.waiter();
   
               WaiterResponse<DescribeProjectVersionsResponse> waiterResponse = waiter
                       .waitUntilProjectVersionRunning(describeProjectVersionsRequest);
   
               Optional<DescribeProjectVersionsResponse> optionalResponse = waiterResponse.matched().response();
   
               DescribeProjectVersionsResponse describeProjectVersionsResponse = optionalResponse.get();
   
               for (ProjectVersionDescription projectVersionDescription : describeProjectVersionsResponse
                       .projectVersionDescriptions()) {
                   if(projectVersionDescription.status() == ProjectVersionStatus.RUNNING) {
                       logger.log(Level.INFO, "Model is running" );
                    
                   }
                   else {
                       String error = "Model training failed: " + projectVersionDescription.statusAsString() + " "
                               + projectVersionDescription.statusMessage() + " " + modelArn;
                       logger.log(Level.SEVERE, error);
                       throw new Exception(error);
                   }
                   
               }
   
   
           } catch (RekognitionException e) {
               logger.log(Level.SEVERE, "Could not start model: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String[] args) {
   
           String modelArn = null;
           String projectArn = null;
           Integer minInferenceUnits = null;
           Integer maxInferenceUnits = null;
           
   
   
   
           final String USAGE = "\n" + "Usage: " + "<project_name> <version_name> <min_inference_units> <max_inference_units>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the model that you want to start. \n\n"
                   + "   model_arn - The ARN of the model version that you want to start.\n\n"
                   + "   min_inference_units - The number of inference units to start the model with.\n\n"
                   + "   max_inference_units - The maximum number of inference units that Custom Labels can use to "
                   + "   automatically scale the model. If the value is null, automatic scaling doesn't happen.\n\n";
   
           if (args.length < 3  || args.length >4) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           projectArn = args[0];
           modelArn = args[1];
           minInferenceUnits=Integer.parseInt(args[2]);
           
           if (args.length == 4) {
               maxInferenceUnits = Integer.parseInt(args[3]);
           }
     
           try {
   
   
               // Get the Rekognition client.
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
               // Start the model.
               startMyModel(rekClient, projectArn, modelArn, minInferenceUnits, maxInferenceUnits);
               
   
               System.out.println(String.format("Model started: %s", modelArn));
   
               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);
           }
   
           
   
       }
   
   }
   ```

------

# Amazon Rekognition Custom Labels モデルの停止
<a name="rm-stop"></a>

Amazon Rekognition Custom Labels モデルの実行を停止するには、コンソールを使用するか [StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) オペレーションを使用します。

**Topics**
+ [Amazon Rekognition Custom Labels モデルの停止 (コンソール)](#rm-stop-console)
+ [Amazon Rekognition Custom Labels モデル (SDK) の停止](#rm-stop-sdk)

## Amazon Rekognition Custom Labels モデルの停止 (コンソール)
<a name="rm-stop-console"></a>

次の手順を使用して、実行中の Amazon Rekognition Custom Labels モデルをコンソールで停止します。モデルをコンソールから直接停止することも、コンソールが提供する AWS SDK コードを使用することもできます。

**モデルを停止するには (コンソール)**

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

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

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

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

1. **[プロジェクト]** リソースページで、停止するモデルを含むプロジェクトを選択します。

1. **[モデル]** セクションで、停止するモデルを選択します。

1. **[モデルを使用]** タブを選択します。

1. 

------
#### [ Stop model using the console ]

   1. **[モデルの開始または停止]** セクションで **[停止]** を選択します。

   1. **[モデルを停止]** ダイアログボックスで、**[停止]** と入力し、モデルを停止することを確認します。

   1. **[停止]** を選択してモデルを停止します。

------
#### [ Stop model using the AWS SDK ]

   **[自分のモデルを使用]** セクションで、次の操作を行います。

   1. **[API コード]** を選択します。

   1. **[AWS CLI]** または **[Python]** のいずれかを選択します。

   1. **[モデルを停止]** で、サンプルコードをコピーします。

   1. サンプルコードを使用してモデルを停止します。詳細については、「[Amazon Rekognition Custom Labels モデル (SDK) の停止](#rm-stop-sdk)」を参照してください。

------

1. ページ上部でプロジェクト名を選択すると、プロジェクトの概要ページに戻ります。

1. **[モデル]** セクションで、モデルのステータスを確認します。モデルのステータスが **[停止しました]** の場合、モデルは停止しています。

## Amazon Rekognition Custom Labels モデル (SDK) の停止
<a name="rm-stop-sdk"></a>

モデルを停止するには、[StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API を呼び出し、モデルの Amazon リソースネーム (ARN) を `ProjectVersionArn` 入力パラメータに渡します。

モデルの停止までに時間がかかる場合があります。現在のステータスを確認するには、`DescribeProjectVersions` を使用します。

**モデル (SDK) を停止するには**

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

1. 次のサンプルコードを使用して、実行中のモデルを停止します。

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

   `project-version-arn` の値を、停止するモデルバージョンの ARN に変更します。

   ```
   aws rekognition stop-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 stop a running Amazon Lookout for Vision model.
   """
   
   import argparse
   import logging
   import time
   import boto3
   
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def get_model_status(rek_client, project_arn, model_arn):
       """
       Gets the current status of an Amazon Rekognition Custom Labels model
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_name:  The name of the project that you want to use.
       :param model_arn:  The name of the model that you want the status for.
       """
   
       logger.info ("Getting status for %s.", model_arn)
   
       # Extract the model version from the model arn.
       version_name=(model_arn.split("version/",1)[1]).rpartition('/')[0]
   
       # Get the model status.
       models=rek_client.describe_project_versions(ProjectArn=project_arn,
       VersionNames=[version_name])
   
       for model in models['ProjectVersionDescriptions']: 
           logger.info("Status: %s",model['StatusMessage'])
           return model["Status"]
   
       # No model found.
       logger.exception("Model %s not found.", model_arn)
       raise Exception("Model %s not found.", model_arn)
   
   
   def stop_model(rek_client, project_arn, model_arn):
       """
       Stops a running Amazon Rekognition Custom Labels Model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_arn: The ARN of the project that you want to stop running.
       :param model_arn:  The ARN of the model (ProjectVersion) that you want to stop running.
       """
   
       logger.info("Stopping model: %s", model_arn)
   
       try:
           # Stop the model.
           response=rek_client.stop_project_version(ProjectVersionArn=model_arn)
   
           logger.info("Status: %s", response['Status'])
   
           # stops when hosting has stopped or failure.
           status = ""
           finished = False
   
           while finished is False:
   
               status=get_model_status(rek_client, project_arn, model_arn)
   
               if status == "STOPPING":
                   logger.info("Model stopping in progress...")
                   time.sleep(10)
                   continue
               if status == "STOPPED":
                   logger.info("Model is not running.")
                   finished = True
                   continue
   
               error_message = f"Error stopping model. Unexepected state: {status}"
               logger.exception(error_message)
               raise Exception(error_message)
   
           logger.info("finished. Status %s", status)
           return status
   
       except ClientError as err:
           logger.exception("Couldn't stop 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 stop."
       )
       parser.add_argument(
           "model_arn", help="The ARN of the model that you want to stop."
       )
   
   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()
   
           # Stop the model.
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           status=stop_model(rekognition_client, args.project_arn, args.model_arn)
   
           print(f"Finished stopping model: {args.model_arn}")
           print(f"Status: {status}")
   
       except ClientError as err:
           logger.exception("Problem stopping model:%s",err)
           print(f"Failed to stop model: {err}")
       
       except Exception as err:
           logger.exception("Problem stopping model:%s", err)
           print(f"Failed to stop model: {err}")
   
   if __name__ == "__main__":
       main()
   ```

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

   次のコマンドラインパラメータを指定します。
   + `project_arn` - 停止するモデルが含まれているプロジェクトの ARN。
   + `model_arn` - 停止するモデルの ARN。

   ```
   /*
      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.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionDescription;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionStatus;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.StopProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.StopProjectVersionResponse;
   
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class StopModel {
   
       public static final Logger logger = Logger.getLogger(StopModel.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 stopMyModel(RekognitionClient rekClient, String projectArn, String modelArn)
               throws Exception, RekognitionException {
   
           try {
   
               logger.log(Level.INFO, "Stopping {0}", modelArn);
   
               StopProjectVersionRequest stopProjectVersionRequest = StopProjectVersionRequest.builder()
                       .projectVersionArn(modelArn).build();
   
               StopProjectVersionResponse response = rekClient.stopProjectVersion(stopProjectVersionRequest);
   
               logger.log(Level.INFO, "Status: {0}", response.statusAsString());
   
               // Get the model version
   
               int start = findForwardSlash(modelArn, 3) + 1;
               int end = findForwardSlash(modelArn, 4);
   
               String versionName = modelArn.substring(start, end);
   
               // wait until model stops
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                       .projectArn(projectArn).versionNames(versionName).build();
   
               boolean stopped = false;
   
               // Wait until create finishes
   
               do {
   
                   DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                           .describeProjectVersions(describeProjectVersionsRequest);
   
                   for (ProjectVersionDescription projectVersionDescription : describeProjectVersionsResponse
                           .projectVersionDescriptions()) {
   
                       ProjectVersionStatus status = projectVersionDescription.status();
   
                       logger.log(Level.INFO, "stopping model: {0} ", modelArn);
   
                       switch (status) {
   
                       case STOPPED:
                           logger.log(Level.INFO, "Model stopped");
                           stopped = true;
                           break;
   
                       case STOPPING:
                           Thread.sleep(5000);
                           break;
   
                       case FAILED:
                           String error = "Model stopping failed: " + projectVersionDescription.statusAsString() + " "
                                   + projectVersionDescription.statusMessage() + " " + modelArn;
                           logger.log(Level.SEVERE, error);
                           throw new Exception(error);
   
                       default:
                           String unexpectedError = "Unexpected stopping state: "
                                   + projectVersionDescription.statusAsString() + " "
                                   + projectVersionDescription.statusMessage() + " " + modelArn;
                           logger.log(Level.SEVERE, unexpectedError);
                           throw new Exception(unexpectedError);
                       }
                   }
   
               } while (stopped == false);
   
           } catch (RekognitionException e) {
               logger.log(Level.SEVERE, "Could not stop model: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String[] args) {
   
           String modelArn = null;
           String projectArn = null;
   
   
           final String USAGE = "\n" + "Usage: " + "<project_name> <version_name>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the model that you want to stop. \n\n"
                   + "   model_arn - The ARN of the model version that you want to stop.\n\n";
   
           if (args.length != 2) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           projectArn = args[0];
           modelArn = args[1];
   
   
           try {
   
               // Get the Rekognition client.
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
               // Stop model
               stopMyModel(rekClient, projectArn, modelArn);
   
               System.out.println(String.format("Model stopped: %s", modelArn));
   
               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);
           }
   
       }
   
   }
   ```

------

# 実行時間と使用された推論単位のレポート
<a name="rm-model-usage"></a>

2022 年 8 月以降にモデルをトレーニングして開始した場合は、`InServiceInferenceUnits` Amazon CloudWatch メトリクスを使用して、モデルの実行時間とその時間中に使用された[推論単位](running-model.md#running-model-inference-units)の数を判断できます。

**注記**  
 AWS リージョンにモデルが 1 つしかない場合は、`StopProjectVersion`CloudWatch で `StartprojectVersion`および への正常な呼び出しを追跡することで、モデルの実行時間を取得することもできます。このアプローチは、メトリクスにモデルに関する情報が含まれていないため、 AWS リージョンで複数のモデルを実行すると機能しません。  
または、 AWS CloudTrail を使用して `StartProjectVersion`および `StopProjectVersion` ([イベント履歴](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html?icmpid=docs_console_unmapped)の `requestParameters`フィールドにモデル ARN を含む) への呼び出しを追跡することもできます。CloudTrail イベントは 90 日間に制限されていますが、[CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) には最大 7 年間イベントを保存できます。

以下の手順では、以下のグラフを作成します。
+ モデルが実行された時間数。
+ モデルが使用した推論単位の数。

過去 15 か月までの期間を選択できます。メトリクスの保持の詳細については、「[メトリクスの保持](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#metrics-retention)」を参照してください。

**モデル期間とモデルに使用される推論単位を決定するには**

1. にサインイン AWS マネジメントコンソール し、[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) で CloudWatch コンソールを開きます。

1. ナビゲーションペインで、**[メトリクス]** から **[すべてのメトリクス]** を選択します。

1. コンテンツペインで、**[ソース]** タブを選択します。

1. **[ダッシュボード]** ボタンが選択されていることを確認します。

1. エディタボックス内で既存の JSON を以下の JSON と置き換えます。以下の値を変更します:
   + `Project_Name` - グラフにするモデルが含まれているプロジェクト。
   + `Version_Name` - グラフにするモデルのバージョン。
   + `AWS_Region` — モデルを含む AWS リージョン。ページ上部のナビゲーションバーの AWS リージョンセレクターをチェックして、CloudWatch コンソールが同じリージョンにあることを確認します。必要に応じて更新します。

   ```
   {
       "sparkline": true,
       "metrics": [
           [
               {
                   "expression": "SUM(m1)*m1",
                   "label": "Inference units used",
                   "id": "e1"
               }
           ],
           [
               {
                   "expression": "DATAPOINT_COUNT(m1)*m1/m1",
                   "label": "Hours running",
                   "id": "e2"
               }
           ],
           [
               "AWS/Rekognition",
               "InServiceInferenceUnits",
               "ProjectName",
               "Project_Name",
               "VersionName",
               "Version_Name",
               {
                   "id": "m1",
                   "visible": false
               }
           ]
       ],
       "view": "singleValue",
       "stacked": false,
       "region": "AWS_Region",
       "stat": "Average",
       "period": 3600,
       "title": "Hours run and inference units used"
   }
   ```

1. **[更新]** を選択します。

1. ページの上部で、[タイムライン] を選択します。タイムライン中に使用した推論単位と実行時間の数値が表示されるはずです。グラフのギャップは、モデルが実行されていなかった時間を示しています。コンソールの以下のスクリーンショットでは、一定期間に使用された推論ユニットとその実行時間を示しています。カスタム期間が 2 週間に設定され、最大値は 214 推論ユニット、209 実行時間となっています。  
![\[推論ユニット数を示すグラフ。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/customlabels-dg/images/model-duration.png)

1. (オプション) グラフをダッシュボードに追加するには、**[アクション]**、**[ダッシュボードに追加 - 改善]** の順に選択します。