Edge のエクスポート可能モデルのトレーニング

準備したデータセットを使用してモデルをトレーニングし、カスタムモデルを作成します。AutoML API では、データセットの項目を使用してモデルをトレーニングしてテストし、パフォーマンスを評価します。その結果を確認し、必要に応じてトレーニング データセットを調整して、改善されたデータセットで新しいモデルをトレーニングします。

モデルのトレーニングが完了するまで数時間かかることがあります。AutoML API を使用すると、トレーニングのステータスを確認できます。

AutoML Vision ではトレーニングを開始するたびに新しいモデルが作成されるため、プロジェクトに多数のモデルが含まれる場合があります。プロジェクト内のモデルの一覧表示や、不要になったモデルの削除が可能です。また、Cloud AutoML Vision UI を使用して、AutoML API で作成したモデルを一覧表示し、不要なモデルを削除することもできます。

これらのモデルには Google の最新の研究成果が反映されています。モデルを TF Lite パッケージとして利用できます。TensorFlow Lite SDK を使用して TensorFlow Lite モデルを統合する方法については、iOSAndroid のリンクをご覧ください。

Edge モデルのトレーニング

ラベル付きトレーニング アイテムを含むデータセットがある場合は、カスタム Edge モデルを作成してトレーニングできます。

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Vision リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Vision リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Vision リファレンス ドキュメントをご覧ください。

TensorFlow サービングと TF Lite モデル

トレーニング時に、特定のユースケースで必要な Edge モデルのタイプを選択できます。

  • 低レイテンシ(mobile-low-latency-1
  • 一般的な用途(mobile-versatile-1
  • 予測品質の向上(mobile-high-accuracy-1

ウェブ UI

  1. Vision Dashboard を開きます。

    [データセット] に、現在のプロジェクトの使用可能データセットが表示されます。

    データセットの一覧ページ
  2. カスタムモデルのトレーニングに使用するデータセットを選択します。
  3. データセットの準備ができたら、[トレーニング] タブと [新しいモデルをトレーニング] ボタンを選択します。

    [新しいモデルのトレーニング] サイド ウィンドウが開き、トレーニング オプションが表示されます。

  4. トレーニングの [モデルの定義] セクションで、モデル名を変更するかデフォルト値を使用して、モデルタイプとして Edge を指定します。Edge モデルのトレーニングを選択したら、[続行] を選択します。Edge モデルのトレーニングのラジオボタン画像
  5. 次の [モデル最適化のオプション] セクションで、必要な最適化基準( 高精度最適なトレードオフまたは 予測の高速化)を選択します。最適化仕様を選択したら、[続行] を選択します。

    最良のトレードオフのラジオボタン画像
  6. 次の [ノード時間予算の設定] セクションで、ノード時間の推奨予算を使用するか、別の値を指定します。

    ほとんどのデータセットでは、モデルをトレーニングするのに 24 ノード時間で十分です。この推奨値は、モデルを完全に統合するための推定値です。ただし、別の値を選択することもできます。画像分類の最小ノード時間は 8 です。オブジェクト検出の場合、この最小値は 20 です。

    ノード予算設定セクション
  7. [トレーニングを開始] を選択して、モデルのトレーニングを開始します。

モデルのトレーニングが完了するまで数時間かかることがあります。モデルのトレーニングが正常に終了したら、Google Cloud Platform プロジェクトに使用したメールアドレスにメッセージが届きます。

REST

Edge モデルをトレーニングする場合は、モデルの要件に合わせて modelType フィールドに次の 3 つ値を指定できます。

  • mobile-low-latency-1: 低レイテンシ
  • mobile-versatile-1: 汎用的な用途
  • mobile-high-accuracy-1: 予測品質の向上

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • display-name: 選択した文字列の表示名。
  • dataset-id: データセットの IDこの ID は、データセットの名前の最後の要素です。例:
    • データセット名: projects/project-id/locations/location-id/datasets/3104518874390609379
    • データセット ID: 3104518874390609379

HTTP メソッドと URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models

リクエストの本文(JSON):

{
  "displayName": "DISPLAY_NAME",
  "datasetId": "DATASET_ID",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1"
  }
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models" | Select-Object -Expand Content

出力は次のようになります。タスクのステータスは、オペレーション ID(この場合は ICN2106290444865378475)を使用して取得できます。例については、長時間実行オペレーションによる作業をご覧ください。

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN2106290444865378475",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-30T20:06:08.253243Z",
    "updateTime": "2019-10-30T20:06:08.253243Z",
    "createModelDetails": {}
  }
}

Go

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// visionClassificationCreateModel creates a model for image classification.
func visionClassificationCreateModel(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateModel: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())
	fmt.Fprintf(w, "Training started...\n")

	return nil
}

Java

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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

class VisionClassificationCreateModel {

  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");
      // Set model metadata.
      ImageClassificationModelMetadata metadata =
          ImageClassificationModelMetadata.newBuilder().setTrainBudgetMilliNodeHours(24000).build();
      Model model =
          Model.newBuilder()
              .setDisplayName(displayName)
              .setDatasetId(datasetId)
              .setImageClassificationModelMetadata(metadata)
              .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,
      imageClassificationModelMetadata: {
        trainBudgetMilliNodeHours: 24000,
      },
    },
  };

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

createModel();

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_models_display_name"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Leave model unset to use the default base model provided by Google
# train_budget_milli_node_hours: The actual train_cost will be equal or
# less than this value.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#imageclassificationmodelmetadata
metadata = automl.ImageClassificationModelMetadata(
    train_budget_milli_node_hours=24000
)
model = automl.Model(
    display_name=display_name,
    dataset_id=dataset_id,
    image_classification_model_metadata=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...")

list オペレーションのステータス

次のコードサンプルでは、プロジェクトのオペレーションを一覧表示して、結果をフィルタリングします。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations" | Select-Object -Expand Content

表示される出力は、リクエストしたオペレーションによって異なります。

select クエリ パラメータ(operationIddoneworksOn)を使用して返されるオペレーションをフィルタすることもできます。たとえば、実行を終了したオペレーションのリストを返すには、URL を次のように変更します。

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations?filter="done=true"

Go

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	longrunning "cloud.google.com/go/longrunning/autogen/longrunningpb"
	"google.golang.org/api/iterator"
)

// listOperationStatus lists existing operations' status.
func listOperationStatus(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &longrunning.ListOperationsRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.LROClient.ListOperations(ctx, req)

	// Iterate over all results
	for {
		op, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListOperations.Next: %w", err)
		}

		fmt.Fprintf(w, "Name: %v\n", op.GetName())
		fmt.Fprintf(w, "Operation details:\n")
		fmt.Fprintf(w, "%v", op)
	}

	return nil
}

Java

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.LocationName;
import com.google.longrunning.ListOperationsRequest;
import com.google.longrunning.Operation;
import java.io.IOException;

class ListOperationStatus {

  static void listOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    listOperationStatus(projectId);
  }

  // Get the status of an operation
  static void listOperationStatus(String projectId) 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()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Create list operations request.
      ListOperationsRequest listrequest =
          ListOperationsRequest.newBuilder().setName(projectLocation.toString()).build();

      // List all the operations names available in the region by applying filter.
      for (Operation operation :
          client.getOperationsClient().listOperations(listrequest).iterateAll()) {
        System.out.println("Operation details:");
        System.out.format("\tName: %s\n", operation.getName());
        System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
        System.out.format("\tDone: %s\n", operation.getDone());
        if (operation.hasResponse()) {
          System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
        }
        if (operation.hasError()) {
          System.out.println("\tResponse:");
          System.out.format("\t\tError code: %s\n", operation.getError().getCode());
          System.out.format("\t\tError message: %s\n\n", operation.getError().getMessage());
        }
      }
    }
  }
}

Node.js

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

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

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

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

async function listOperationStatus() {
  // Construct request
  const request = {
    name: client.locationPath(projectId, location),
    filter: `worksOn=projects/${projectId}/locations/${location}/models/*`,
  };

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

  console.log('List of operation status:');
  for (const operation of response) {
    console.log(`Name: ${operation.name}`);
    console.log('Operation details:');
    console.log(`${operation}`);
  }
}

listOperationStatus();

Python

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

from google.cloud import automl

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

client = automl.AutoMlClient()
# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# List all the operations names available in the region.
response = client._transport.operations_client.list_operations(
    name=project_location, filter_="", timeout=5
)

print("List of operations:")
for operation in response:
    print(f"Name: {operation.name}")
    print("Operation details:")
    print(operation)

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

長時間実行オペレーションによる作業

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • operation-id: オペレーションの IDこの ID は、オペレーションの名前の最後の要素です。例:
    • オペレーション名: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • オペレーション ID: IOD5281059901324392598

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID" | Select-Object -Expand Content
完了したインポート オペレーションの場合、出力は次のようになります。
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

完了したモデル作成オペレーションの場合、出力は次のようになります。

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-07-22T18:35:06.881193Z",
    "updateTime": "2019-07-22T19:58:44.972235Z",
    "createModelDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
    "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID"
  }
}

Go

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getOperationStatus gets an operation's status.
func getOperationStatus(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Name: %v\n", op.Name())

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
		return err
	}
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
		return err
	}
	fmt.Fprintf(w, "Response: %v\n", resp)

	return nil
}

Java

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  static void getOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
    getOperationStatus(operationFullId);
  }

  // Get the status of an operation
  static void getOperationStatus(String operationFullId) 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 latest state of a long-running operation.
      Operation operation = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println("Operation details:");
      System.out.format("\tName: %s\n", operation.getName());
      System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
      System.out.format("\tDone: %s\n", operation.getDone());
      if (operation.hasResponse()) {
        System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
      }
      if (operation.hasError()) {
        System.out.println("\tResponse:");
        System.out.format("\t\tError code: %s\n", operation.getError().getCode());
        System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
      }
    }
  }
}

Node.js

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

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

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

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

async function getOperationStatus() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
  };

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

  console.log(`Name: ${response.name}`);
  console.log('Operation details:');
  console.log(`${response}`);
}

getOperationStatus();

Python

このサンプルを試す前に、[API とリファレンス] > [クライアント ライブラリ] ページを参照して、この言語の設定手順を完了してください。

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# operation_full_id = \
#     "projects/[projectId]/locations/us-central1/operations/[operationId]"

client = automl.AutoMlClient()
# Get the latest state of a long-running operation.
response = client._transport.operations_client.get_operation(operation_full_id)

print(f"Name: {response.name}")
print("Operation details:")
print(response)

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Vision リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Vision リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Vision リファレンス ドキュメントをご覧ください。

オペレーションのキャンセル

オペレーション ID を使用して、インポート タスクやトレーニング タスクをキャンセルできます。

REST

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • operation-id: オペレーションの IDこの ID は、オペレーションの名前の最後の要素です。例:
    • オペレーション名: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • オペレーション ID: IOD5281059901324392598

HTTP メソッドと URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel" | Select-Object -Expand Content
リクエストが正常に処理されると、空の JSON オブジェクトが返されます。
{}

モデルに関する情報の取得

次のコードサンプルを使用して、特定のトレーニング済みモデルに関する情報を取得します。このリクエストから返された情報を使用して、モードの変更や予測リクエストの送信を行うことができます。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • model-id: モデルを作成したときにレスポンスで返されたモデルの ID。この ID は、モデルの名前の最後の要素です。例:
    • モデル名: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • モデル ID: IOD4412217016962778756

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。



    {
  "name": "projects/project-id/locations/us-central1/models/model-id",
  "displayName": "display-name",
  "datasetId": "dataset-id",
  "createTime": "2019-10-30T20:06:08.253243Z",
  "deploymentState": "UNDEPLOYED",
  "updateTime": "2019-10-30T20:54:50.472328Z",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1",
    "nodeQps": 3.2
  }
}

Go

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getModel gets a model.
func getModel(w io.Writer, projectID string, location string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TRL123456789..."

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.GetModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	model, err := client.GetModel(ctx, req)
	if err != nil {
		return fmt.Errorf("GetModel: %w", err)
	}

	// Retrieve deployment state.
	deploymentState := "undeployed"
	if model.GetDeploymentState() == automlpb.Model_DEPLOYED {
		deploymentState = "deployed"
	}

	// Display the model information.
	fmt.Fprintf(w, "Model name: %v\n", model.GetName())
	fmt.Fprintf(w, "Model display name: %v\n", model.GetDisplayName())
	fmt.Fprintf(w, "Model create time:\n")
	fmt.Fprintf(w, "\tseconds: %v\n", model.GetCreateTime().GetSeconds())
	fmt.Fprintf(w, "\tnanos: %v\n", model.GetCreateTime().GetNanos())
	fmt.Fprintf(w, "Model deployment state: %v\n", deploymentState)

	return nil
}

Java

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

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

class GetModel {

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

  // Get a model
  static void getModel(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);
      Model model = client.getModel(modelFullId);

      // Display the model information.
      System.out.format("Model name: %s\n", model.getName());
      // To get the model id, you have to parse it out of the `name` field. As models Ids are
      // required for other methods.
      // Name Format: `projects/{project_id}/locations/{location_id}/models/{model_id}`
      String[] names = model.getName().split("/");
      String retrievedModelId = names[names.length - 1];
      System.out.format("Model id: %s\n", retrievedModelId);
      System.out.format("Model display name: %s\n", model.getDisplayName());
      System.out.println("Model create time:");
      System.out.format("\tseconds: %s\n", model.getCreateTime().getSeconds());
      System.out.format("\tnanos: %s\n", model.getCreateTime().getNanos());
      System.out.format("Model deployment state: %s\n", model.getDeploymentState());
    }
  }
}

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 getModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

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

  console.log(`Model name: ${response.name}`);
  console.log(
    `Model id: ${
      response.name.split('/')[response.name.split('/').length - 1]
    }`
  );
  console.log(`Model display name: ${response.displayName}`);
  console.log('Model create time');
  console.log(`\tseconds ${response.createTime.seconds}`);
  console.log(`\tnanos ${response.createTime.nanos / 1e9}`);
  console.log(`Model deployment state: ${response.deploymentState}`);
}

getModel();

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)
model = client.get_model(name=model_full_id)

# Retrieve deployment state.
if model.deployment_state == automl.Model.DeploymentState.DEPLOYED:
    deployment_state = "deployed"
else:
    deployment_state = "undeployed"

# Display the model information.
print(f"Model name: {model.name}")
print("Model id: {}".format(model.name.split("/")[-1]))
print(f"Model display name: {model.display_name}")
print(f"Model create time: {model.create_time}")
print(f"Model deployment state: {deployment_state}")

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Vision Object Detection リファレンス ドキュメントをご覧ください。

再開可能なトレーニング

これで、大規模なデータセット(1,000 個を超える画像)でカスタムモデルのトレーニングを一時停止し、再開できるようになりました。モデルのトレーニングの一時停止は、一時停止ボタンを使用した手動によるアクションではありません。代わりに、ノード時間予算を特定の時間(2 時間など)に設定します。設定した時間に達すると、モデルのステータスに関係なく、トレーニングは自動的に停止します。

再開可能なトレーニングには次の制限があります。

  • 基本モデルの時間制限 - トレーニングを再開できるのは、直近の 14 日間にトレーニングされたモデルのみです。リクエストの 14 日以上前に作成されたベースモデルは再開可能なトレーニングの対象外です。
  • ラベルの変更なし - ベースモデルのデータセットでラベルを変更すると、再開可能なトレーニングは失敗します。
  • パフォーマンスの向上は保証されません - モデルで再開可能なトレーニングを使用しても、モデルのパフォーマンスが向上するとは限りません。

ウェブ UI

このサンプルを試す前に、クライアント ライブラリ ページを参照して、この言語の設定手順を完了してください。

  1. AutoML Vision UI を開きます。

    [データセット] ページに、現在のプロジェクトで使用可能なデータセットが表示されます。

    データセット一覧ページ
  2. カスタムモデルのトレーニングに使用するデータセットを選択します。

    選択したデータセットの表示名がタイトルバーに表示され、データセット内の個々の項目がラベルと一緒にページに一覧表示されます。

    画像項目ページ
  3. データセットの確認を終えたら、タイトルバーのすぐ下にある [トレーニング] タブを選択します。

    以前にトレーニングしたモデルは、このタブのリストに表示されます。

    トレーニング済みモデルのリスト
  4. モデルで再開可能なトレーニングが利用可能な場合、[評価全体を見る] の近くにオプションが表示されます。

    [トレーニングを再開] を選択して、該当するモデルでトレーニングを再開します。

    トレーニングの再開オプション
  5. 元のモデルのトレーニングと同様に、[トレーニングを再開] を選択すると、[新しいモデルのトレーニング] サイド ウィンドウが表示されます。[モデルの定義] セクションで、新しいモデルの名前を変更できます。また、このモデルのトレーニングに使用されたベースモデルの名前も表示されます。

    モデルのサイド ウィンドウを定義する

    モデルを定義したら、[続行] を選択して次のセクションに進みます。

  6. [ノード時間予算の設定] セクションで、ノード時間予算を指定します。この予算には、初期モデル トレーニングと同様の料金体系と割り当て制限が適用されます。

    トレーニング予算を指定したら、[トレーニングを開始] を選択します。再開可能なトレーニングが終了すると、メールが届きます。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • base-model-id: 基本(既存)モデルの ID。新しいモデルは、この基本モデルに基づいて作成されます。次の新規モデルの仕様は、基本モデルに一致する必要があります。
    • プロジェクト
    • ロケーション
    • modelType*

    * 新しいモデルのリクエストでこのフィールドが省略されていても、基本と新しい modelType はチェックされます。

  • project-id: GCP プロジェクト ID
  • display-name: 選択した文字列の表示名。
  • dataset-id: データセットの IDこの ID は、データセットの名前の最後の要素です。例:
    • データセット名: projects/project-id/locations/location-id/datasets/3104518874390609379
    • データセット ID: 3104518874390609379

HTTP メソッドと URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models

リクエストの本文(JSON):

{
  "baseModelId": BASE_MODEL_ID,
  "displayName": "DISPLAY_NAME",
  "datasetId": "DATASET_ID",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1"
  }
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models" | Select-Object -Expand Content

出力は次のようになります。タスクのステータスは、オペレーション ID(この場合は ICN2106290444865378475)を使用して取得できます。例については、長時間実行オペレーションによる作業をご覧ください。

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN2106290444865378475",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-30T20:06:08.253243Z",
    "updateTime": "2019-10-30T20:06:08.253243Z",
    "createModelDetails": {}
  }
}