Managing models

You create a custom model by training it using a prepared dataset. AutoML Natural Language 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 Natural Language 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 and can delete models that you no longer need.

Getting information about a model

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

The examples in this section return the basic metadata about a model. To get details about a model's accuracy and readiness, see Evaluating models.

REST & CMD LINE

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

  • project-id: your project ID
  • location-id: the location for the resource, us-central1 for the Global location or eu for the European Union
  • model-id: your model ID

HTTP method and URL:

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

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "model": [
    {
      "name": "projects/434039606874/locations/us-central1/models/3745331181667467569",
      "createTime": "2018-04-27T02:00:22.329970Z",
      "textClassificationModelMetadata": {
      },
      "displayName": "a_98487760535e48319dd204e6394670"
    },
}

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("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:")
print("\tseconds: {}".format(model.create_time.seconds))
print("\tnanos: {}".format(model.create_time.nanos))
print("Model deployment state: {}".format(deployment_state))

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

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}");
    Console.WriteLine($"Model id: {model.ModelName.ModelId}");
    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
}

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

Ruby

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

Listing models

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

To see a list of the available models using the AutoML Natural Language UI, click the lightbulb icon in the left navigation bar.

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 project ID
  • location-id: the location for the resource, us-central1 for the Global location or eu for the European Union

HTTP method and URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "model": [
    {
      "name": "projects/434039606874/locations/us-central1/models/7537307368641647584",
      "displayName": "c982e11ffbd5455e8d9bee2734f01f81",
      "textClassificationModelMetadata": {
      },
      "createTime": "2018-04-30T23:06:19.223230Z"
    },
    {
      "name": "projects/434039606874/locations/us-central1/models/6877109870585533885",
      "displayName": "test_201801111318",
      "textClassificationModelMetadata": {
      },
      "createTime": "2018-01-11T21:25:05.893590Z"
    }
  ]
}

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")
response = client.list_models(project_location, "")

print("List of models:")
for model in response:
    # Display the model information.
    if (
        model.deployment_state
        == automl.enums.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:")
    print("\tseconds: {}".format(model.create_time.seconds))
    print("\tnanos: {}".format(model.create_time.nanos))
    print("Model deployment state: {}".format(deployment_state))

Java

import com.google.cloud.automl.v1.AutoMlClient;
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;

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 listModlesRequest =
          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(listModlesRequest).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

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

C#

/// <summary>
/// Demonstrates using the AutoML client to list all models.
/// </summary>
/// <param name="projectId">GCP Project ID.</param>
public static object ListModels(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 models request.
    ListModelsRequest listModlesRequest = new ListModelsRequest
    {
        Parent = projectLocation,
        Filter = ""
    };

    // List all the models available in the region by applying filter.
    Console.WriteLine("List of models:");
    foreach (Model model in client.ListModels(listModlesRequest))
    {
        // 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"
	"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
}

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

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

Ruby

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

Deploying or undeploying a model

You must deploy a model before you can use it to make predictions. When training a model using the web UI, you have the option to automatically deploy the model when training is complete.

Deploying a model incurs charges. For more information, see the pricing page.

Inactive models are subject to automatic undeployment. An inactive model is one that has not been used for prediction in 60 days. An undeployed model is not available for use until you explicitly redeploy it using a method that will be made available in advance of any undeployments.

To see the deployment status of a model in the AutoML Natural Language UI, refer to the Deployed column on the model listing page. On the Test & Use tab, a note box appears just below the model name indicating whether the selected model is currently deployed and offering a link to change the deployment status. Click Deploy model or Remove deployment to change the model's status.

REST & CMD LINE

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

  • project-id: your project ID
  • location-id: the location for the resource, us-central1 for the Global location or eu for the European Union
  • model-name: your model name

HTTP method and URL:

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

To send your request, expand one of these options:

You should receive a successful status code (2xx) and an empty response.

Python

from google.cloud import automl

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

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

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

Java

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

class UndeployModel {

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

  // Undeploy a model from prediction
  static void undeployModel(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);
      UndeployModelRequest request =
          UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
      OperationFuture<Empty, OperationMetadata> future = client.undeployModelAsync(request);

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

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

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

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

undeployModel();

C#

/// <summary>
/// Undeploys a model.
/// </summary>
/// <param name="projectId">GCP Project ID.</param>
/// <param name="modelId">the Id of the model.</param>
public static object UndeployModel(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);
    UndeployModelRequest request = new UndeployModelRequest
    {
        Name = modelFullId
    };

    var result = Task.Run(() => client.UndeployModelAsync(request)).Result;
    result.PollUntilCompleted();
    Console.WriteLine("Model undeployment finished");
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

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

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

	op, err := client.UndeployModel(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 undeployed.\n")

	return nil
}

PHP

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->undeployModel($formattedName);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        printf('Model undeployed.' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $client->close();
}

Ruby

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.undeploy_model name: model_full_id

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

puts "Model undeployment finished."

Deleting a model

The following example deletes a model.

To delete a model using the AutoML Natural Language UI:

  1. In the AutoML Natural Language UI, click the lighbuld 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.

REST & CMD LINE

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

  • project-id: your project ID
  • location-id: the location for the resource, us-central1 for the Global location or eu for the European Union
  • model-name: your model name

HTTP method and URL:

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

To send your request, expand one of these options:

You should receive a successful status code (2xx) and an empty response.

Python

from google.cloud import automl

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

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

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

Java

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ModelName;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeleteModel {

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

  // Delete a model
  static void deleteModel(String projectId, String modelId)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);

      // Delete a model.
      Empty response = client.deleteModelAsync(modelFullId).get();

      System.out.println("Model deletion started...");
      System.out.println(String.format("Model deleted. %s", response));
    }
  }
}

Node.js

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

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

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

async function deleteModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [response] = await client.deleteModel(request);
  console.log(`Model deleted: ${response}`);
}

deleteModel();

C#

/// <summary>
/// Deletes a custom AutoML model.
/// </summary>
/// <returns>Success or failure as integer</returns>
/// <param name="projectId">Project identifier.</param>
/// <param name="modelId">Model identifier.</param>
public static object DeleteModel(string projectId,
                                 string modelId)
{
    // 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.
    var client = AutoMlClient.Create();

    // Get the full path of the model.
    var modelFullName =
        ModelName.Format(projectId, "us-central1", modelId);

    // Delete the model
    var response = client.DeleteModel(modelFullName);

    Console.WriteLine("Model deletion started ...");
    Console.WriteLine($"Model deleted. {response}");

    return 0;
}

Go

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
}

PHP

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

Ruby

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