Tutorial sull'API AutoML Translation

Questo tutorial illustra come creare un modello di traduzione personalizzato utilizzando AutoML Translation. L'applicazione addestra un modello personalizzato utilizzando un set di dati dall'inglese allo spagnolo di coppie di frasi orientate alla tecnologia dalla localizzazione del software.

Il tutorial tratta l'addestramento del modello personalizzato, la valutazione delle sue prestazioni e la traduzione di nuovi contenuti.

Prerequisiti

Configura l'ambiente del progetto

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. Nella console di Google Cloud Console, nella pagina del selettore dei progetti, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  3. Verifica che la fatturazione sia attivata per il tuo progetto Google Cloud. Scopri come verificare se la fatturazione è abilitata per un progetto.

  4. Abilita le API AutoML Translation.

    Abilita le API

  5. Nella console di Google Cloud Console, nella pagina del selettore dei progetti, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  6. Verifica che la fatturazione sia attivata per il tuo progetto Google Cloud. Scopri come verificare se la fatturazione è abilitata per un progetto.

  7. Abilita le API AutoML Translation.

    Abilita le API

  8. Installa Google Cloud CLI.
  9. Segui le istruzioni per creare un account di servizio e scaricare un file della chiave.
  10. Imposta la variabile di ambiente GOOGLE_APPLICATION_CREDENTIALS sul percorso del file della chiave dell'account di servizio scaricato al momento della creazione dell'account di servizio. Ad esempio:
    export GOOGLE_APPLICATION_CREDENTIALS=key-file
  11. Aggiungi il nuovo account di servizio al ruolo IAM AutoML Editor con i seguenti comandi. Sostituisci project-id con il nome del tuo progetto Google Cloud e service-account-name con il nome del tuo nuovo account di servizio, ad esempio service-account1@myproject.iam.gserviceaccount.com.
    gcloud auth login
    gcloud config set project project-id
    gcloud projects add-iam-policy-binding project-id \
      --member=serviceAccount:service-account-name \
      --role='roles/automl.editor'
  12. Consenti agli account di servizio AutoML Translation di accedere alle risorse del progetto Google Cloud:
    gcloud projects add-iam-policy-binding project-id \
      --member="serviceAccount:service-project-number@gcp-sa-automl.iam.gserviceaccount.com" \
      --role="roles/automl.serviceAgent"
  13. Installa la libreria client.
  14. Imposta le variabili di ambiente PROJECT_ID e REGION_NAME.

    Sostituisci project-id con l'ID progetto del tuo progetto Google Cloud. Al momento AutoML Translation richiede la località us-central1.
    export PROJECT_ID="project-id"
    export REGION_NAME="us-central1"
  15. Crea un bucket Google Cloud Storage per archiviare i documenti che utilizzerai per addestrare il modello personalizzato.

    Il nome del bucket deve essere nel formato: $PROJECT_ID-vcm. Il comando seguente crea un bucket di archiviazione denominato $PROJECT_ID-vcm nella regione us-central1.
    gsutil mb -p $PROJECT_ID -c regional -l $REGION_NAME gs://$PROJECT_ID-vcm/
  16. Scarica il file di archivio contenente i dati di esempio per addestrare il modello, estrai i suoi contenuti e carica i file nel bucket di Google Cloud Storage.

    Vedi Preparare i dati di addestramento per i dettagli sui formati.

    Il codice campione in questo tutorial utilizza il set di dati dall'inglese allo spagnolo. Sono disponibili anche set di dati con lingue di destinazione tedesco, francese, russo e cinese. Se utilizzi uno di questi set di dati alternativi, sostituisci il codice della lingua es negli esempi con il codice della lingua appropriato.

  17. Nel file en-es.csv del passaggio precedente, sostituisci {project_id} con l'ID progetto del tuo progetto.

Località dei file di codice sorgente

Puoi scaricare il codice sorgente dalla posizione fornita di seguito. Dopo il download, puoi copiare il codice sorgente nella cartella del tuo progetto Google Cloud.

Python

Il tutorial è composto da questi file Python:

  • translate_create_dataset.py: include la funzionalità per creare un set di dati
  • import_dataset.py - Include la funzionalità per importare un set di dati
  • translate_create_model.py - Include la funzionalità per creare un modello
  • list_model_evaluations.py: funzionalità inclusa per elencare le valutazioni dei modelli
  • translate_predict.py: include funzionalità relative alla previsione
  • delete_model.py - Includi la funzionalità per eliminare un modello

Java

Il tutorial consiste in questi file Java:

  • TranslateCreateDataset.java: include la funzionalità per creare un set di dati
  • ImportDataset.java - Include la funzionalità per importare un set di dati
  • TranslateCreateModel.java - Include la funzionalità per creare un modello
  • ListModelEvaluations.java: funzionalità inclusa per elencare le valutazioni dei modelli
  • TranslatePredict.java: include funzionalità relative alla previsione
  • DeleteModel.java: include la funzionalità per eliminare un modello

Node.js

Il tutorial consiste in questi programmi Node.js:

  • translate_create_dataset.js: include la funzionalità per creare un set di dati
  • import_dataset.js - Include la funzionalità per importare un set di dati
  • translate_create_model.js - Include la funzionalità per creare un modello
  • list_model_evaluations.js: funzionalità inclusa per elencare le valutazioni dei modelli
  • translate_predict.js: include funzionalità relative alla previsione
  • delete_model.js - Includi la funzionalità per eliminare un modello

Esecuzione dell'applicazione

Passaggio 1: crea un set di dati

Il primo passaggio nella creazione di un modello personalizzato è creare un set di dati vuoto che contenga i dati di addestramento del modello. Quando crei un set di dati, devi specificare le lingue di origine e di destinazione per la traduzione.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "YOUR_DATASET_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# For a list of supported languages, see:
# https://cloud.google.com/translate/automl/docs/languages
dataset_metadata = automl.TranslationDatasetMetadata(
    source_language_code="en", target_language_code="ja"
)
dataset = automl.Dataset(
    display_name=display_name,
    translation_dataset_metadata=dataset_metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print("Dataset name: {}".format(created_dataset.name))
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TranslationDatasetMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class TranslateCreateDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String displayName = "YOUR_DATASET_NAME";
    createDataset(projectId, displayName);
  }

  // Create a dataset
  static void createDataset(String projectId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Specify the source and target language.
      TranslationDatasetMetadata translationDatasetMetadata =
          TranslationDatasetMetadata.newBuilder()
              .setSourceLanguageCode("en")
              .setTargetLanguageCode("ja")
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTranslationDatasetMetadata(translationDatasetMetadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

      // Display the dataset information.
      System.out.format("Dataset name: %s\n", createdDataset.getName());
      // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
      // required for other methods.
      // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
      String[] names = createdDataset.getName().split("/");
      String datasetId = names[names.length - 1];
      System.out.format("Dataset id: %s\n", datasetId);
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const displayName = 'YOUR_DISPLAY_NAME';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function createDataset() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      translationDatasetMetadata: {
        sourceLanguageCode: 'en',
        targetLanguageCode: 'ja',
      },
    },
  };

  // Create dataset
  const [operation] = await client.createDataset(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Dataset name: ${response.name}`);
  console.log(`
    Dataset id: ${
      response.name
        .split('/')
        [response.name.split('/').length - 1].split('\n')[0]
    }`);
}

createDataset();

Risorse richieste:

Esegui la funzione create_dataset per creare un set di dati vuoto. Devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta il display_name per il set di dati (en_es_dataset)
  • Modifica il campo target_language_code da ja a es

Python

python translate_create_dataset.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.TranslateCreateDataset"

Node.js

node translate_create_dataset.js

Risposta

La risposta include i dettagli del set di dati appena creato, incluso l'ID del set di dati che utilizzerai per fare riferimento al set di dati nelle richieste future. Ti consigliamo di impostare una variabile di ambiente DATASET_ID sul valore restituito del set di dati.

Dataset name: projects/216065747626/locations/us-central1/datasets/TRL7372141011130533778
Dataset id: TRL7372141011130533778
Dataset display name: en_es_dataset
Translation dataset Metadata:
        source_language_code: en
        target_language_code: es
Dataset example count: 0
Dataset create time:
       seconds: 1530251987
       nanos: 216586000

Passaggio 2: importa le coppie di frasi di addestramento nel set di dati

Il passaggio successivo consiste nel completare il set di dati con un elenco di coppie di frasi di addestramento.

L'interfaccia delle funzioni import_dataset utilizza un file .csv in cui sono elencate le posizioni di tutti i documenti di addestramento e l'etichetta corretta per ciascun documento di addestramento. Per ulteriori dettagli sul formato richiesto, consulta l'articolo Preparare i dati. Per questo tutorial, utilizzeremo en-es.csv, che hai caricato in Google Cloud Storage qui sopra.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print("Data imported. {}".format(response.result()))

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Risorse richieste:

Esegui la funzione import_data per importare i contenuti di addestramento. Devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta il dataset_id per il set di dati (dall'output del passaggio precedente)
  • Imposta il path che corrisponde all'URI di (gs://YOUR_PROJECT_ID-vcm/en-es.csv)

Python

python import_dataset.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.ImportDataset"

Node.js

node import_dataset.js

Risposta

Processing import...
Dataset imported.

Passaggio 3: crea (addestra) il modello

Ora che hai un set di dati di documenti di addestramento etichettati, puoi addestrare un nuovo modello.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# display_name = "YOUR_MODEL_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
translation_model_metadata = automl.TranslationModelMetadata()
model = automl.Model(
    display_name=display_name,
    dataset_id=dataset_id,
    translation_model_metadata=translation_model_metadata,
)

# Create a model with the model metadata in the region.
response = client.create_model(parent=project_location, model=model)

print("Training operation name: {}".format(response.operation.name))
print("Training started...")

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.Model;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TranslationModelMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class TranslateCreateModel {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String displayName = "YOUR_DATASET_NAME";
    createModel(projectId, datasetId, displayName);
  }

  // Create a model
  static void createModel(String projectId, String datasetId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");
      TranslationModelMetadata translationModelMetadata =
          TranslationModelMetadata.newBuilder().build();
      Model model =
          Model.newBuilder()
              .setDisplayName(displayName)
              .setDatasetId(datasetId)
              .setTranslationModelMetadata(translationModelMetadata)
              .build();

      // Create a model with the model metadata in the region.
      OperationFuture<Model, OperationMetadata> future =
          client.createModelAsync(projectLocation, model);
      // OperationFuture.get() will block until the model is created, which may take several hours.
      // You can use OperationFuture.getInitialFuture to get a future representing the initial
      // response to the request, which contains information while the operation is in progress.
      System.out.format("Training operation name: %s\n", future.getInitialFuture().get().getName());
      System.out.println("Training started...");
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const dataset_id = 'YOUR_DATASET_ID';
// const displayName = 'YOUR_DISPLAY_NAME';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function createModel() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    model: {
      displayName: displayName,
      datasetId: datasetId,
      translationModelMetadata: {},
    },
  };

  // Don't wait for the LRO
  const [operation] = await client.createModel(request);
  console.log('Training started...');
  console.log(`Training operation name: ${operation.name}`);
}

createModel();

Risorse richieste:

Per eseguire create_model, devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta il dataset_id per il set di dati (dall'output del passaggio precedente)
  • Imposta il display_name per il nuovo modello (en_es_test_model)

Python

python translate_create_model.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.TranlateCreateModel"

Node.js

node translate_create_model.js

Risposta

La funzione create_model avvia un'operazione di addestramento e stampa il nome dell'operazione. L'addestramento avviene in modo asincrono e il completamento può richiedere un po' di tempo, quindi puoi utilizzare l'ID operazione per controllare lo stato dell'addestramento. Una volta completato l'addestramento, create_model restituisce l'ID modello. Come per l'ID del set di dati, ti consigliamo di impostare una variabile di ambiente MODEL_ID sul valore dell'ID modello restituito.

Training operation name: projects/216065747626/locations/us-central1/operations/TRL3007727620979824033
Training started...
Model name: projects/216065747626/locations/us-central1/models/TRL3007727620979824033
Model id: TRL3007727620979824033
Model display name: en_es_test_model
Model create time:
        seconds: 1529649600
        nanos: 966000000
Model deployment state: deployed

Passaggio 4: valuta il modello

Dopo l'addestramento, puoi valutare l'idoneità del tuo modello esaminando il relativo punteggio BLEU.

La funzione list_model_evaluations accetta l'ID modello come parametro.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)

print("List of model evaluations:")
for evaluation in client.list_model_evaluations(parent=model_full_id, filter=""):
    print("Model evaluation name: {}".format(evaluation.name))
    print("Model annotation spec id: {}".format(evaluation.annotation_spec_id))
    print("Create Time: {}".format(evaluation.create_time))
    print("Evaluation example count: {}".format(evaluation.evaluated_example_count))
    print(
        "Translation model evaluation metrics: {}".format(
            evaluation.translation_evaluation_metrics
        )
    )

Java


import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ListModelEvaluationsRequest;
import com.google.cloud.automl.v1.ModelEvaluation;
import com.google.cloud.automl.v1.ModelName;
import java.io.IOException;

class ListModelEvaluations {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    listModelEvaluations(projectId, modelId);
  }

  // List model evaluations
  static void listModelEvaluations(String projectId, String modelId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
      ListModelEvaluationsRequest modelEvaluationsrequest =
          ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();

      // List all the model evaluations in the model by applying filter.
      System.out.println("List of model evaluations:");
      for (ModelEvaluation modelEvaluation :
          client.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {

        System.out.format("Model Evaluation Name: %s\n", modelEvaluation.getName());
        System.out.format("Model Annotation Spec Id: %s", modelEvaluation.getAnnotationSpecId());
        System.out.println("Create Time:");
        System.out.format("\tseconds: %s\n", modelEvaluation.getCreateTime().getSeconds());
        System.out.format("\tnanos: %s", modelEvaluation.getCreateTime().getNanos() / 1e9);
        System.out.format(
            "Evalution Example Count: %d\n", modelEvaluation.getEvaluatedExampleCount());
        System.out.format(
            "Translate Model Evaluation Metrics: %s\n",
            modelEvaluation.getTranslationEvaluationMetrics());
      }
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function listModelEvaluations() {
  // Construct request
  const request = {
    parent: client.modelPath(projectId, location, modelId),
    filter: '',
  };

  const [response] = await client.listModelEvaluations(request);

  console.log('List of model evaluations:');
  for (const evaluation of response) {
    console.log(`Model evaluation name: ${evaluation.name}`);
    console.log(`Model annotation spec id: ${evaluation.annotationSpecId}`);
    console.log(`Model display name: ${evaluation.displayName}`);
    console.log('Model create time');
    console.log(`\tseconds ${evaluation.createTime.seconds}`);
    console.log(`\tnanos ${evaluation.createTime.nanos / 1e9}`);
    console.log(
      `Evaluation example count: ${evaluation.evaluatedExampleCount}`
    );
    console.log(
      `Translation model evaluation metrics: ${evaluation.translationEvaluationMetrics}`
    );
  }
}

listModelEvaluations();

Risorse richieste:

Esegui una richiesta per visualizzare le prestazioni complessive della valutazione del modello eseguendo la richiesta seguente. Devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta model_id sull'ID del modello

Python

python list_model_evaluations.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.ListModelEvaluations"

Node.js

node list_model_evaluations.js

Risposta

Se il punteggio BLEU è troppo basso, puoi rafforzare il set di dati di addestramento e reimpostare il modello. Per ulteriori informazioni, consulta la sezione Valutare i modelli.

List of model evaluations:
name: "projects/216065747626/locations/us-central1/models/5419131644870929143/modelEvaluations/TRL7683346839371803263"
create_time {
  seconds: 1530196488
  nanos: 509247000
}
evaluated_example_count: 3
translation_evaluation_metrics {
  bleu_score: 19.23076957464218
  base_bleu_score: 11.428571492433548
}

Passaggio 5: utilizza un modello per eseguire una previsione

Se il tuo modello personalizzato soddisfa i tuoi standard qualitativi, puoi utilizzarlo per tradurre contenuti nuovi.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# file_path = "path_to_local_file.txt"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Read the file content for translation.
with open(file_path, "rb") as content_file:
    content = content_file.read()
content.decode("utf-8")

text_snippet = automl.TextSnippet(content=content)
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)
translated_content = response.payload[0].translation.translated_content

print(u"Translated content: {}".format(translated_content.content))

Java

import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class TranslatePredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String filePath = "path_to_local_file.txt";
    predict(projectId, modelId, filePath);
  }

  static void predict(String projectId, String modelId, String filePath) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      String content = new String(Files.readAllBytes(Paths.get(filePath)));

      TextSnippet textSnippet = TextSnippet.newBuilder().setContent(content).build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);
      TextSnippet translatedContent =
          response.getPayload(0).getTranslation().getTranslatedContent();
      System.out.format("Translated Content: %s\n", translatedContent.getContent());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const filePath = 'path_to_local_file.txt';

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;
const fs = require('fs');

// Instantiates a client
const client = new PredictionServiceClient();

// Read the file content for translation.
const content = fs.readFileSync(filePath, 'utf8');

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
      },
    },
  };

  const [response] = await client.predict(request);

  console.log(
    'Translated content: ',
    response.payload[0].translation.translatedContent.content
  );
}

predict();

Risorse richieste:

Per la funzione predict devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta model_id sull'ID del modello
  • Imposta il file file_path sul file scaricato ("resources/input.txt")

Python

python tranlsate_predict.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.TranslatePredict"

Node.js

node translate_predict.js predict

Risposta

La funzione restituisce il contenuto tradotto.

Translated content: Ver y administrar tus cuentas de Google Tag Manager.

Sopra è presente la traduzione spagnola per la frase inglese: "View and management your Google Tag Manager accounts". Confronta questa traduzione personalizzata con la traduzione del modello Google di base:

Ver y administrar sus cuentas de Administrador de etiquetas de Google

Passaggio 6: elimina un modello

Quando hai finito di utilizzare questo modello di esempio, puoi eliminarlo definitivamente. Non potrai più utilizzare il modello per la previsione.

Copia il codice

Python

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)
response = client.delete_model(name=model_full_id)

print("Model deleted. {}".format(response.result()))

Java

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ModelName;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeleteModel {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    deleteModel(projectId, modelId);
  }

  // Delete a model
  static void deleteModel(String projectId, String modelId)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);

      // Delete a model.
      Empty response = client.deleteModelAsync(modelFullId).get();

      System.out.println("Model deletion started...");
      System.out.println(String.format("Model deleted. %s", response));
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function deleteModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [response] = await client.deleteModel(request);
  console.log(`Model deleted: ${response}`);
}

deleteModel();

Risorse richieste:

Effettua una richiesta con il tipo di operazione delete_model per eliminare un modello che hai creato. Devi modificare le seguenti righe di codice:

  • Imposta il project_id su PROJECT_ID
  • Imposta model_id sull'ID del modello

Python

python delete_model.py

Java

mvn compile exec:java -Dexec.mainClass="com.example.automl.DeleteModel"

Node.js

node delete_model.js

Risposta

Model deleted.