

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 훈련된 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>

모델을 시작할 때 모델에서 사용하는 컴퓨팅 리소스(추론 단위라고도 함)의 수를 지정합니다.

**중요**  
모델 실행 구성 방법에 따라 모델이 실행되는 시간 및 모델이 실행되는 동안 사용하는 추론 단위 수에 대한 요금이 부과됩니다. 예를 들어 두 개의 추론 단위로 모델을 시작하고 8시간 동안 모델을 사용하면 추론 시간 16시간 (실행 시간 8시간\$1 추론 단위 2개) 에 대한 요금이 부과됩니다. 자세한 정보는 [추론 시간](https://aws.amazon.com/rekognition/pricing/#Amazon_Rekognition_Custom_Labels_pricing)을 참조하세요. 명시적으로 [모델을 중지하지 않으면](rm-stop.md) 모델로 이미지를 적극적으로 분석하지 않더라도 요금이 부과됩니다.

단일 추론 단위가 지원하는 초당 트랜잭션 수(TPS)는 다음의 영향을 받습니다.
+ 이미지 수준 레이블(분류)을 탐지하는 모델은 일반적으로 객체를 감지하고 경계 상자로 객체의 위치를 파악하는 모델(객체 감지)보다 TPS가 높습니다.
+ 모델의 복잡성
+ 해상도가 높은 이미지는 분석에 더 많은 시간이 필요합니다.
+ 이미지에 객체가 많을수록 분석하는 데 더 많은 시간이 필요합니다.
+ 작은 이미지는 큰 이미지보다 빠르게 분석됩니다.
+ 이미지 바이트로 전달된 이미지는 먼저 Amazon S3 버킷에 이미지를 업로드한 다음 업로드된 이미지를 참조하는 것보다 빠르게 분석됩니다. 이미지 바이트로 전달된 이미지는 4.0MB 미만이어야 합니다. 이미지를 거의 실시간으로 처리하고 이미지 크기가 4.0MB 미만인 경우에는 이미지 바이트를 사용하는 것이 좋습니다. 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/)을 참조하세요. 모델의 지원되는 처리량을 변경하려면 다음 두 가지 옵션이 있습니다.

#### 수동으로 추론 유닛을 추가하거나 제거합니다.
<a name="running-model-manual-inference-units"></a>

모델을 [중지](rm-stop.md)한 다음 필요한 수의 추론 단위로 [다시 시작](rm-start.md)합니다. 이 접근 방식의 단점은 모델을 다시 시작하는 동안 요청을 받을 수 없고 급증하는 수요를 처리하는 데 사용할 수 없다는 것입니다. 모델의 처리량이 안정적이고 사용 사례가 10\$120분의 가동 중지 시간을 견딜 수 있는 경우 이 접근 방식을 사용하세요. 예를 들어 주간 일정을 사용하여 모델과의 통화를 일괄 처리하려는 경우를 들 수 있습니다.

#### 추론 단위 자동 규모 조정
<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시간의 처리 시간을 나타냅니다.

**참고**  
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에서 반환되는 지표 및 필터링 차원에 대한 자세한 내용은 [Rekognition용 CloudWatch 지표](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)을 참조하세요. 가용 영역 중단 및 추론 단위 장애로부터 프로덕션 모델을 보호하려면 최소 두 개의 추론 단위로 프로덕션 모델을 시작하십시오.

가용 영역이 중단되면 가용 영역의 모든 추론 유닛을 사용할 수 없게 되고 모델 용량이 감소합니다. [DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels)에 대한 직접 호출은 나머지 추론 단위에 재분배됩니다. 이러한 직접 호출은 나머지 추론 단위의 지원되는 초당 트랜잭션 수(TPS)를 초과하지 않으면 성공합니다. AWS가 가용 영역을 복구하면 추론 유닛이 다시 시작되고 전체 용량이 복원됩니다.

단일 추론 단위에 장애가 발생하는 경우 Amazon Rekognition Custom Labels는 동일한 가용 영역에서 새 추론 단위를 자동으로 시작합니다. 새 추론 단위가 시작되기 전까지는 모델 용량이 줄어듭니다.

# Amazon Rekognition Custom Labels 모델 시작
<a name="rm-start"></a>

콘솔을 사용하거나 [StartProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion) 작업을 사용하여 Amazon Rekognition Custom Labels 모델 실행을 시작할 수 있습니다.

**중요**  
모델이 실행되는 시간 수와 모델이 실행되는 동안 사용하는 추론 단위 수에 따라 요금이 부과됩니다. 자세한 내용은 [훈련된 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. [https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)에서 Amazon Rekognition 콘솔을 엽니다.

1. **사용자 지정 레이블 사용**을 선택합니다.

1. **Get started**를 선택합니다.

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. **모델** 항목에서 모델의 상태를 확인합니다. 모델 상태가 **실행 중**이면 모델을 사용하여 이미지를 분석할 수 있습니다. 자세한 내용은 [훈련된 모델을 사용한 이미지 분석](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 예제에서는 웨이터를 사용하여 모델이 시작되기를 기다립니다. Waiter는 특정 상태에 대해 폴링되는 유틸리티 메서드입니다. 또는 [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>

콘솔을 사용하거나 [StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) 작업을 사용하여 Amazon Rekognition Custom Labels 모델 실행을 중단할 수 있습니다.

**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. [https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)에서 Amazon Rekognition 콘솔을 엽니다.

1. **사용자 지정 레이블 사용**을 선택합니다.

1. **Get started**를 선택합니다.

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 리전에 모델이 하나만 있는 경우 CloudWatch에서 `StartprojectVersion` 및에 대한 성공적인 호출을 추적하여 모델의 실행 시간을 얻을 수도 `StopProjectVersion` 있습니다. 지표에 모델에 대한 정보가 포함되어 있지 않으므로 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 Management Console 하고 [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/ko_kr/rekognition/latest/customlabels-dg/images/model-duration.png)

1. (선택 사항) 대시보드에 그래프를 추가하려면 **작업**을 선택한 후 **대시보드에 추가 - 개선됨**을 선택합니다.