List models

Demonstrate listing models.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Java

To authenticate to AutoML Tables, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to AutoML Tables, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const automl = require('@google-cloud/automl');
const client = new automl.v1beta1.AutoMlClient();

/**
 * Demonstrates using the AutoML client to list all models.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const filter_ = '[FILTER_EXPRESSIONS]' e.g., "tablesModelMetadata:*";

// A resource that represents Google Cloud Platform location.
const projectLocation = client.locationPath(projectId, computeRegion);

// List all the models available in the region by applying filter.
client
  .listModels({parent: projectLocation, filter: filter})
  .then(responses => {
    const model = responses[0];

    // Display the model information.
    console.log('List of models:');
    for (let i = 0; i < model.length; i++) {
      console.log(`\nModel name: ${model[i].name}`);
      console.log(`Model Id: ${model[i].name.split('/').pop(-1)}`);
      console.log(`Model display name: ${model[i].displayName}`);
      console.log(`Dataset Id: ${model[i].datasetId}`);
      console.log('Tables model metadata:');
      console.log(
        `\tTraining budget: ${model[i].tablesModelMetadata.trainBudgetMilliNodeHours}`
      );
      console.log(
        `\tTraining cost: ${model[i].tablesModelMetadata.trainCostMilliNodeHours}`
      );
      console.log(`Model deployment state: ${model[i].deploymentState}`);
    }
  })
  .catch(err => {
    console.error(err);
  });

Python

To authenticate to AutoML Tables, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# filter = 'DATASET_DISPLAY_NAME_HERE'

from google.cloud import automl_v1beta1 as automl

client = automl.TablesClient(project=project_id, region=compute_region)

# List all the models available in the region by applying filter.
response = client.list_models(filter=filter)

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

    # Display the model information.
    print(f"Model name: {model.name}")
    print("Model id: {}".format(model.name.split("/")[-1]))
    print(f"Model display name: {model.display_name}")
    metadata = model.tables_model_metadata
    print(
        "Target column display name: {}".format(
            metadata.target_column_spec.display_name
        )
    )
    print(
        "Training budget in node milli hours: {}".format(
            metadata.train_budget_milli_node_hours
        )
    )
    print(
        "Training cost in node milli hours: {}".format(
            metadata.train_cost_milli_node_hours
        )
    )
    print(f"Model create time: {model.create_time}")
    print(f"Model deployment state: {deployment_state}")
    print("\n")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.