

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Controllo dei risultati della previsione
<a name="async-inference-check-predictions"></a>

Ci sono diversi modi per controllare i risultati delle previsioni dal proprio endpoint asincrono. Alcune di queste opzioni sono:

1. Argomenti di Amazon SNS.

1. Controllo degli output nel tuo bucket Amazon S3.

## Argomenti di Amazon SNS
<a name="async-inference-check-predictions-sns-topic"></a>

Amazon SNS è un servizio di notifica per applicazioni orientate alla messaggistica, in cui più abbonati richiedono e ricevono notifiche push di messaggi urgenti tramite una scelta di protocolli di trasporto, tra cui HTTP, Amazon SQS ed e-mail. Amazon SageMaker Asynchronous Inference invia notifiche quando crei un endpoint con [`CreateEndpointConfig`](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) e specifichi un argomento Amazon SNS.

**Nota**  
Per ricevere le notifiche Amazon SNS, il tuo ruolo IAM deve disporre delle autorizzazioni `sns:Publish`. Consulta [Completa i prerequisiti](async-inference-create-endpoint-prerequisites.md) per informazioni sui requisiti da soddisfare per utilizzare Asynchronous Inference.

Per utilizzare Amazon SNS per controllare i risultati della previsione dal tuo endpoint asincrono, devi prima creare un argomento, abbonarti all'argomento, confermare la tua sottoscrizione all'argomento e annotare il nome della risorsa Amazon (ARN) di quell'argomento. Per informazioni dettagliate su come creare, sottoscrivere e trovare l'ARN Amazon di un argomento Amazon SNS, consulta [Configurazione di Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-configuring.html).

Inserisci gli ARN dell'argomento di Amazon SNS nel campo `AsyncInferenceConfig` quando crei una configurazione endpoint con `CreateEndpointConfig`. Puoi specificare sia un Amazon SNS `ErrorTopic` che un `SuccessTopic`.

```
import boto3

sagemaker_client = boto3.client('sagemaker', region_name=<aws_region>)

sagemaker_client.create_endpoint_config(
    EndpointConfigName={{<endpoint_config_name>}}, # You specify this name in a CreateEndpoint request.
    # List of ProductionVariant objects, one for each model that you want to host at this endpoint.
    ProductionVariants=[
        {
            "VariantName": {{"variant1"}}, # The name of the production variant.
            "ModelName": {{"model_name"}}, 
            "InstanceType": {{"ml.m5.xlarge"}}, # Specify the compute instance type.
            "InitialInstanceCount": {{1}} # Number of instances to launch initially.
        }
    ],
    AsyncInferenceConfig={
        "OutputConfig": {
            # Location to upload response outputs when no location is provided in the request.
            "S3OutputPath": "s3://{{<bucket>/<output_directory>}}"
            "NotificationConfig": {
                "SuccessTopic": "arn:aws:sns:{{aws-region:account-id:topic-name}}",
                "ErrorTopic": "arn:aws:sns:{{aws-region:account-id:topic-name}}",
            }
        }
    }
)
```

Dopo aver creato l'endpoint e averlo richiamato, riceverai una notifica dal tuo argomento Amazon SNS. Ad esempio, se hai effettuato una sottoscrizione per ricevere notifiche e-mail dal tuo argomento, riceverai una notifica e-mail ogni volta che richiami il tuo endpoint. Il seguente esempio illustra il contenuto JSON di una notifica e-mail per un richiamo riuscito.

```
{
   "awsRegion":"us-east-1",
   "eventTime":"2022-01-25T22:46:00.608Z",
   "receivedTime":"2022-01-25T22:46:00.455Z",
   "invocationStatus":"Completed",
   "requestParameters":{
      "contentType":"text/csv",
      "endpointName":"{{<example-endpoint>}}",
      "inputLocation":"s3://{{<bucket>}}/{{<input-directory>}}/input-data.csv"
   },
   "responseParameters":{
      "contentType":"text/csv; charset=utf-8",
      "outputLocation":"s3://{{<bucket>}}/{{<output_directory>}}/prediction.out"
   },
   "inferenceId":"11111111-2222-3333-4444-555555555555", 
   "eventVersion":"1.0",
   "eventSource":"aws:sagemaker",
   "eventName":"InferenceResult"
}
```

## Controlla il tuo Bucket S3
<a name="async-inference-check-predictions-s3-bucket"></a>

Quando richiami un endpoint con `InvokeEndpointAsync`, questo restituisce un oggetto di risposta. Puoi utilizzare l'oggetto di risposta per ottenere l'URI di Amazon S3 in cui è archiviato l'output. Con la posizione di output, puoi utilizzare una classe di sessione SageMaker Python SDK SageMaker AI per verificare in modo programmatico un output.

Quanto segue memorizza il dizionario di output di `InvokeEndpointAsync` come una variabile denominata risposta. Con la variabile risposta, ottieni quindi l'URI dell’output di Amazon S3 e lo archivi come una variabile stringa chiamata `output_location`. 

```
import uuid
import boto3

sagemaker_runtime = boto3.client("sagemaker-runtime", region_name={{<aws_region>}})

# Specify the S3 URI of the input. Here, a single SVM sample
input_location = "s3://{{bucket-name/test_point_0.libsvm}}" 

response = sagemaker_runtime.invoke_endpoint_async(
    EndpointName={{'<endpoint-name>'}},
    InputLocation=input_location,
    InferenceId=str(uuid.uuid4()), 
    ContentType={{"text/libsvm"}} #Specify the content type of your data
)

output_location = response['OutputLocation']
print(f"OutputLocation: {output_location}")
```

Per ulteriori informazioni sui tipi di contenuti supportati, consulta [Formati di dati comuni per l’inferenza](cdf-inference.md).

Con la posizione di output di Amazon S3, puoi quindi utilizzare una classe [ di sessione SageMaker AI ](https://sagemaker.readthedocs.io/en/stable/api/sagemaker_core.html) SageMaker Python SDK per leggere i file Amazon S3. Il seguente esempio di codice mostra come creare una funzione (`get_ouput`) che tenta ripetutamente di leggere un file dalla posizione di output di Amazon S3:

```
from sagemaker.core.helper.session_helper import Session
import urllib, time
from botocore.exceptions import ClientError

sagemaker_session = Session()

def get_output(output_location):
    output_url = urllib.parse.urlparse(output_location)
    bucket = output_url.netloc
    key = output_url.path[1:]
    while True:
        try:
            return sagemaker_session.read_s3_file(
                                        bucket=output_url.netloc, 
                                        key_prefix=output_url.path[1:])
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchKey':
                print("waiting for output...")
                time.sleep(2)
                continue
            raise
            
output = get_output(output_location)
print(f"Output: {output}")
```