AutoML Translation API チュートリアル

このチュートリアルでは、AutoML Translation を使用してカスタム翻訳モデルを作成する方法を説明します。このアプリケーションでは、ソフトウェアのローカライゼーションから取得した、技術に関する英語からスペイン語への文のペアのデータセットを使用して、カスタムモデルをトレーニングします。

このチュートリアルでは、カスタムモデルのトレーニング、パフォーマンスの評価、新しいコンテンツの翻訳について説明します。

要件

プロジェクトの環境を構成する

  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトの課金が有効になっていることを確認します。詳しくは、プロジェクトで課金が有効になっているかどうかを確認する方法をご覧ください。

  4. AutoML Translation API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトの課金が有効になっていることを確認します。詳しくは、プロジェクトで課金が有効になっているかどうかを確認する方法をご覧ください。

  7. AutoML Translation API を有効にします。

    API を有効にする

  8. Google Cloud CLI をインストールします
  9. 手順に沿ってサービス アカウントを作成し、鍵ファイルをダウンロードします
  10. GOOGLE_APPLICATION_CREDENTIALS 環境変数を、サービス アカウントの作成時にダウンロードしたサービス アカウントの鍵ファイルのパスに設定します。次に例を示します。
    export GOOGLE_APPLICATION_CREDENTIALS=key-file
  11. 次のコマンドを使用して、新しいサービス アカウントを AutoML 編集者の IAM 役割に追加します。project-id を実際の Google Cloud プロジェクトの名前に置き換え、service-account-name を新しいサービス アカウントの名前に置き換えます。たとえば、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. AutoML Translation サービス アカウントが使用する 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. クライアント ライブラリをインストールします
  14. PROJECT_ID および REGION_NAME 環境変数を設定します。

    project-id は、Google Cloud プロジェクトの プロジェクト ID に置き換えます。現在、AutoML Translation にはロケーションとして us-central1 を指定する必要があります。
    export PROJECT_ID="project-id"
    export REGION_NAME="us-central1"
  15. カスタムモデルのトレーニングに使用するドキュメントを保存する Google Cloud Storage バケットを作成します。

    バケット名の形式は、$PROJECT_ID-vcm にする必要があります。次のコマンドによって、$PROJECT_ID-vcm という名前の us-central1 リージョンにストレージ バケットが作成されます。
    gsutil mb -p $PROJECT_ID -c regional -l $REGION_NAME gs://$PROJECT_ID-vcm/
  16. モデルのトレーニングに使用するサンプルデータを含むアーカイブ ファイルをダウンロードし、そのコンテンツを抽出してファイルを Google Cloud Storage バケットにアップロードします。

    形式の詳細については、トレーニング データの準備をご覧ください。

    このチュートリアルのサンプルコードでは、英語からスペイン語へのデータセットを使用しています。ターゲット言語がドイツ語、フランス語、ロシア語、中国語のデータセットも用意されています。これらの代替データセットのいずれかを使用する場合は、サンプルの言語コード es を適切な言語コードに置き換えます。

  17. 前のステップの en-es.csv ファイルで、{project_id} をプロジェクトのプロジェクト ID に置き換えます。

ソースコード ファイルの場所

ソースコードは以下の場所からダウンロードできます。ダウンロードした後、ソースコードを Google Cloud プロジェクト フォルダにコピーできます。

Python

このチュートリアルは、次の Python ファイルで構成されています。

  • translate_create_dataset.py – データセットを作成するための関数が含まれています
  • import_dataset.py – データセットをインポートするための関数が含まれています
  • translate_create_model.py - モデルを作成するための関数が含まれています
  • list_model_evaluations.py - モデル評価を一覧表示するための関数が含まれています
  • translate_predict.py - 予測に関連する関数が含まれています
  • delete_model.py - モデルを削除するための関数が含まれています

Java

このチュートリアルは、次の Java ファイルで構成されています。

  • TranslateCreateDataset.java – データセットを作成するための関数が含まれています
  • ImportDataset.java – データセットをインポートするための関数が含まれています
  • TranslateCreateModel.java - モデルを作成するための関数が含まれています
  • ListModelEvaluations.java - モデル評価を一覧表示するための関数が含まれています
  • TranslatePredict.java - 予測に関連する関数が含まれています
  • DeleteModel.java - モデルを削除するための関数が含まれています

Node.js

このチュートリアルは、次の Node.js プログラムで構成されています。

  • translate_create_dataset.js – データセットを作成するための関数が含まれています
  • import_dataset.js – データセットをインポートするための関数が含まれています
  • translate_create_model.js - モデルを作成するための関数が含まれています
  • list_model_evaluations.js - モデル評価を一覧表示するための関数が含まれています
  • translate_predict.js - 予測に関連する関数が含まれています
  • delete_model.js - モデルを削除するための関数が含まれています

アプリケーションの実行

ステップ 1: データセットを作成する

カスタムモデルを作成するには、まず空のデータセットを作成します。作成したデータセットには、最終的にそのモデルのトレーニング データが格納されます。データセットの作成時には、翻訳のソース言語とターゲット言語を指定します。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

create_dataset 関数を実行して、空のデータセットを作成します。次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • データセット(en_es_dataset)の display_name を設定します
  • target_language_code フィールドを ja から 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

レスポンス

レスポンスには、新しく作成されたデータセットの詳細が格納されます。その詳細に、今後のリクエストでデータセットを参照するために使用するデータセット ID が含まれています。環境変数 DATASET_ID を、レスポンスで返されたデータセット ID の値に設定することをおすすめします。

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

ステップ 2: データセットにトレーニング用のセンテンスペアをインポートする

次のステップとして、トレーニング用の文のペアのリストをデータセットに入力します。

import_dataset 関数インターフェースは、すべてのトレーニング用ドキュメントの場所と各トレーニング用ドキュメントの適切なラベルをリストした .csv ファイルを入力として受け取ります(必要な形式について詳しくは、データの準備をご覧ください)。このチュートリアルでは、上記で Google Cloud Storage にアップロードした en-es.csv を使用します。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Data imported. {response.result()}")

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

import_data 関数を実行してトレーニング コンテンツをインポートします。次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • データセットの dataset_id を設定します(前のステップの出力から取得)
  • gs://YOUR_PROJECT_ID-vcm/en-es.csv)の URI である path を設定します

Python

python import_dataset.py

Java

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

Node.js

node import_dataset.js

レスポンス

Processing import...
Dataset imported.

ステップ 3: モデルを作成(トレーニング)する

ラベル付きトレーニング用ドキュメントのデータセットが作成されたので、新しいモデルをトレーニングできます。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Training operation name: {response.operation.name}")
print("Training started...")

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

create_model を実行するには、次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • データセットの dataset_id を設定します(前のステップの出力から取得)
  • 新しいモデル(en_es_test_model)の display_name を設定します

Python

python translate_create_model.py

Java

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

Node.js

node translate_create_model.js

レスポンス

create_model 関数はトレーニング オペレーションを開始し、オペレーション名を出力します。トレーニングは非同期で行われ、完了するまでに時間がかかることがあります。オペレーション ID を使用すると、トレーニング ステータスを確認できます。トレーニングが完了したら、create_model によってモデル ID が返されます。データセット ID の場合と同様に、返されたモデル ID に環境変数 MODEL_ID を設定することもできます。

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

ステップ 4: モデルを評価する

トレーニングが終了したら、モデルの BLEU スコアを確認することでモデルの準備状況を評価できます。

list_model_evaluations 関数はモデル ID をパラメータとして取得します。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Model evaluation name: {evaluation.name}")
    print(f"Model annotation spec id: {evaluation.annotation_spec_id}")
    print(f"Create Time: {evaluation.create_time}")
    print(f"Evaluation example count: {evaluation.evaluated_example_count}")
    print(
        "Translation model evaluation metrics: {}".format(
            evaluation.translation_evaluation_metrics
        )
    )

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

次のリクエストを実行して、モデルの全体的な評価パフォーマンスを表示するリクエストを行います。次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • model_id をモデル ID に設定します

Python

python list_model_evaluations.py

Java

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

Node.js

node list_model_evaluations.js

レスポンス

BLEU スコアが低すぎる場合は、トレーニング データセットを強化してモデルを再トレーニングできます。詳細については、モデルの評価をご覧ください。

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
}

ステップ 5: モデルを使用して予測する

カスタムモデルが品質基準を満たしている場合は、このモデルを新しいコンテンツの翻訳に使用できます。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Translated content: {translated_content.content}")

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

predict 関数では、次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • model_id をモデル ID に設定します
  • ダウンロードしたファイル(resources/input.txt)に file_path を設定します

Python

python tranlsate_predict.py

Java

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

Node.js

node translate_predict.js predict

レスポンス

この関数は、翻訳後のコンテンツを返します。

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

上記は、「View and manage your Google Tag Manager accounts.」という英文のスペイン語訳です。このカスタム翻訳と、基本的な Google モデルの翻訳を比較します。

Ver y administrar sus cuentas de Administrador de etiquetas de Google

ステップ 6: モデルを削除する

サンプルモデルの使用が終わったら、モデルを完全に削除できます。削除したモデルは、予測に使用できなくなります。

コードをコピーする

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Model deleted. {response.result()}")

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

リクエスト

オペレーション タイプ delete_model でリクエストを作成し、作成したモデルを削除します。次のコード行を変更する必要があります。

  • project_id を実際の PROJECT_ID に設定します
  • model_id をモデル ID に設定します

Python

python delete_model.py

Java

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

Node.js

node delete_model.js

レスポンス

Model deleted.