Training Cloud-hosted models

You create a custom model by training it using a prepared dataset. AutoML API uses the items from the dataset to train the model, test it, and evaluate its performance. You review the results, adjust the training dataset as needed, and train a new model using the improved dataset.

Training a model can take several hours to complete. The AutoML API enables you to check the status of training.

Since AutoML Vision creates a new model each time you start training, your project may include numerous models. You can get a list of the models in your project can delete models you no longer need. Alternatively, you can use the Cloud AutoML Vision UI to list and delete models created via the AutoML API that you do not need anymore.

Note:

  • Unless otherwise specified in applicable terms of service or documentation, custom models created in Cloud AutoML products cannot be exported.
  • The maximum lifespan for a custom model is 18 months as of the GA release. You must create and train a new model to continue classifying content after that amount of time.
  • Edge models are optimized for inference on an Edge device. Consequently, Edge model accuracy will differ from Cloud model accuracy.

Training models

When you have a dataset with a representative set of labeled training items, you are ready to create and train the custom model.

Web UI

  1. Open the AutoML Vision UI.

    The Datasets page shows the available datasets for the current project.

    Dataset list page

  2. Select the dataset you want to use to train the custom model.

    The display name of the selected dataset appears in the title bar, and the page lists the individual items in the dataset along with their labels.

    Image items page

  3. When you are done reviewing the dataset, click the Train tab just below the title bar.

    The training page provides a basic analysis of your dataset and advises you about whether it is adequate for training. If AutoML Vision suggests changes, consider returning to the Images page and adding items or labels.

  4. When the dataset is ready, click Start Training.

Training a model can take several hours to complete. After the model is successfully trained, you will receive a message at the email address that you used to sign up for the program.

Integrated UI

  1. Open the Vision Dashboard.

    The Datasets page shows the available datasets for the current project.

    updated dataset list page

  2. Select the dataset you want to use to train the custom model.

    The display name of the selected dataset appears in the title bar, and the page lists the individual items in the dataset along with their labels.

    updated image items page

  3. When you are done reviewing the dataset, select the Train tab just below the title bar.

    The training page provides a basic analysis of your dataset and advises you about whether it is adequate for training. If AutoML Vision suggests changes, consider returning to the Images page and adding items or labels.

  4. When the dataset is ready, select Start Training.

  5. A side window with model training options will appear. Choose a proper training budget value based on your dataset size.

    By default, 24 node hours should be sufficient for most datasets.

  6. Optional: Select the checkbox check_box Deploy model to 1 node after training to opt-in to automatic model deployment after training has completed.

    Automatic model deployment means your model will be available for prediction immediately after training.

  7. Select Start training.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID.
  • dataset-id: the ID of your dataset. The ID is the last element of the name of your dataset. For example:
    • dataset name: projects/project-id/locations/location-id/datasets/3104518874390609379
    • dataset id: 3104518874390609379
  • display-name: a string display name of your choosing.

HTTP method and URL:

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

Request JSON body:

{
    "displayName": "display-name",
    "datasetId": "dataset-id",
    "imageClassificationModelMetadata": {
      "trainBudget": "1",
      "modelType": "cloud"
    }
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

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

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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

You should see output similar to the following. You can use the operation ID (ICN3819960680614725486, in this case) to get the status of the task. For an example, see Working with long-running operations.

{
  "name": "projects/project-id/locations/us-central1/operations/ICN3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-29T19:06:38.048492Z",
    "updateTime": "2019-10-29T19:06:38.048492Z",
    "createModelDetails": {}
  }
}

C#

/// <summary>
/// Demonstrates using the AutoML client to create a model.
/// </summary>
/// <param name="projectId">GCP Project ID.</param>
/// <param name="datasetId">the Id of the dataset.</param>
/// <param name="displayName">The name of the dataset to be created.</param>
public static object VisionClassificationCreateModel(string projectId = "YOUR-PROJECT-ID",
    string datasetId = "YOUR_DATASET_ID",
    string displayName = "YOUR_DATASET_NAME")
{
    // Initialize the client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    AutoMlClient client = AutoMlClient.Create();

    // A resource that represents Google Cloud Platform location.
    string projectLocation = LocationName.Format(projectId, "us-central1");
    // Set model metadata.
    ImageClassificationModelMetadata metadata = new ImageClassificationModelMetadata
    {
        TrainBudgetMilliNodeHours = 24000
    };
    Model model = new Model
    {
        DisplayName = displayName,
        DatasetId = datasetId,
        ImageClassificationModelMetadata = metadata
    };

    // Create a model with the model metadata in the region.
    Operation<Model, OperationMetadata> response =
        client.CreateModel(projectLocation, model);
    // Don't wait for model creation to finish, as this can take several hours.
    // However, you can use the `name` of the operation to check the status of your model.

    Console.WriteLine($"Training operation name: {response.Name}");
    Console.WriteLine("Training started...");
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1"
)

// 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: %v", 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: %v", 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: {
        train_budget_milli_node_hours: 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();

PHP

use Google\Cloud\AutoMl\V1\AutoMlClient;
use Google\Cloud\AutoMl\V1\Model;
use Google\Cloud\AutoMl\V1\ImageClassificationModelMetadata;

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $datasetId = 'my_dataset_id_123';
// $displayName = 'your_dataset_name';

$client = new AutoMlClient();

try {
    // resource that represents Google Cloud Platform location
    $formattedParent = $client->locationName(
        $projectId,
        $location
    );

    // leave model unset to use the default base model provided by Google
    $metadata = new ImageClassificationModelMetadata();
    $model = (new Model())
        ->setDisplayName($displayName)
        ->setDatasetId($datasetId)
        ->setImageClassificationModelMetadata($metadata);

    // create model with above location and metadata
    $operationResponse = $client->createModel($formattedParent, $model);
    $operation = $operationResponse->getOperation();
    printf('Training operation name: %s' . PHP_EOL, $operation->getName());
    print('Training started...' . PHP_EOL);
} finally {
    $client->close();
}

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 = client.location_path(project_id, 'us-central1')
# Leave model unset to use the default base model provided by Google
metadata = automl.types.ImageClassificationModelMetadata()
model = automl.types.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(project_location, model)

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

Ruby

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"
dataset_id = "YOUR_DATASET_ID"
display_name = "YOUR_MODEL_NAME"

client = Google::Cloud::AutoML::AutoML.new

# A resource that represents Google Cloud Platform location.
project_location = client.location_path project_id, "us-central1"
# Leave model unset to use the default base model provided by Google
metadata = automl.types.ImageClassificationModelMetadata()
model = automl.types.Model(
  display_name = display_name,
  dataset_id = dataset_id,
  image_classification_model_metadata = metadata
)

# Create a model with the model metadata in the region.
operation = client.create_model project_location, model

puts "Training started..."

# Wait until the long running operation is done
operation.wait_until_done!

puts "Training complete."

List operations

You can list your project's operations, and filter results.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID.

HTTP method and URL:

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

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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

The output you see will vary depending on the operations you have requested.

You can also filter the operations returned by using select query parameters (operationId, done, and worksOn). For example, to return a list of operations that have finished running modify the URL:

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

C#

/// <summary>
/// Demonstrates using the AutoML client to list operations.
/// </summary>
/// <param name="projectId">GCP Project ID.</param>
public static object ListOperationStatus(string projectId = "YOUR-PROJECT-ID")
{
    // Initialize the client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    AutoMlClient client = AutoMlClient.Create();

    // A resource that represents Google Cloud Platform location.
    string projectLocation = LocationName.Format(projectId, "us-central1");

    // Create list operations request.
    ListOperationsRequest listrequest = new ListOperationsRequest
    {
        Name = projectLocation
    };

    // List all the operations names available in the region by applying filter.
    foreach (Operation operation in
      client.CreateModelOperationsClient.ListOperations(listrequest))
    {
        Console.WriteLine($"Operation details:");
        Console.WriteLine($"\tName: {operation.Name}");
        Console.WriteLine($"\tMetadata Type Url: { operation.Metadata.TypeUrl}");
        Console.WriteLine($"\tDone: {operation.Done}");
        if (operation.Response != null)
        {
            Console.WriteLine($"\tResponse Type Url: {operation.Response.TypeUrl}");
        }
        if (operation.Error != null)
        {
            Console.WriteLine("\tResponse:");
            Console.WriteLine($"\t\tError code: {operation.Error.Code}");
            Console.WriteLine($"\t\tError message: {operation.Error.Message}");
        }
    }

    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"google.golang.org/api/iterator"
	"google.golang.org/genproto/googleapis/longrunning"
)

// 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: %v", 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: %v", err)
		}

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

	return nil
}

Java

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

/**
 * 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: '',
  };

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

PHP

use Google\ApiCore\LongRunning\OperationsClient;

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $operationId = 'my_operation_id_123';

$client = new OperationsClient();

try {
    // resource that represents Google Cloud Platform location
    $formattedName = $client->locationName(
        $projectId,
        $location
    );

    // list all operations
    $filter = '';
    $pagedResponse = $client->listOperations($formattedName, '');

    print('List of models' . PHP_EOL);
    foreach ($pagedResponse->iteratePages() as $page) {
        foreach ($page as $operation) {
            // display operation information
            printf('Operation name: %s' . PHP_EOL, $operation->getName());
            print('Operation details: ');
            print($operation);
        }
    }
} finally {
    if (isset($client)) {
        $client->close();
    }
}

Python

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 = client.location_path(project_id, 'us-central1')
# List all the operations names available in the region.
response = client.transport._operations_client.list_operations(
    project_location, '')

print('List of operations:')
for operation in response:
    print(u'Name: {}'.format(operation.name))
    print('Operation details:')
    print(operation)

Getting the status of an operation

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID.
  • operation-id: the ID of your operation. The ID is the last element of the name of your operation. For example:
    • operation name: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • operation id: IOD5281059901324392598

HTTP method and URL:

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

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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
You should see output similar to the following for a completed import operation:
{
  "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"
  }
}

You should see output similar to the following for a completed create model operation:

{
  "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"
  }
}

C#

/// <summary>
/// Demonstrates using the AutoML client to get operation status.
/// </summary>
/// <param name="operationFullId">the complete name of a operation. For example, the name of your
/// operation is projects/[projectId]/locations/us-central1/operations/[operationId].</param>
public static object GetOperationStatus(string operationFullId
    = "projects/[projectId]/locations/us-central1/operations/[operationId]")
{
    // Initialize the client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    AutoMlClient client = AutoMlClient.Create();

    // Get the latest state of a long-running operation.
    //TODO: I dont know why there is no 'GetOperationsClient'
    Operation operation = client.CreateModelOperationsClient.GetOperation(operationFullId);

    // Display operation details.
    Console.WriteLine("Operation details:");
    Console.WriteLine($"\tName: {operation.Name}");
    Console.WriteLine($"\tMetadata Type Url: {operation.Metadata.TypeUrl}");
    Console.WriteLine($"\tDone: {operation.Done}");
    if (operation.Response != null)
    {
        Console.WriteLine($"\tResponse Type Url: {operation.Response.TypeUrl}");
    }
    if (operation.Error != null)
    {
        Console.WriteLine("\tResponse:");
        Console.WriteLine($"\t\tError code: {operation.Error.Code}");
        Console.WriteLine($"\t\tError message: {operation.Error.Message}");
    }

    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"google.golang.org/genproto/googleapis/longrunning"
)

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

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

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

	op, err := client.LROClient.GetOperation(ctx, req)
	if err != nil {
		return fmt.Errorf("GetOperation: %v", err)
	}

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

	return nil
}

Java

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

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

PHP

use Google\ApiCore\LongRunning\OperationsClient;

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $operationId = 'my_operation_id_123';

$client = new OperationsClient();

try {
    // full name of operation
    $formattedName = 'projects/' . $projectId . '/locations/us-central1/operations/' . $operationId;

    // get latest state of long running operation
    $operation = $client->getOperation($name);
    printf('Operation name: %s' . PHP_EOL, $operation->getName());
    print('Operation details: ');
    print($operation);
} finally {
    if (isset($client)) {
        $client->close();
    }
}

Python

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(u'Name: {}'.format(response.name))
print('Operation details:')
print(response)

Cancelling an Operation

You can cancel an import or training task using the operation ID.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID.
  • operation-id: the ID of your operation. The ID is the last element of the name of your operation. For example:
    • operation name: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • operation id: IOD5281059901324392598

HTTP method and URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/operations/operation-id:cancel

To send your request, choose one of these options:

curl

Execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-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

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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
You will see an empty JSON object returned from a successful request:
{}

Getting information about a model

When training is complete, you can get information about the newly created model.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID.
  • model-id: the ID of your model, from the response when you created the model. The ID is the last element of the name of your model. For example:
    • model name: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • model id: IOD4412217016962778756

HTTP method and URL:

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

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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

You should receive a JSON response similar to the following:

{
  "name": "projects/project-id/locations/us-central1/models/model-id",
  "displayName": "display-name",
  "datasetId": "dataset-id",
  "createTime": "2019-10-29T19:06:38.048492Z",
  "deploymentState": "UNDEPLOYED",
  "updateTime": "2019-10-29T19:35:19.104716Z",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "cloud",
    "nodeQps": 3.2
  }
}

C#

/// <summary>
/// Demonstrates using the AutoML client to get a model by ID.
/// </summary>
/// <param name="projectId">GCP Project ID.</param>
/// <param name="modelId">the Id of the model.</param>
public static object GetModel(string projectId = "YOUR-PROJECT-ID",
    string modelId = "YOUR-MODEL-ID")
{
    // Initialize the client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    AutoMlClient client = AutoMlClient.Create();

    // Get the full path of the model.
    string modelFullId = ModelName.Format(projectId, "us-central1", modelId);
    Model model = client.GetModel(modelFullId);

    // Display the model information.
    Console.WriteLine($"Model name: {model.Name}");
    // 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.Name.Split("/");
    string retrievedModelId = names[names.Length - 1];
    Console.WriteLine($"Model id: {retrievedModelId}");
    Console.WriteLine($"Model display name: {model.DisplayName}");
    Console.WriteLine($"Model create time:");
    Console.WriteLine($"\tseconds: { model.CreateTime.Seconds}");
    Console.WriteLine($"\tnanos: {model.CreateTime.Nanos}");
    Console.WriteLine($"Model deployment state: { model.DeploymentState}");

    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1"
)

// 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: %v", 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: %v", 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();

PHP

use Google\Cloud\AutoMl\V1\AutoMlClient;
use Google\Cloud\AutoMl\V1\Model\DeploymentState;

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $modelId = 'my_model_id_123';

$client = new AutoMlClient();

try {
    // get full path of model
    $formattedName = $client->modelName(
        $projectId,
        $location,
        $modelId
    );

    $model = $client->getModel($formattedName);

    // retrieve deployment state
    if ($model->getDeploymentState() == DeploymentState::DEPLOYED) {
        $deployment_state = 'deployed';
    } else {
        $deployment_state = 'undeployed';
    }

    // display model information
    $splitName = explode('/', $model->getName());
    printf('Model name: %s' . PHP_EOL, $model->getName());
    printf('Model id: %s' . PHP_EOL, end($splitName));
    printf('Model display name: %s' . PHP_EOL, $model->getDisplayName());
    printf('Model create time' . PHP_EOL);
    printf('seconds: %d' . PHP_EOL, $model->getCreateTime()->getSeconds());
    printf('nanos : %d' . PHP_EOL, $model->getCreateTime()->getNanos());
    printf('Model deployment state: %s' . PHP_EOL, $deployment_state);
} finally {
    $client->close();
}

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

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

# Display the model information.
print(u'Model name: {}'.format(model.name))
print(u'Model id: {}'.format(model.name.split('/')[-1]))
print(u'Model display name: {}'.format(model.display_name))
print(u'Model create time:')
print(u'\tseconds: {}'.format(model.create_time.seconds))
print(u'\tnanos: {}'.format(model.create_time.nanos))
print(u'Model deployment state: {}'.format(deployment_state))

Ruby

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"
model_id = "YOUR_MODEL_ID"

client = Google::Cloud::AutoML::AutoML.new

# Get the full path of the model.
model_full_id = client.class.model_path project_id, "us-central1", model_id

model = client.get_model model_full_id

# Retrieve deployment state.
deployment_state = if model.deployment_state == :DEPLOYED
                     "deployed"
                   else
                     "undeployed"
                   end

# Display the model information.
puts "Model name: #{model.name}"
puts "Model id: #{model.name.split('/').last}"
puts "Model display name: #{model.display_name}"
puts "Model create time: #{model.create_time.to_time}"
puts "Model deployment state: #{deployment_state}"