

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

# 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);
           }
   
           
   
       }
   
   }
   ```

------