Managing models

Since AutoML Vision Object Detection 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, get a specific model, update a model's node number, or delete models you no longer need.

Note: Unless otherwise specified in applicable terms of service or documentation, custom models created in Cloud AutoML products cannot be exported.

Listing models

A project can include numerous models. This section describes how to retrieve a list of the available models for a project.

Web UI

To see a list of the available models using the AutoML Vision Object Detection UI, click the Models link at the top of the left navigation menu.

Listing models image

To see the models for a different project, select the project from the drop-down list in the upper right of the title bar.

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/models

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

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" | Select-Object -Expand Content

You should receive a JSON response similar to the following example. This response shows information about two Cloud-hosted models.

{
  "model": [
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-1",
      "displayName": "display-name-1",
      "datasetId": "dataset-id",
      "createTime": "2019-07-26T21:10:18.338846Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-08-07T22:24:07.720068Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "cloud-low-latency-1",
        "nodeQps": 1.2987012987012987,
        "stopReason": "MODEL_CONVERGED",
        "trainBudgetMilliNodeHours": "216000",
        "trainCostMilliNodeHours": "8230"
      }
    },
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-2",
      "displayName": "display-name-2",
      "datasetId": "dataset-id",
      "createTime": "2019-07-22T18:35:06.881193Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-07-22T19:58:44.980357Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "mobile-versatile-1",
        "nodeQps": -1,
        "stopReason": "MODEL_CONVERGED",
        "trainBudgetMilliNodeHours": "24000",
        "trainCostMilliNodeHours": "9367"
      }
    },
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-3",
      "displayName": "display-name-3",
      "datasetId": "dataset-id",
      "createTime": "2019-03-31T22:56:51.348238Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-07-22T18:42:44.594876Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "cloud-high-accuracy-1",
        "nodeQps": 0.6872852233676976
      }
    }
  ]
}

Go

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

import (
	"context"
	"fmt"
	"io"

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

// listModels lists existing models.
func listModels(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 := &automlpb.ListModelsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListModels(ctx, req)

	// Iterate over all results
	for {
		model, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListModels.Next: %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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.AutoMlSettings;
import com.google.cloud.automl.v1.ListModelsRequest;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.Model;
import java.io.IOException;
import org.threeten.bp.Duration;

class ListModels {

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

  // List the models available in the specified location
  static void listModels(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 models request.
      ListModelsRequest listModelsRequest =
          ListModelsRequest.newBuilder()
              .setParent(projectLocation.toString())
              .setFilter("")
              .build();

      // List all the models available in the region by applying filter.
      System.out.println("List of models:");
      for (Model model : client.listModels(listModelsRequest).iterateAll()) {
        // 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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

/**
 * 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 listModels() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    filter: 'translation_model_metadata:*',
  };

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

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

listModels();

PHP

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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';

$client = new AutoMlClient();

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

    $pagedResponse = $client->listModels($formattedParent);

    print('List of models' . PHP_EOL);
    foreach ($pagedResponse->iteratePages() as $page) {
        foreach ($page as $model) {
            // 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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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"

request = automl.ListModelsRequest(parent=project_location, filter="")
response = client.list_models(request=request)

print("List of models:")
for model in response:
    # Display the model information.
    if (
        model.deployment_state
        == automl.Model.DeploymentState.DEPLOYED
    ):
        deployment_state = "deployed"
    else:
        deployment_state = "undeployed"

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

Ruby

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::AutoML.auto_ml
# A resource that represents Google Cloud Platform location.
project_location = client.location_path project: project_id,
                                        location: "us-central1"
models = client.list_models parent: project_location

puts "List of models:"

models.each do |model|
  # Display the model information.
  deployment_state = if model.deployment_state == :DEPLOYED
                       "deployed"
                     else
                       "undeployed"
                     end

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

Get a model

You can get a specific trained model to modify or for prediction.

Web UI

To see a list of the available models using the AutoML Vision Object Detection UI, click the Models link at the top of the left navigation menu.

Listing models image

To see the models for a different project, select the project from the drop-down list in the upper right of the title bar.

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-07-26T21:10:18.338846Z",
  "deploymentState": "UNDEPLOYED",
  "updateTime": "2019-07-26T22:28:57.464076Z",
  "imageObjectDetectionModelMetadata": {
    "modelType": "cloud-low-latency-1",
    "nodeQps": 1.2987012987012987,
    "stopReason": "MODEL_CONVERGED",
    "trainBudgetMilliNodeHours": "216000",
    "trainCostMilliNodeHours": "8230"
  }
}

Java

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

/**
 * 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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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("Model name: {}".format(model.name))
print("Model id: {}".format(model.name.split("/")[-1]))
print("Model display name: {}".format(model.display_name))
print("Model create time: {}".format(model.create_time))
print("Model deployment state: {}".format(deployment_state))

Ruby

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"
model_id = "YOUR_MODEL_ID"

client = Google::Cloud::AutoML.auto_ml

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

model = client.get_model name: 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}"

Update a model's node number

Once you have a trained deployed model you can update the number of nodes the model is deployed on to respond to your specific amount of traffic. For example, if you experience a higher amount of queries per second (QPS) than expected.

You can change this node number without first having to undeploy the model. Updating deployment will change the node number without interrupting your served prediction traffic.

Web UI

  1. In the Cloud AutoML Vision Object Detection UI and select the Models tab (with lightbulb icon) in the left navigation bar to display the available models.

    To view the models for a different project, select the project from the drop-down list in the upper right of the title bar.

  2. Select your trained model that has been deployed.
  3. Select the Test & Use tab just below the title bar.
  4. A message is displayed in a box at the top of the page that says "Your model is deployed and is available for online prediction requests". Select the Update deployment option to the side of this text.

    image of update deployment button
  5. In the Update deployment window that opens select the new node number to deploy your model on from the list. Node numbers display their estimated prediction queries per second (QPS). image of update deployment popup window
  6. After selecting a new node number from the list select Update deployment to update the node number the model is deployed on.

    update deployment window after selecting a new node number
  7. You will be returned to the Test & Use window where you see the text box now displaying "Deploying model...". model deploying
  8. After your model has successfully deployed on the new node number you will receive an email at the address associated with your project.

REST & CMD LINE

The same method you use to initially use to deploy a model is used to change the deployed model's node number.

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

Field considerations:

  • nodeCount - The number of nodes to deploy the model on. The value must be between 1 and 100, inclusive on both ends. A node is an abstraction of a machine resource, which can handle online prediction queries per second (QPS) as given in the model's qps_per_node.

HTTP method and URL:

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

Request JSON body:

{
  "imageObjectDetectionModelDeploymentMetadata": {
    "nodeCount": 2
  }
}

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/model-id:deploy

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/model-id:deploy" | Select-Object -Expand Content

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

{
  "name": "projects/project-id/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-08-07T22:00:20.692109Z",
    "updateTime": "2019-08-07T22:00:20.692109Z",
    "deployModelDetails": {}
  }
}

Go

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

import (
	"context"
	"fmt"
	"io"

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

// visionObjectDetectionDeployModelWithNodeCount deploys a model with node count.
func visionObjectDetectionDeployModelWithNodeCount(w io.Writer, projectID string, location string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "IOD123456789..."

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

	req := &automlpb.DeployModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		ModelDeploymentMetadata: &automlpb.DeployModelRequest_ImageObjectDetectionModelDeploymentMetadata{
			ImageObjectDetectionModelDeploymentMetadata: &automlpb.ImageObjectDetectionModelDeploymentMetadata{
				NodeCount: 2,
			},
		},
	}

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

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Model deployed.\n")

	return nil
}

Java

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DeployModelRequest;
import com.google.cloud.automl.v1.ImageObjectDetectionModelDeploymentMetadata;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VisionObjectDetectionDeployModelNodeCount {

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

  // Deploy a model for prediction with a specified node count (can be used to redeploy a model)
  static void visionObjectDetectionDeployModelNodeCount(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);
      ImageObjectDetectionModelDeploymentMetadata metadata =
          ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
      DeployModelRequest request =
          DeployModelRequest.newBuilder()
              .setName(modelFullId.toString())
              .setImageObjectDetectionModelDeploymentMetadata(metadata)
              .build();
      OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

      future.get();
      System.out.println("Model deployment finished");
    }
  }
}

Node.js

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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

  const [operation] = await client.deployModel(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Model deployment finished. ${response}`);
}

deployModelWithNodeCount();

PHP

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

use Google\Cloud\AutoMl\V1\AutoMlClient;
use Google\Cloud\AutoMl\V1\ImageObjectDetectionModelDeploymentMetadata;

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

    // set prediction node count
    $metadata = (new ImageObjectDetectionModelDeploymentMetadata())
        ->setNodeCount(2);
    $args = ['imageObjectDetectionModelDeploymentMetadata' => $metadata];

    $operationResponse = $client->deployModel($formattedName, $args);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        printf('Model deployed.' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $client->close();
}

Python

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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)

# node count determines the number of nodes to deploy the model on.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#imageobjectdetectionmodeldeploymentmetadata
metadata = automl.types.ImageObjectDetectionModelDeploymentMetadata(
    node_count=2
)
response = client.deploy_model(
    model_full_id,
    image_object_detection_model_deployment_metadata=metadata,
)

print("Model deployment finished. {}".format(response.result()))

Ruby

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"
model_id = "YOUR_MODEL_ID"

client = Google::Cloud::AutoML.auto_ml
# Get the full path of the model.
model_full_id = client.model_path project: project_id,
                                  location: "us-central1",
                                  model: model_id
metadata = { node_count: 2 }
operation = client.deploy_model name: model_full_id,
                                image_object_detection_model_deployment_metadata: metadata

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

puts "Model deployment finished."

Deleting a model

You can delete a model resource by using the model ID.

Web UI

  1. In the AutoML Vision Object Detection UI, click the lightbulb icon in the left navigation menu to display the list of available models.

  2. Click the three-dot menu at the far right of the row you want to delete and select Delete model.

  3. Click Delete in the confirmation dialog box.

    Deleting a model image

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:

DELETE 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 DELETE \
-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 DELETE `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id" | Select-Object -Expand Content

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

{
  "name": "projects/project-id/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-11-01T15:59:36.196506Z",
    "updateTime": "2018-11-01T15:59:36.196506Z",
    "deleteDetails": {}
  }
}

Go

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

import (
	"context"
	"fmt"
	"io"

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

// deleteModel deletes a model.
func deleteModel(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.DeleteModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

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

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Model deleted.\n")

	return nil
}

Java

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

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

PHP

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

use Google\Cloud\AutoMl\V1\AutoMlClient;

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

    $operationResponse = $client->deleteModel($formattedName);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        printf('Model deleted.' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $client->close();
}

Python

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

from google.cloud import automl

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

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

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

Ruby

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.

require "google/cloud/automl"

project_id = "YOUR_PROJECT_ID"
model_id = "YOUR_MODEL_ID"

client = Google::Cloud::AutoML.auto_ml

# Get the full path of the dataset
model_full_id = client.model_path project: project_id,
                                  location: "us-central1",
                                  model: model_id

operation = client.delete_model name: model_full_id

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

if operation.error?
  puts "Model was not deleted. #{operation.error}"
else
  puts "Model deleted."
end