Instructivo de la API de AutoML Translation

En este instructivo, se explica cómo crear un modelo de traducción personalizado con AutoML Translation. La aplicación entrena un modelo personalizado mediante un conjunto de datos de inglés a español de pares de oraciones orientados hacia la tecnología sobre la localización de software.

El instructivo abarca el entrenamiento del modelo personalizado, la evaluación de su rendimiento y la traducción de contenido nuevo.

Requisitos previos

Configura el entorno de tu proyecto

  1. Accede a tu cuenta de Google Cloud. Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  2. En la página del selector de proyectos de la consola de Google Cloud, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  3. Asegúrate de que la facturación esté habilitada para tu proyecto de Google Cloud. Obtén información sobre cómo verificar si la facturación está habilitada en un proyecto.

  4. Habilita las API de AutoML Translation.

    Habilita las API

  5. En la página del selector de proyectos de la consola de Google Cloud, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  6. Asegúrate de que la facturación esté habilitada para tu proyecto de Google Cloud. Obtén información sobre cómo verificar si la facturación está habilitada en un proyecto.

  7. Habilita las API de AutoML Translation.

    Habilita las API

  8. Instala la CLI de Google Cloud.
  9. Sigue las instrucciones para crear una cuenta de servicio y descargar un archivo de claves.
  10. Establece la variable de entorno GOOGLE_APPLICATION_CREDENTIALS en la ruta de acceso al archivo de claves de la cuenta de servicio que descargaste cuando creaste la cuenta de servicio. Por ejemplo:
    export GOOGLE_APPLICATION_CREDENTIALS=key-file
  11. Agrega la cuenta de servicio a la función de IAM del Editor de AutoML con los siguientes comandos. Reemplaza project-id con el nombre de tu proyecto de Google Cloud y reemplaza service-account-name con el nombre de tu nueva cuenta de servicio, por ejemplo, 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. Permite que las cuentas de servicio de AutoML Translation accedan a los recursos del proyecto de 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. Instala la biblioteca cliente.
  14. Configura las variables de entorno PROJECT_ID y REGION_NAME.

    Reemplaza project-id con el ID de tu proyecto de Google Cloud. Actualmente, AutoML Translation requiere la ubicación us-central1.
    export PROJECT_ID="project-id"
    export REGION_NAME="us-central1"
  15. Crea un bucket de Google Cloud Storage para almacenar los documentos que usarás para entrenar tu modelo personalizado.

    El nombre del depósito debe tener el siguiente formato: $PROJECT_ID-vcm. El siguiente comando crea un depósito de almacenamiento llamado $PROJECT_ID-vcm en la región us-central1.
    gsutil mb -p $PROJECT_ID -c regional -l $REGION_NAME gs://$PROJECT_ID-vcm/
  16. Descarga el archivo que contiene los datos de muestra para el entrenamiento del modelo, extrae su contenido y sube los archivos a tu depósito de Google Cloud Storage.

    Consulta Cómo preparar los datos de entrenamiento para obtener detalles sobre los formatos.

    El código de muestra en este instructivo usa el conjunto de datos de inglés a español. También están disponibles los conjuntos de datos con idiomas objetivo: alemán, francés, ruso y chino. Si usas uno de estos conjuntos de datos alternativos, reemplaza el código de idioma es en las muestras con el código de idioma adecuado.

  17. En el archivo en-es.csv del paso anterior, reemplaza {project_id} por el ID de tu proyecto.

Ubicaciones de los archivos de código fuente

Puedes descargar el código fuente desde la ubicación que se indica a continuación. Después de la descarga, lo puedes copiar en la carpeta de tu proyecto de Google Cloud.

Python

El instructivo consta de estos archivos de Python:

  • translate_create_dataset.py: Incluye la funcionalidad para crear conjuntos de datos.
  • import_dataset.py: Incluye la funcionalidad para importar conjuntos de datos.
  • translate_create_model.py: Incluye la funcionalidad para crear modelos.
  • list_model_evaluations.py: Incluye la funcionalidad para ver listas de las evaluaciones de modelos.
  • translate_predict.py: Incluye la funcionalidad relacionada con las predicciones.
  • delete_model.py: Incluye la funcionalidad para borrar modelos.

Java

El instructivo consta de estos archivos de Java:

  • TranslateCreateDataset.java: Incluye la funcionalidad para crear conjuntos de datos.
  • ImportDataset.java: Incluye la funcionalidad para importar conjuntos de datos.
  • TranslateCreateModel.java: Incluye la funcionalidad para crear modelos.
  • ListModelEvaluations.java: Incluye la funcionalidad para ver listas de las evaluaciones de modelos.
  • TranslatePredict.java: Incluye la funcionalidad relacionada con las predicciones.
  • DeleteModel.java: Incluye la funcionalidad para borrar modelos

Node.js

El instructivo consta de estos programas de Node.js:

  • translate_create_dataset.js: Incluye la funcionalidad para crear conjuntos de datos.
  • import_dataset.js: Incluye la funcionalidad para importar conjuntos de datos.
  • translate_create_model.js: Incluye la funcionalidad para crear modelos.
  • list_model_evaluations.js: Incluye la funcionalidad para ver listas de las evaluaciones de modelos.
  • translate_predict.js: Incluye la funcionalidad relacionada con las predicciones.
  • delete_model.js: Incluye la funcionalidad para borrar modelos.

Ejecuta la aplicación

Paso 1: Crear un conjunto de datos

El primer paso cuando se crea un modelo personalizado es crear un conjunto de datos vacío que finalmente tendrá los datos de entrenamiento para el modelo. Cuando creas un conjunto de datos, especificas los idiomas fuente y objetivo para la traducción.

Copia el código

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();

Solicitud

Ejecuta la función create_dataset para crear un conjunto de datos vacío. Debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece el display_name para el conjunto de datos (en_es_dataset).
  • Modifica el campo target_language_code de 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

Respuesta

La respuesta incluye los detalles del conjunto de datos recién creado, incluido el ID del conjunto de datos que utilizarás para hacer referencia al conjunto de datos en solicitudes futuras. Te recomendamos que establezcas una variable de entorno DATASET_ID para el valor del ID del conjunto de datos mostrado.

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

Paso 2: Importar pares de oraciones de entrenamiento al conjunto de datos

El siguiente paso consiste en propagar el conjunto de datos con una lista de pares de oraciones de entrenamiento.

La interfaz de la función import_dataset toma como entrada un archivo .csv que enumera las ubicaciones de todos los documentos de entrenamiento, además de la etiqueta adecuada para cada documento de entrenamiento (consulta Cómo preparar los datos de entrenamiento para obtener detalles sobre el formato requerido). Para este instructivo, usaremos el archivo en-es.csv, que subiste anteriormente a Google Cloud Storage.

Copia el código

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();

Solicitud

Ejecuta la función import_data para importar el contenido de entrenamiento. Debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece el dataset_id para el conjunto de datos (del resultado del paso anterior).
  • Establece la path que corresponde al URI del (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

Respuesta

Processing import...
Dataset imported.

Paso 3: Crear (entrenar) el modelo

Ahora que tienes un conjunto de datos de documentos de entrenamiento etiquetados, puedes entrenar un modelo nuevo.

Copia el código

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();

Solicitud

Para ejecutar create_model, debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece el dataset_id para el conjunto de datos (del resultado del paso anterior).
  • Establece el display_name para el nuevo modelo (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

Respuesta

La función create_model inicia una operación de entrenamiento y, luego, imprime el nombre de la operación. El entrenamiento se realiza de forma asíncrona y puede tardar un poco en completarse, por lo que puedes usar el ID de la operación para verificar el estado del entrenamiento. Cuando finaliza el entrenamiento, create_model muestra el ID del modelo. Al igual que con el ID del conjunto de datos, puedes establecer una variable de entorno MODEL_ID para el valor del ID del modelo que se muestra.

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

Paso 4: Evaluar el modelo

Después del entrenamiento, puedes analizar la puntuación BLEU para saber si tu modelo está listo.

La función list_model_evaluations toma el ID del modelo como parámetro.

Copia el código

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();

Solicitud

Realiza una solicitud para mostrar el rendimiento general de la evaluación del modelo mediante la ejecución de la siguiente solicitud. Debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece model_id para el ID de tu modelo.

Python

python list_model_evaluations.py

Java

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

Node.js

node list_model_evaluations.js

Respuesta

Si la puntuación BLEU es demasiado baja, puedes fortalecer el conjunto de datos de entrenamiento y volver a entrenar a tu modelo. Para obtener más información, consulta Evaluar modelos.

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
}

Paso 5: Usar un modelo para hacer una predicción

Cuando tu modelo personalizado cumple con tus estándares de calidad, puedes usarlo para traducir contenido novedoso.

Copia el código

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();

Solicitud

Para la función predict, debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece model_id para el ID de tu modelo.
  • Establece file_path para el archivo descargado ("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

Respuesta

La función muestra el contenido traducido.

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

Arriba aparece la traducción al español de la oración en inglés: “View and manage your Google Tag Manager accounts”. Compara esta traducción personalizada con la traducción del modelo base de Google:

Ver y administrar sus cuentas de Administrador de etiquetas de Google

Paso 6: Borrar un modelo

Cuando hayas terminado de usar este modelo de muestra, puedes borrarlo permanentemente. Ya no podrás usar el modelo para predicción.

Copia el código

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();

Solicitud

Realiza una solicitud con el tipo de operación delete_model para borrar un modelo que creaste. Debes modificar las siguientes líneas de código:

  • Establece project_id para tu PROJECT_ID.
  • Establece model_id para el ID de tu modelo.

Python

python delete_model.py

Java

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

Node.js

node delete_model.js

Respuesta

Model deleted.