

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition
<a name="rm-start"></a>

Vous pouvez commencer à exécuter un modèle d'étiquettes personnalisées Amazon Rekognition à l'aide de la console ou à l'aide de l'opération. [StartProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion)

**Important**  
Vous êtes facturé en fonction du nombre d’heures d’exécution de votre modèle et du nombre d’unités d’inférence qu’il utilise pendant son exécution. Pour plus d’informations, consultez [Exécution d’un modèle Étiquettes personnalisées Amazon Rekognition entraîné](running-model.md).

Le démarrage d’un modèle peut prendre quelques minutes. Pour vérifier l'état actuel de préparation du modèle, consultez la page de détails du projet ou de l'utilisation [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions).

Une fois le modèle démarré, vous utilisez [DetectCustomLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectCustomLabels), pour analyser les images à l'aide du modèle. Pour de plus amples informations, veuillez consulter [Analyse d’une image avec un modèle entraîné](detecting-custom-labels.md). La console fournit également un exemple de code pour appeler `DetectCustomLabels`. 

**Topics**
+ [Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition (Console)](#rm-start-console)
+ [Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition (kit SDK)](#rm-start-sdk)

## Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition (Console)
<a name="rm-start-console"></a>

Utilisez la procédure suivante pour commencer à exécuter un modèle Étiquettes personnalisées Amazon Rekognition avec la console. Vous pouvez démarrer le modèle directement depuis la console ou utiliser le code AWS SDK fourni par la console. 

**Pour démarrer un modèle (console)**

1. Ouvrez la console Amazon Rekognition à l'adresse. [https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)

1. Choisissez **Utiliser Custom Labels**.

1. Choisissez **Démarrer**. 

1. Dans le volet de navigation de gauche, choisissez **Projets**.

1. Sur la page des ressources **Projets**, choisissez le projet qui contient le modèle entraîné que vous souhaitez démarrer.

1. Dans la section **Modèles**, choisissez le modèle que vous souhaitez démarrer. 

1. Choisissez l’onglet **Utiliser le modèle**.

1. Effectuez l’une des actions suivantes :

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

   Dans la section **Démarrer ou arrêter le modèle**, procédez comme suit :

   1. Sélectionnez le nombre d’unités d’inférence que vous souhaitez utiliser. Pour plus d’informations, consultez [Exécution d’un modèle Étiquettes personnalisées Amazon Rekognition entraîné](running-model.md).

   1. Sélectionnez **Démarrer**.

   1. Dans la boîte de dialogue **Démarrer le modèle**, choisissez **Démarrer**. 

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

   Dans la section **Utiliser votre modèle**, procédez comme suit :

   1. Choisissez **Code de l’API**.

   1. Choisissez **AWS CLI** ou **Python**.

   1. Dans **Démarrer le modèle**, copiez l’exemple de code.

   1. Utilisez l’exemple de code pour démarrer votre modèle. Pour plus d’informations, consultez [Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition (kit SDK)](#rm-start-sdk).

------

1. Pour revenir à la page de présentation du projet, choisissez le nom de votre projet en haut de la page.

1. Dans la section **Modèle**, vérifiez le statut du modèle. Lorsque le statut du modèle est **EN COURS D’EXÉCUTION**, vous pouvez utiliser le modèle pour analyser des images. Pour plus d’informations, consultez [Analyse d’une image avec un modèle entraîné](detecting-custom-labels.md).

## Démarrage d’un modèle Étiquettes personnalisées Amazon Rekognition (kit SDK)
<a name="rm-start-sdk"></a>

Vous démarrez un modèle en appelant l'[StartProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartProjectVersion)API et en transmettant le nom de ressource Amazon (ARN) du modèle dans le paramètre `ProjectVersionArn` d'entrée. Vous spécifiez également le nombre d’unités d’inférence que vous souhaitez utiliser. Pour plus d’informations, consultez [Exécution d’un modèle Étiquettes personnalisées Amazon Rekognition entraîné](running-model.md).

Le démarrage d’un modèle peut prendre un certain temps. Les exemples Python et Java présentés dans cette rubrique utilisent des programmes d’attente pour attendre le démarrage du modèle. Un programme d’attente est un utilitaire qui attend qu’un statut particulier survienne. Vous pouvez également vérifier l'état actuel en appelant [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions). 

**Pour démarrer un modèle (kit SDK)**

1. Si ce n'est pas déjà fait, installez et configurez le AWS CLI et le AWS SDKs. Pour de plus amples informations, veuillez consulter [Étape 4 : configurer le AWS CLI et AWS SDKs](su-awscli-sdk.md).

1. Utilisez l’exemple de code suivant pour démarrer un modèle.

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

   Remplacez la valeur de `project-version-arn` par l’ARN du modèle que vous souhaitez démarrer. Remplacez la valeur de `--min-inference-units` par le nombre d’unités d’inférence que vous souhaitez utiliser. (Facultatif) Modifiez `--max-inference-units` par le nombre maximum d’unités d’inférence que la fonctionnalité Étiquettes personnalisées Amazon Rekognition peut utiliser pour automatiquement mettre à l’échelle le modèle.

   ```
   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 ]

   Fournissez les paramètres de ligne de commande suivants :
   + `project_arn` : l’ARN du projet contenant le modèle que vous souhaitez démarrer.
   + `model_arn` : l’ARN du modèle que vous souhaitez démarrer.
   + `min_inference_units` : le nombre d’unités d’inférence que vous souhaitez utiliser.
   + (Facultatif) `--max_inference_units` : le nombre maximum d’unités d’inférence que la fonctionnalité Étiquettes personnalisées Amazon Rekognition peut utiliser pour automatiquement mettre à l’échelle le modèle. 

   ```
   # 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 ]

   Fournissez les paramètres de ligne de commande suivants :
   + `project_arn` : l’ARN du projet contenant le modèle que vous souhaitez démarrer.
   + `model_arn` : l’ARN du modèle que vous souhaitez démarrer.
   + `min_inference_units` : le nombre d’unités d’inférence que vous souhaitez utiliser.
   + (Facultatif) `max_inference_units` : le nombre maximum d’unités d’inférence que la fonctionnalité Étiquettes personnalisées Amazon Rekognition peut utiliser pour automatiquement mettre à l’échelle le modèle. Si vous ne spécifiez pas de valeur, la mise à l’échelle automatique ne se produit pas.

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

------