Managing models

This page describes how to create and manage custom models using AutoML Tables.

Introduction

You create a custom model by training it using a prepared dataset. AutoML Tables uses the items from the dataset to train the model, test it, and evaluate its performance. You can 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 Cloud AutoML enables you to check the status of training.

Since AutoML Tables 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.

The maximum lifespan for a custom model is two years. You must create and train a new model to continue getting predictions after two years.

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

Using curl

To make it more convenient to run the curl samples in this topic, set the following environment variable. Replace project-id with the name of your GCP project.

export PROJECT_ID="project-id"

Creating a model

After you have created your dataset, you use that dataset to create (train) a model.

Console

  1. Visit the AutoML Tables page in the Google Cloud Platform Console to begin the process of creating and training your model.

    Go to the AutoML Tables page

  2. Under Datasets, select the dataset you want to use for your model.

  3. Select the Train tab and click Train model.

  4. Update the model name if needed.

  5. For Training budget, enter the maximum number of training hours for this model.

    Training budget is between 1 and 72 hours. This is the maximum amount of training time you will be charged for.

    Suggested training time is related to the number of rows in your training data:

    Rows Suggested training time
    Less than 100,000 1-3 hours
    100,000 - 1,000,000 1-6 hours
    1,000,000 - 10,000,000 1-12 hours
    More than 10,000,000 3 - 24 hours

    Model creation includes other tasks besides training, so the total time it takes to create your model is longer than the training time. For example, if you specify 2 training hours, it could still take 3 or more hours before the model is ready to deploy. You are charged only for actual training time.

    Learn more about training prices.

    If AutoML Tables detects that the model is no longer improving before the training budget is exhausted, it stops training. If you want to use the entire budgeted training time, open Advanced options and disable Early stopping.

  6. In the Input feature selection section, exclude any columns that you targeted for exclusion in the schema analysis step.

  7. If you do not want to use the default optimization objective, open Advanced options and select the metric you want AutoML Tables to optimize for when training your model. Learn more.

    Depending on the data type of your target column, there might be only one choice for Optimization objective.

  8. Click Train model to begin model training.

    Training a model can take several hours to complete depending on the size of the dataset and the training budget. You can close your browser window without affecting the training process.

    After the model is successfully trained, the Train tab shows high-level metrics for the model, such as precision and recall.

    High-level metrics for a trained model

    For help with evaluating the quality of your model, see Evaluating models.

curl command

If you set your target column in your dataset, setting the target column when you create your model is optional. You can override the target column setting in the dataset with a different, model-specific, value when you create the model.

  1. Get your full dataset name if you do not already have it.

    You can get the full name by listing your datasets. The full name has the format: projects/{project-id}/locations/us-central1/datasets/{dataset-id}

  2. Create the model, replacing:

    • dataset-name with the full name of your dataset.
    • model-display-name with the name of the model.
    • train-budget-milli-node-hours with the number of milli-node-hours for training. For example, 1000 = 1 hour.

      Suggested training time is related to the number of rows in your training data:

      Rows Suggested training time
      Less than 100,000 1-3 hours
      100,000 - 1,000,000 1-6 hours
      1,000,000 - 10,000,000 1-12 hours
      More than 10,000,000 3 - 24 hours

      Model creation includes other tasks besides training, so the total time it takes to create your model is longer than the training time. For example, if you specify 2 training hours, it could still take 3 or more hours before the model is ready to deploy. You are charged only for actual training time.

      Learn more about training prices.

      If AutoML Tables detects that the model is no longer improving before the training budget is exhausted, it stops training. If you want to use the entire budgeted training time, set the disableEarlyStopping property on the tablesModelMetadata object to true.

    • optimization-objective with the metric to optimize (optional).

      See About model optimization objectives.

    • column-spec-name with the full column name of your target column (optional).

    curl -X POST \
        -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
        -H "Content-Type: application/json" \
        -d '{
             "datasetId": "dataset-name",
             "displayName": "model-display-name",
             "tablesModelMetadata": {
               "trainBudgetMilliNodeHours": "train-budget-milli-node-hours",
               "optimizationObjective": "optimization-objective",
               "targetColumnSpec": {
                    "name": "column-spec-name"
               }
            },
        }' \
        https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models
    

    You should see output similar to the following. You can use the operation ID to get the status of the operation, or wait for it to complete. For more information, see Working with long-running operations.

    {
     "name": "projects/1234/locations/us-central1/operations/TBL745",
     "metadata": {
         "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
         "createTime": "2018-12-14T20:10:00.655898Z",
         "updateTime": "2018-12-14T20:10:00.655898Z",
         "createModelDetails": {}
      }
    }
    

Java

/**
 * Demonstrates using the AutoML client to create a model.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param datasetId the Id of the dataset to which model is created.
 * @param tableId the Id of the table.
 * @param columnId the Id of the column.
 * @param modelName the name of the model.
 * @param trainBudget the integer amount for maximum cost of model.
 * @throws IOException
 * @throws InterruptedException
 * @throws ExecutionException
 */
public static void createModel(
    String projectId,
    String computeRegion,
    String datasetId,
    String tableId,
    String columnId,
    String modelName,
    String trainBudget)
    throws IOException, InterruptedException, ExecutionException {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // A resource that represents Google Cloud Platform location.
  LocationName projectLocation = LocationName.of(projectId, computeRegion);

  // Get the complete path of the column.
  ColumnSpecName columnSpecId =
      ColumnSpecName.of(projectId, computeRegion, datasetId, tableId, columnId);

  // Build the get column spec request.
  GetColumnSpecRequest columnSpec =
      GetColumnSpecRequest.newBuilder().setName(columnSpecId.toString()).build();

  // Build the get column spec.
  ColumnSpec targetColumnSpec =
      ColumnSpec.newBuilder().setName(columnSpec.getName().toString()).build();

  // Set model meta data.
  TablesModelMetadata tablesModelMetadata =
      TablesModelMetadata.newBuilder()
          .setTargetColumnSpec(targetColumnSpec)
          .setTrainBudgetMilliNodeHours(Long.valueOf(trainBudget))
          .build();

  // Set model name, dataset and metadata.
  Model myModel =
      Model.newBuilder()
          .setDatasetId(datasetId)
          .setDisplayName(modelName)
          .setTablesModelMetadata(tablesModelMetadata)
          .build();

  // Build the Create model request.
  CreateModelRequest createModelRequestrequest =
      CreateModelRequest.newBuilder()
          .setParent(projectLocation.toString())
          .setModel(myModel)
          .build();

  // Create a model with the model metadata in the region.
  OperationFuture<Model, OperationMetadata> response =
      client.createModelAsync(createModelRequestrequest);

  System.out.println(
      String.format("Training operation name: %s", response.getInitialFuture().get().getName()));
  System.out.println("Training started...");
}

Node.js

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

/**
 * Demonstrates using the AutoML client to create a model.
 * 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 datasetId = '[DATASET_ID]' e.g., "TBL2246891593778855936";
// const tableId = '[TABLE_ID]' e.g., "1991013247762825216";
// const columnId = '[COLUMN_ID]' e.g., "773141392279994368";
// const modelName = '[MODEL_NAME]' e.g., "testModel";
// const trainBudget = '[TRAIN_BUDGET]' e.g., "1000",
// `Train budget in milli node hours`;

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

// Get the full path of the column.
const columnSpecId = client.columnSpecPath(
  projectId,
  computeRegion,
  datasetId,
  tableId,
  columnId
);

// Set target column to train the model.
const targetColumnSpec = {name: columnSpecId};

// Set tables model metadata.
const tablesModelMetadata = {
  targetColumnSpec: targetColumnSpec,
  trainBudgetMilliNodeHours: trainBudget,
};

// Set datasetId, model name and model metadata for the dataset.
const myModel = {
  datasetId: datasetId,
  displayName: modelName,
  tablesModelMetadata: tablesModelMetadata,
};

// Create a model with the model metadata in the region.
client
  .createModel({parent: projectLocation, model: myModel})
  .then(responses => {
    const initialApiResponse = responses[1];
    console.log(`Training operation name: ${initialApiResponse.name}`);
    console.log(`Training started...`);
  })
  .catch(err => {
    console.error(err);
  });

Python

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# dataset_display_name = 'DATASET_DISPLAY_NAME_HERE'
# model_display_name = 'MODEL_DISPLAY_NAME_HERE'
# train_budget_milli_node_hours = 'TRAIN_BUDGET_MILLI_NODE_HOURS_HERE'
# include_column_spec_names = 'INCLUDE_COLUMN_SPEC_NAMES_HERE'
#    or None if unspecified
# exclude_column_spec_names = 'EXCLUDE_COLUMN_SPEC_NAMES_HERE'
#    or None if unspecified

from google.cloud import automl_v1beta1 as automl

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

# Create a model with the model metadata in the region.
response = client.create_model(
    model_display_name,
    train_budget_milli_node_hours=train_budget_milli_node_hours,
    dataset_display_name=dataset_display_name,
    include_column_spec_names=include_column_spec_names,
    exclude_column_spec_names=exclude_column_spec_names,
)

print("Training model...")
print("Training operation name: {}".format(response.operation.name))
print("Training completed: {}".format(response.result()))

About model optimization objectives

The optimization objective impacts how your model is trained, and therefore how it performs in production. The table below provides some details about what kinds of problems each objective is best for:

Optimization objective Problem type API value Use this objective if you want to...
AUC ROC Classification MAXIMIZE_AU_ROC Distinguish between classes. Default value for binary classification.
Log loss Classification MINIMIZE_LOG_LOSS Keep prediction probabilities as accurate as possible. Default value for multi-class classification.
AUC PR Classification MAXIMIZE_AU_PRC Optimize results for predictions for the less common class.
RMSE Regression MINIMIZE_RMSE Capture more extreme values accurately.
MAE Regression MINIMIZE_MAE View extreme values as outliers with less impact on model.
RMSLE Regression MINIMIZE_RMSLE Penalize error on relative size rather than absolute value. Especially helpful when both predicted and actual values can be quite large.

Deploying a model

After you train your model, you must deploy it before you can request online predictions using that model. Batch predictions can be requested from a model that is not deployed.

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

Console

  1. Go to the AutoML Tables page in the Google Cloud Platform Console.

    Go to the AutoML Tables page

  2. Select the Models tab in the left navigation pane.

  3. In the More actions menu for the model you want to deploy, click Deploy model.

    More actions menu for deployment

curl command

You deploy a model by using the models.deploy method.

Replace model-id with the ID of the model.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/model-id:deploy

Java

/**
 * Demonstrates using the AutoML client to deploy model.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param modelId the Id of the model.
 * @throws Exception
 */
public static void deployModel(String projectId, String computeRegion, String modelId)
    throws Exception {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // Get the full path of the model.
  ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId);

  // Build deploy model request.
  DeployModelRequest deployModelRequest =
      DeployModelRequest.newBuilder().setName(modelFullId.toString()).build();

  // Deploy a model with the deploy model request.
  OperationFuture<Empty, OperationMetadata> response = client.deployModelAsync(deployModelRequest);

  // Display the deployment details of model.
  System.out.println(String.format("Deployment Details:"));
  System.out.println(String.format("\tName: %s", response.getName()));
  System.out.println(String.format("\tMetadata:"));
  System.out.println(response.getMetadata());
}

Node.js

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

/**
 * Demonstrates using the AutoML client to deploy model.
 * 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 modelId = '[MODEL_ID]' e.g., "TBL4704590352927948800";

// Get the full path of the model.
const modelFullId = client.modelPath(projectId, computeRegion, modelId);

// Deploy a model with the deploy model request.
client
  .deployModel({name: modelFullId})
  .then(responses => {
    const response = responses[0];
    console.log(`Deployment Details:`);
    console.log(`\tName: ${response.name}`);
    console.log(`\tMetadata:`);
    console.log(`\t\tType Url: ${response.metadata.typeUrl}`);
    console.log(`\tDone: ${response.done}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

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

from google.cloud import automl_v1beta1 as automl

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

# Deploy model
response = client.deploy_model(model_display_name=model_display_name)

# synchronous check of operation status.
print("Model deployed. {}".format(response.result()))

Undeploying a model

Console

  1. Go to the AutoML Tables page in the Google Cloud Platform Console.

    Go to the AutoML Tables page

  2. Select the Models tab in the left navigation pane.

  3. In the More actions menu for the model you want to undeploy, click Remove deployment.

    More actions menu with Remove deployment

curl command

You use the models.undeploy method to undeploy a model.

Replace model-id with the ID of the model.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/model-id:undeploy

Java

/**
 * Demonstrates using the AutoML client to undelpoy model.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param modelId the Id of the model.
 * @throws Exception
 */
public static void undeployModel(String projectId, String computeRegion, String modelId)
    throws Exception {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // Get the full path of the model.
  ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId);

  // Build undeploy model request.
  UndeployModelRequest undeployModelRequest =
      UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();

  // Undeploy a model with the undeploy model request.
  OperationFuture<Empty, OperationMetadata> response = client.undeployModelAsync(undeployModelRequest);

  // Display the undeployment details of model.
  System.out.println(String.format("Undeployment Details:"));
  System.out.println(String.format("\tName: %s", response.getName()));
  System.out.println(String.format("\tMetadata:"));
  System.out.println(response.getMetadata());
}

Node.js

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

/**
 * Demonstrates using the AutoML client to undelpoy model.
 * 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 modelId = '[MODEL_ID]' e.g., "TBL4704590352927948800";

// Get the full path of the model.
const modelFullId = client.modelPath(projectId, computeRegion, modelId);

// Undeploy a model with the undeploy model request.
client
  .undeployModel({name: modelFullId})
  .then(responses => {
    const response = responses[0];
    console.log(`Undeployment Details:`);
    console.log(`\tName: ${response.name}`);
    console.log(`\tMetadata:`);
    console.log(`\t\tType Url: ${response.metadata.typeUrl}`);
    console.log(`\tDone: ${response.done}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

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

from google.cloud import automl_v1beta1 as automl

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

# Undeploy model
response = client.undeploy_model(model_display_name=model_display_name)

# synchronous check of operation status.
print("Model undeployed. {}".format(response.result()))

Getting information about a model

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

Console

  1. Go to the AutoML Tables page in the Google Cloud Platform Console.

    Go to the AutoML Tables page

  2. Select the Models tab in the left navigation pane, and select the model you want to see information about.

  3. Select the Train tab.

    You can see high-level metrics for the model, such as precision and recall.

    High-level metrics for a trained model

    For help with evaluating the quality of your model, see Evaluating models.

curl command

Replace model-id with the ID of your model.
curl -X GET \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/model-id

You should see output similar to the following:

{
  "name": "projects/4321/locations/us-central1/models/TBL543",
  "displayName": "Sample_Model",
  "datasetId": "TBL234",
  "createTime": "2018-12-12T02:13:50.389130Z",
  "updateTime": "2018-12-12T02:13:50.389130Z",
  "tablesModelMetadata": {
    "targetColumnSpec": {
      "name": "projects/4321/locations/us-central1/datasets/TBL234/tableSpecs/567/columnSpecs/890",
      "dataType": {
        "typeCode": "CATEGORY"
      },
      "displayName": "Deposit"
    },
    "inputFeatureColumnSpecs": [
      {
        "name": "projects/4321/locations/us-central1/datasets/TBL234/tableSpecs/567/columnSpecs/567",
        "dataType": {
          "typeCode": "FLOAT64"
        },
        "displayName": "Age"
      },
      ...
      {
        "name": "projects/4321/locations/us-central1/datasets/TBL234/tableSpecs/567/columnSpecs/654",
        "dataType": {
          "typeCode": "FLOAT64"
        },
        "displayName": "Previous"
      },
      {
        "name": "projects/4321/locations/us-central1/datasets/TBL234/tableSpecs/567/columnSpecs/531",
        "dataType": {
          "typeCode": "CATEGORY"
        },
        "displayName": "Outcome"
      }
    ]
  }
}

Java

/**
 * Demonstrates using the AutoML client to get model details.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param modelId the Id of the model.
 * @throws IOException
 */
public static void getModel(String projectId, String computeRegion, String modelId)
    throws IOException {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // Get the full path of the model.
  ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId);

  // Get complete detail of the model.
  Model model = client.getModel(modelFullId);

  // Display the model information.
  System.out.println(String.format("Model name: %s", model.getName()));
  System.out.println(
      String.format(
          "Model Id: %s", model.getName().split("/")[model.getName().split("/").length - 1]));
  System.out.println(String.format("Model display name: %s", model.getDisplayName()));
  System.out.println(String.format("Dataset Id: %s", model.getDatasetId()));
  System.out.println("Tables Model Metadata: ");
  System.out.println(
      String.format(
          "\tTraining budget: %s",
          model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()));
  System.out.println(
      String.format(
          "\tTraining cost: %s", model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()));

  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  String createTime =
      dateFormat.format(new java.util.Date(model.getCreateTime().getSeconds() * 1000));
  System.out.println(String.format("Model create time: %s", createTime));

  System.out.println(String.format("Model deployment state: %s", model.getDeploymentState()));
}

Node.js

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

/**
 * Demonstrates using the AutoML client to get model details.
 * 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 modelId = '[MODEL_ID]' e.g., "TBL4704590352927948800";

// Get the full path of the model.
const modelFullId = client.modelPath(projectId, computeRegion, modelId);

// Get complete detail of the model.
client
  .getModel({name: modelFullId})
  .then(responses => {
    const model = responses[0];

    // Display the model information.
    console.log(`Model name: ${model.name}`);
    console.log(`Model Id: ${model.name.split(`/`).pop(-1)}`);
    console.log(`Model display name: ${model.displayName}`);
    console.log(`Dataset Id: ${model.datasetId}`);
    console.log(`Tables model metadata: `);
    console.log(
      `\tTraining budget: ${model.tablesModelMetadata.trainBudgetMilliNodeHours}`
    );
    console.log(
      `\tTraining cost: ${model.tablesModelMetadata.trainCostMilliNodeHours}`
    );
    console.log(`Model deployment state: ${model.deploymentState}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

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

from google.cloud import automl_v1beta1 as automl
from google.cloud.automl_v1beta1 import enums

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

# Get complete detail of the model.
model = client.get_model(model_display_name=model_display_name)

# Retrieve deployment state.
if model.deployment_state == 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 metadata:")
print(model.tables_model_metadata)
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))

Listing models

A project can include numerous models trained from the same or different datasets.

Console

To see a list of the available models using the Google Cloud Platform Console, click the Models tab in the left navigation bar.

curl command

curl -X GET \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models

You should see output similar to the following:

{
  "model": [
    {
      "name": "projects/4321/locations/us-central1/models/TBL893",
      "displayName": "Sample_Model",
      "datasetId": "TBL756",
      "createTime": "2018-12-12T02:13:50.389130Z",
      "updateTime": "2018-12-12T02:13:50.389130Z",
      "tablesModelMetadata": {
        "targetColumnSpec": {
          "name": "projects/4321/locations/us-central1/datasets/TBL756/tableSpecs/147/columnSpecs/352",
          "dataType": {
            "typeCode": "CATEGORY"
          },
          "displayName": "Deposit"
        },
        "inputFeatureColumnSpecs": [
          {
            "name": "projects/4321/locations/us-central1/datasets/TBL756/tableSpecs/147/columnSpecs/647",
            "dataType": {
              "typeCode": "FLOAT64"
            },
            "displayName": "Age"
          },
          ...
          {
            "name": "projects/4321/locations/us-central1/datasets/TBL756/tableSpecs/147/columnSpecs/409",
            "dataType": {
              "typeCode": "FLOAT64"
            },
            "displayName": "Previous"
          },
          {
            "name": "projects/4321/locations/us-central1/datasets/TBL756/tableSpecs/147/columnSpecs/871",
            "dataType": {
              "typeCode": "CATEGORY"
            },
            "displayName": "Outcome"
          }
        ]
      }
    }
  ]
}

Java

/**
 * Demonstrates using the AutoML client to list all models.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param filter the filter expression.
 * @throws IOException
 */
public static void listModels(String projectId, String computeRegion, String filter)
    throws IOException {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // A resource that represents Google Cloud Platform location.
  LocationName projectLocation = LocationName.of(projectId, computeRegion);

  // Create list models request.
  ListModelsRequest listModelsRequest =
      ListModelsRequest.newBuilder()
          .setParent(projectLocation.toString())
          .setFilter(filter)
          .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.println(String.format("\nModel name: %s", model.getName()));
    System.out.println(
        String.format(
            "Model Id: %s", model.getName().split("/")[model.getName().split("/").length - 1]));
    System.out.println(String.format("Model display name: %s", model.getDisplayName()));
    System.out.println(String.format("Dataset Id: %s", model.getDatasetId()));
    System.out.println("Tables Model Metadata: ");
    System.out.println(
        String.format(
            "\tTraining budget: %s",
            model.getTablesModelMetadata().getTrainBudgetMilliNodeHours()));
    System.out.println(
        String.format(
            "\tTraining cost: %s", model.getTablesModelMetadata().getTrainCostMilliNodeHours()));

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    String createTime =
        dateFormat.format(new java.util.Date(model.getCreateTime().getSeconds() * 1000));
    System.out.println(String.format("Model create time: %s", createTime));

    System.out.println(String.format("Model deployment state: %s", model.getDeploymentState()));
  }
}

Node.js

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

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

# 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
from google.cloud.automl_v1beta1 import enums

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

Deleting a model

The following example deletes a model.

Console

  1. In the AutoML Tables UI, click the Models tab 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.

curl command

Replace model-id with the ID of your model.

curl -X DELETE \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/model-id

You should see output similar to the following. You can use the operation ID to get the status of the delete operation. For an example, see Getting the Status of an Operation.

{
  "name": "projects/4321/locations/us-central1/operations/TBL442",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "progressPercentage": 100,
    "createTime": "2018-04-27T02:33:02.479200Z",
    "updateTime": "2018-04-27T02:35:17.309060Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

Java

/**
 * Demonstrates using the AutoML client to delete a model.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name. (e.g., "us-central1")
 * @param modelId the Id of the model.
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public static void deleteModel(String projectId, String computeRegion, String modelId)
    throws IOException, InterruptedException, ExecutionException {
  // Instantiates a client.
  AutoMlClient client = AutoMlClient.create();

  // Get the full path of the model.
  ModelName modelFullId = ModelName.of(projectId, computeRegion, 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

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

/**
 * Demonstrates using the AutoML client to delete a model.
 * 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 modelId = '[MODEL_ID]' e.g., "TBL4704590352927948800";

// Get the full path of the model.
const modelFullId = client.modelPath(projectId, computeRegion, modelId);

// Delete a model.
client
  .deleteModel({name: modelFullId})
  .then(responses => {
    const operation = responses[0];
    return operation.promise();
  })
  .then(responses => {
    // The final result of the operation.
    const operationDetails = responses[2];

    // Get the Model delete details.
    console.log('Model delete details:');
    console.log(`\tOperation details:`);
    console.log(`\t\tName: ${operationDetails.name}`);
    console.log(`\tDone: ${operationDetails.done}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

The client library for AutoML Tables includes additional Python methods that simplify using the AutoML Tables API. These methods refer to datasets and models by name instead of id. Your dataset and model names must be unique. For more information, see the Client reference.

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

from google.cloud import automl_v1beta1 as automl

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

# Undeploy model
response = client.delete_model(model_display_name=model_display_name)

# synchronous check of operation status.
print("Model deleted. {}".format(response.result()))

What's next

هل كانت هذه الصفحة مفيدة؟ يرجى تقييم أدائنا:

إرسال تعليقات حول...

AutoML Tables Documentation