

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 執行培訓過的 Amazon Rekognition 自訂標籤模型
<a name="running-model"></a>

當您對模型的效能感到滿意時，您便可以開始使用它。您可以使用 主控台或 AWS SDK 來啟動和停止模型。主控台還包括您可以使用的範例 SDK 操作。

**Topics**
+ [推論單元](#running-model-inference-units)
+ [可用區域](#running-model-availability-zones)
+ [啟動 Amazon Rekognition 自訂標籤模型](rm-start.md)
+ [停止 Amazon Rekognition 自訂標籤模型](rm-stop.md)
+ [報告使用的執行持續時間和推論單元](rm-model-usage.md)

## 推論單元
<a name="running-model-inference-units"></a>

當您啟動模型時，您可以指定模型使用的計算資源 (稱為推論單元) 的數量。

**重要**  
根據您配置模型執行的方式，您需要根據模型執行的時數以及模型執行時使用的推理單元的數量付費。例如，您使用兩個推論單元啟動模型，並使用該模型 8 小時，則需支付 16 個推論時數的費用（8 小時執行時間 \$1 2 個推論單元）。如需更多詳細資訊，請參閱 [推論時數](https://aws.amazon.com/rekognition/pricing/#Amazon_Rekognition_Custom_Labels_pricing)。如果您沒有明確 [停止模型](rm-stop.md)，即使您沒有主動使用模型分析圖像，仍需支付費用。

單一推論單元支援的每秒交易數 (TPS) 會受到以下項目的影響。
+ 偵測影像層級標籤 (分類) 的模型，通常比偵測和使用週框方塊定位物件 (物件偵測) 的模型具有更高的 TPS。
+ 模型的複雜性。
+ 解析度較高的影像需要更多時間進行分析。
+ 圖像中的物體越多，需要更多時間進行分析。
+ 較小的圖像比較大的圖像的分析速度更快。
+ 以圖像位元組形式傳遞的圖像的分析速度比先將圖像上傳到 Amazon S3 儲存貯體然後引用上傳的圖像要快。作為圖像位元組傳遞的圖像必須小於 4.0 MB。我們建議您在圖像大小小於 4.0 MB 時使用圖像位元組進行近乎即時的圖像處理。例如，從 IP 攝影機擷取的圖像。
+ 處理儲存在 Amazon S3 儲存貯體中的圖像比下載圖像、轉換為圖像位元組，然後傳遞圖像位元組進行的分析更快。
+ 分析已儲存在 Amazon S3 儲存貯體中的圖像可能比分析作為圖像位元組傳遞的相同圖像更快。如果圖像較大，則尤其如此。

如果呼叫次數 `DetectCustomLabels` 超過模型使用的推論單元總和支援的最大 TPS，Amazon Rekognition 自訂標籤將傳回 `ProvisionedThroughputExceededException` 異常。

### 使用推論單元管理輸送量
<a name="running-model-manage-throughput"></a>

您可以根據應用程式的需求增加或減少模型的輸送量。若要增加輸送量，請使用額外的推論單元。每個額外的推論單元都會將您的處理速度提高一個推論單元。有關計算所需推論單元數量的資訊，請參閱 [計算 Amazon Rekognition 自訂標籤和 Amazon Lookout for Vision 模型的推論單元](https://aws.amazon.com/blogs/machine-learning/calculate-inference-units-for-an-amazon-rekognition-custom-labels-model/)。如果您想要變更模型的支援輸送量，您有兩種選擇：

#### 手動新增或刪除推論單元
<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 自訂標籤可以自動擴展模型使用的推論單元數量。隨著需求的增加，Amazon Rekognition 自訂標籤會在模型中新增額外的推論單元，並在需求減少時將其移除。

若要讓 Amazon Rekognition 自訂標籤自動擴展模型的推論單元，請 [啟動](rm-start.md) 模型並使用該 `MaxInferenceUnits` 參數設定可使用的推論單元數目上限。設定推論單元的最大數量可讓您透過限制可用的推論單元數量來管理執行模型的成本。如果您未指定單元數目上限，Amazon Rekognition 自訂標籤不會自動擴展模型，只會使用您開始使用的推論單元數量。如需推論單元數目上限的更多詳細資訊，請參閱 [Service Quotas](https://docs.aws.amazon.com/general/latest/gr/rekognition.html#limits_rekognition)。

您也可以使用 `MinInferenceUnits` 參數指定最小推論單元數量。這可讓您指定模型的最小輸送量，其中單一推論單元代表 1 小時的處理時間。

**注意**  
您無法使用 Amazon Rekognition 自訂標籤主控台設定推論單元的數量上限。相反，請指定 `StartProjectVersion` 操作的 `MaxInferenceUnits` 輸入參數。

Amazon Rekognition 自訂標籤提供下列 Amazon CloudWatch Logs 指標，您可以使用這些指標來判斷模型目前的自動擴展狀態。


| 指標 | Description | 
| --- | --- | 
|  `DesiredInferenceUnits`  |  Amazon Rekognition 自訂標籤要縱向擴展或縮減的推論單元數量。  | 
|  `InServiceInferenceUnits`  |  模型正在使用的推論單元數目。  | 

如果 `DesiredInferenceUnits` = `InServiceInferenceUnits`，則 Amazon Rekognition 自訂標籤目前不會擴展推論單元的數量。

如果 `DesiredInferenceUnits` > `InServiceInferenceUnits`，則 Amazon Rekognition 自訂標籤將縱向擴展到的 `DesiredInferenceUnits` 值。

如果 `DesiredInferenceUnits` < `InServiceInferenceUnits`，則 Amazon Rekognition 自訂標籤將縮減規模為的 `DesiredInferenceUnits` 值。

 如需 Amazon Rekognition 自訂標籤和篩選維度傳回的指標的更多詳細資訊，請參閱 [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 自訂標籤會將推論單元分散到一個 AWS 區域內的多個可用區域，以提供更高的可用性。如需更多詳細資訊，請參閱 [可用區域](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/#Availability_Zones)。為了協助保護您的生產模型免於可用區域中斷和推論單元故障的影響，請至少使用兩個推論單元來啟動生產模型。

如果發生可用區域中斷的情況，則可用區域中的所有推論單元將無法使用，且模型容量也會降低。對 [檢測自訂標籤](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels) 的呼叫會重新分配至其餘的推論單元。如果這類呼叫未超過其餘推論單元所支援的每秒交易數 (TPS)，則此類呼叫就會成功。AWS 修復可用區域後，推論單元會重新啟動，並恢復完整容量。

如果單一推論單元發生故障，Amazon Rekognition 自訂標籤會在相同的可用區域中自動啟動新的推論單元。模型容量會減少，直到新的推論單元啟動為止。

# 啟動 Amazon Rekognition 自訂標籤模型
<a name="rm-start"></a>

您可以使用主控台或 [啟動專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion) 操作開始執行 Amazon Rekognition 自訂標籤模型。

**重要**  
您需要根據模型執行的時數以及模型執行時使用的推論單元數量付費。如需詳細資訊，請參閱[執行培訓過的 Amazon Rekognition 自訂標籤模型](running-model.md)。

啟動模型可能需要幾分鐘才能完成。若要檢查模型準備的目前狀態，請檢查專案的詳細資訊頁面或使用 [描述專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions)。

模型啟動後，您可以使用 [檢測自訂標籤](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels) 來分析使用模型的圖像。如需詳細資訊，請參閱[使用經過培訓的模型分析圖像](detecting-custom-labels.md)。主控台也提供了呼叫 `DetectCustomLabels` 的範例程式碼。

**Topics**
+ [啟動 Amazon Rekognition 自訂標籤模型 (主控台)](#rm-start-console)
+ [啟動 Amazon Rekognition 自訂標籤模型 (SDK)](#rm-start-sdk)

## 啟動 Amazon Rekognition 自訂標籤模型 (主控台)
<a name="rm-start-console"></a>

跟隨以下步驟，開始透過主控台執行 Amazon Rekognition 自訂標籤模型。您可以從 主控台直接啟動模型，或使用 主控台提供的 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 自訂標籤模型](running-model.md)。

   1. 選擇 **開始使用**。

   1. 在 **啟動模型** 的對話框中，選擇 **啟動**。

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

   在 **使用模型** 的區域中，執行以下操作：

   1. 選擇 **API 程式碼。**

   1. 選擇 **AWS CLI** 或 **Python**。

   1. 在 **啟動模型** 中複製範例程式碼。

   1. 使用範例程式碼來啟動模型。如需詳細資訊，請參閱[啟動 Amazon Rekognition 自訂標籤模型 (SDK)](#rm-start-sdk)。

------

1. 若要返回專案概述頁面，請選擇頁面頂部的專案名稱。

1. 在 **模型** 的區域中，檢查模型的狀態。當模型狀態為 **執行中** 時，您可以使用模型來分析圖像。如需詳細資訊，請參閱[使用經過培訓的模型分析圖像](detecting-custom-labels.md)。

## 啟動 Amazon Rekognition 自訂標籤模型 (SDK)
<a name="rm-start-sdk"></a>

您可透過呼叫 [啟動模型版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion) API 並在 `ProjectVersionArn` 輸入參數中傳遞模型的 Amazon Resource Name (ARN) 來啟動模型。您也可指定您要使用的推論單元數量。如需詳細資訊，請參閱[執行培訓過的 Amazon Rekognition 自訂標籤模型](running-model.md)。

模型可能需要一段時間才能啟動。本主題中的 Python 和 Java 範例使用等待程式來等待模型啟動。等待程式是一種實用程式方法，用於輪詢特定狀態發生。或者，您可以通過呼叫 [描述專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) 來檢查當前狀態。

**啟動模型 (SDK)**

1. 如果您尚未這麼做，請安裝並設定 AWS CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 4：設定 AWS CLI 和 AWS SDKs](su-awscli-sdk.md)。

1. 使用以下範例程式碼來啟動模型。

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

   將 `project-version-arn` 的值變更為您要啟動的模型的 ARN。將 `--min-inference-units` 的值變更為您要使用的推論單元數量。（可選）將 `--max-inference-units` 變更為 Amazon Rekognition 自訂標籤可用於自動擴展模型的最大推論單元數量。

   ```
   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 自訂標籤可用於自動擴展模型的最大推論單元數量。

   ```
   # 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 自訂標籤可用於自動擴展模型的最大推論單元數量。如果您未有指定值，則不會進行自動擴展。

   ```
   /*
      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 自訂標籤模型
<a name="rm-stop"></a>

您可以使用主控台或 [停止專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) 操作停止執行 Amazon Rekognition 自訂標籤模型。

**Topics**
+ [停止 Amazon Rekognition 自訂標籤模型 (主控台)](#rm-stop-console)
+ [停止 Amazon Rekognition 自訂標籤模型 (SDK)](#rm-stop-sdk)

## 停止 Amazon Rekognition 自訂標籤模型 (主控台)
<a name="rm-stop-console"></a>

請使用以下步驟來停止執行中的 Amazon Rekognition 自訂標籤模型。您可以從 主控台直接停止模型，或使用 主控台提供的 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 自訂標籤模型 (SDK)](#rm-stop-sdk)。

------

1. 在頁面頂端選擇您的專案名稱，以返回專案概述頁面。

1. 在 **模型** 的區域中，檢查模型的狀態。當模型狀態顯示為 **已停止** 時，則表示模型已經停止。

## 停止 Amazon Rekognition 自訂標籤模型 (SDK)
<a name="rm-stop-sdk"></a>

您可以透過呼叫 [停止專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API 並在 `ProjectVersionArn` 輸入參數中傳遞模型的 Amazon Resource Name (ARN) 來停止模型。

模型可能需要一段時間才能停止。若要檢查目前狀態，請使用 `DescribeProjectVersions`。

**停止模型 (SDK)**

1. 如果您尚未這麼做，請安裝並設定 AWS CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 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 區域中只有一個模型，您也可以在 CloudWatch `StopProjectVersion`中追蹤對 `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：//[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 的區域。檢查頁面頂端導覽列中的區域選擇器，確認 CloudWatch 主控台位於相同 AWS 區域。根據需要進行更新。

   ```
   {
       "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/zh_tw/rekognition/latest/customlabels-dg/images/model-duration.png)

1. (可選) 透過選擇 **動作**，然後 **新增至儀表板－改進**，將圖表新增至儀表板。