Managing models

You create a custom model by training it using a prepared dataset. AutoML Natural Language Entity Extraction 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 Entity Extraction 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.

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

Training models

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

Web UI

  1. Open the AutoML Natural Language Entity Extraction UI and select the Get started link in the AutoML Entity Extraction box.

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

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

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

    Text items page

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

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

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

  5. Enter a name for the model.

    The model name can be up to 32 characters and contain only letters, numbers and underscores. The first character must be a letter.

  6. Specify whether to deploy the trained model.

    A model must be deployed before you can use it. Click the 'Deploy model after training finishes' check box to deploy your model automatically when training is complete. If you don't select the check box, you'll need to deploy the model manually before using it.

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

Command-line

In the command below, replace project-id and dataset-id with your IDs.

curl \
  -X POST \
  -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 \
  -d '{
    "displayName": "test_model",
    "datasetId": "dataset-id",
    "textExtractionModelMetadata": {
    },
  }'

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 Getting the status of an operation.

{
  "name": "projects/000000000000/locations/us-central1/operations/TEN4403957485614923776",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2018-10-26T17:53:02.784760Z",
    "updateTime": "2018-10-26T17:53:02.784760Z",
    "createModelDetails": {}
  }
}

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.Model;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.TextExtractionModelMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class CreateModel {

  // Create a model
  static void createModel(
      String projectId, String computeRegion, String datasetId, String modelName)
      throws IOException, InterruptedException, ExecutionException {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String datasetId = "YOUR_DATASET_ID";
    // String modelName = "YOUR_MODEL_NAME";

    // Instantiates a client
    try (AutoMlClient client = AutoMlClient.create()) {

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

      // Set model meta data
      TextExtractionModelMetadata textExtractionModelMetadata =
          TextExtractionModelMetadata.newBuilder().build();

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

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

      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., "TEN8051890775971069952";
// const modelName = '[MODEL_NAME]' e.g., "myModel";

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

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

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

    # TODO(developer): Uncomment and set the following variables
    # project_id = '[PROJECT_ID]'
    # compute_region = '[COMPUTE_REGION]'
    # dataset_id = '[DATASET_ID]'
    # model_name = '[MODEL_NAME]'

    from google.cloud import automl_v1beta1 as automl

    client = automl.AutoMlClient()

    # A resource that represents Google Cloud Platform location.
    project_location = client.location_path(project_id, compute_region)

    # Set model name and model metadata for the dataset.
    my_model = {
        "display_name": model_name,
        "dataset_id": dataset_id,
        "text_extraction_dataset_metadata": {}
    }

    # Create a model with the model metadata in the region.
    response = client.create_model(project_location, my_model)
    print("Training operation name: {}".format(response.operation.name))
    print("Training started...")

Training a model can take several hours to complete. Note the name and ID if the new model, which you will need for other operations such as evaluating the model and using it for predictions. The model name has the format projects/{project-id}/locations/us-central1/models/{model-id}; the model ID is the element that appears after models/ in the "name" value of the response.

Getting the status of an operation

You can check the status of a long-running task (importing items into a dataset or training a model) using the operation ID from the response when you started the task.

Command-line

In the command below, replace operation-name with the full name of your operation. The full name has the format projects/{project-id}/locations/us-central1/operations/{operation-id}.

curl \
  -X GET \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  https://automl.googleapis.com/v1beta1/operation-name

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

{
  "name": "projects/000000000000/locations/us-central1/operations/2126599795587061786",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2018-04-27T01:56:28.395640Z",
    "updateTime": "2018-04-27T02:04:12.336070Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.Model",
    "name": "projects/000000000000/locations/us-central1/models/3745331181667467569",
    "createTime": "2018-04-27T02:00:22.329970Z",
    "textExtractionModelMetadata": {
     },
    "displayName": "a_98487760535e48319dd204e6394670"
  }
}

If the response does not include "done": true, it means that the operation is still in progress.

Java

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  // Get the status of a given operation
  static void getOperationStatus(String operationFullId) throws IOException {
    // String operationFullId = "COMPLETE_NAME_OF_OPERATION";
    // like: projects/[projectId]/locations/us-central1/operations/[operationId]

    // Instantiates a client
    try (AutoMlClient client = AutoMlClient.create()) {

      // Get the latest state of a long-running operation.
      Operation response = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println(String.format("Operation details:"));
      System.out.println(String.format("\tName: %s", response.getName()));
      System.out.println(String.format("\tMetadata:"));
      System.out.println(String.format("\t\tType Url: %s", response.getMetadata().getTypeUrl()));
      System.out.println(
          String.format(
              "\t\tValue: %s", response.getMetadata().getValue().toStringUtf8().replace("\n", "")));
      System.out.println(String.format("\tDone: %s", response.getDone()));
      if (response.hasResponse()) {
        System.out.println("\tResponse:");
        System.out.println(String.format("\t\tType Url: %s", response.getResponse().getTypeUrl()));
        System.out.println(
            String.format(
                "\t\tValue: %s",
                response.getResponse().getValue().toStringUtf8().replace("\n", "")));
      }
      if (response.hasError()) {
        System.out.println("\tResponse:");
        System.out.println(String.format("\t\tError code: %s", response.getError().getCode()));
        System.out
            .println(String.format("\t\tError message: %s", response.getError().getMessage()));
      }
    }
  }
}

Node.js

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

/**
 * Demonstrates using the AutoML client to get operation status.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const operationFullId = '[OPERATION_FULL_ID]'
// eg., "projects/<projectId>/locations/us-central1/operations/<operationId>",
// `Full name of an operation`;

// Get the latest state of a long-running operation.
client.operationsClient
  .getOperation({name: operationFullId})
  .then(responses => {
    const response = responses[0];
    console.log(`Operation details:`);
    console.log(`\tName: ${response.name}`);
    console.log(`\tMetadata:`);
    console.log(`\t\tType Url: ${response.metadata.typeUrl}`);
    console.log(`\tDone: ${response.done}`);

    if (response.response) {
      console.log(`\tResponse:`);
      console.log(`\t\tType Url: ${response.response.typeUrl}`);
    }

    if (response.error) {
      console.log(`\tResponse:`);
      console.log(`\t\tError code: ${response.error.code}`);
      console.log(`\t\tError message: ${response.error.message}`);
    }
  })
  .catch(err => {
    console.error(err);
  });

Python

    # TODO(developer): Uncomment and set the following variables
    # operation_full_id =
    #   'projects/[PROJECT_ID]/locations/[REGION]/operations/[operationId]'

    from google.cloud import automl_v1beta1 as automl

    client = automl.AutoMlClient()

    # Get the latest state of a long-running operation.
    response = client.transport._operations_client.get_operation(
        operation_full_id
    )

    print("Operation status: {}".format(response))

Cancelling an operation

You can cancel an import or training task using the operation ID. In the command below, replace operation-name with the full name of your operation. The full name has the format projects/{project-id}/locations/us-central1/operations/{operation-id}.

curl \
  -X POST "Content-Type: application/json" \
  -H "Authorization: Bearer `gcloud auth application-default print-access-token`" \
  https://automl.googleapis.com/v1beta1/operation-name:cancel"

Deploying and undeploying models

When training is complete you can deploy your model to get it ready for online serving. Deployment is necessary if you would like to extract entities using the predict method.

Deploy a model

Web UI

  1. Open the AutoML Natural Language Entity Extraction UI and select the Get started link in the AutoML Entity Extraction box.

    The Models page shows the available models for the current project.

  2. Select the model you would like to deploy.

  3. On the Test and use page, click Deploy model on the right side of the deployment control bar at the top of the page.

    Text items page

Deployment will take several minutes or more. After the model is successfully deployed, you will receive a message at the email address that you used to sign up for the program.

Command-line

In the command below, replace project-id and model-id with your IDs.

curl \
  -X POST \
  -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:deploy

You should see output similar to the following:

{
  "name": "projects/000000000000/locations/us-central1/operations/TEN8195786061721370624",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2019-03-13T15:37:49.972372Z",
    "updateTime": "2019-03-13T15:37:49.972372Z"
  }
}

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.DeployModelRequest;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.protobuf.Empty;

class DeployModel {

  // Deploy a model
  static void deployModel(String projectId, String computeRegion, String modelId) throws Exception {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String modelId = "MODEL_ID";

    // Instantiates a client.
    try (AutoMlClient client = AutoMlClient.create()) {

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

      // Build deploy model request.
      DeployModelRequest deployModelRequest =
          DeployModelRequest.newBuilder().setName(modelName.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(String.format("\t\tType Url: %s", 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., "TEN5200971474357190656";

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

Undeploy a model

Web UI

  1. Open the AutoML Natural Language Entity Extraction UI and select the Get started link in the AutoML Entity Extraction box.

  2. Select Models from the left navigation bar, then choose the model you want to undeploy.

    The last column on the model listing page indicates whether each model is Deployed.

  3. From the Test & Use page, click Remove Deployment from the note box that appears just below the model name.

  4. Click Remove Deployment again in the confirmation dialog box.

Command-line

  • Replace model-name with the full name of your model, from the response when you created the model. The full name has the format: projects/{project-id}/locations/us-central1/models/{model-id}
curl \
  -X POST \
  -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:undeploy

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.UndeployModelRequest;
import com.google.protobuf.Empty;

class UndeployModel {

  // Undeploy a given model
  static void undeployModel(String projectId, String computeRegion, String modelId)
      throws Exception {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String modelId = "YOUR_MODEL_ID";

    // Instantiates a client.
    try (AutoMlClient client = AutoMlClient.create()) {

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

      // Build undeploy model request.
      UndeployModelRequest undeployModelRequest =
          UndeployModelRequest.newBuilder().setName(modelName.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().get().toString());
    }
  }
}

Node.js

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

  /**
   * Demonstrates using the AutoML client to undeploy 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., "TEN5200971474357190656";

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

  // Deploy a model with the deploy 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);
    });
}
main(...process.argv.slice(2)).catch(console.error());

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.

Command-line

In the command below, replace project-id and model-id with your IDs.

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:

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

Java

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.Model;
import com.google.cloud.automl.v1beta1.ModelName;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

class GetModel {

  // Get a given model
  static void getModel(String projectId, String computeRegion, String modelId) throws IOException {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String modelId = "YOUR_MODEL_ID";

    // Instantiates a client
    try (AutoMlClient client = AutoMlClient.create()) {

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

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

      // 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()));
      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 util = require(`util`);
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., "TEN5200971474357190656";

// 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}`);

    if (model.modelMetadata === `textExtractionModelMetadata`) {
      console.log(
        `TextExtractionModelMetadata: ${util.inspect(
          model.textExtractionModelMetadata,
          false,
          null
        )}`
      );
    }

    console.log(`Model deployment state: ${model.deploymentState}`);
  })
  .catch(err => {
    console.error(err);
  });

Python

    # TODO(developer): Uncomment and set the following variables
    # project_id = '[PROJECT_ID]'
    # compute_region = '[COMPUTE_REGION]'
    # model_id = '[MODEL_ID]'

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

    client = automl.AutoMlClient()

    # Get the full path of the model.
    model_full_id = client.model_path(project_id, compute_region, model_id)

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

    # Retrieve deployment state.
    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 create time: {}".format(datetime.fromtimestamp(model.create_time.seconds).strftime("%b %d %Y, %I:%M:%S %p")))
    print("Model deployment state: {}".format(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.

Web UI

To see a list of the available models using the AutoML Natural Language Entity Extraction 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.

Command-line

In the command below, replace project-id with the ID for your project.

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/000000000000/locations/us-central1/models/7537307368641647584",
      "displayName": "c982e11ffbd5455e8d9bee2734f01f81",
      "textExtractionModelMetadata": {
      },
      "createTime": "2018-04-30T23:06:19.223230Z"
    },
    {
      "name": "projects/000000000000/locations/us-central1/models/6877109870585533885",
      "displayName": "test_201801111318",
      "textExtractionModelMetadata": {
      },
      "createTime": "2018-01-11T21:25:05.893590Z"
    }
  ]
}

Java

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;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

class ListModels {

  // List all models for a given project based on the filter expression
  static void listModels(String projectId, String computeRegion, String filter) throws IOException {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String filter = "YOUR_FILTER_EXPRESSION";

    // Instantiates a client
    try (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(
            String
                .format("TextExtractionModelMetadata: %s", model.getTextExtractionModelMetadata()));
        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 util = require(`util`);
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., "textExtractionModelMetadata:*";

// 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}`);

      if (model[i].modelMetadata === `textExtractionModelMetadata`) {
        console.log(
          `TextExtractionModelMetadata: ${util.inspect(
            model[i].textExtractionModelMetadata,
            false,
            null
          )}`
        );
      }
      console.log(`Model deployment state: ${model[i].deploymentState}`);
    }
  })
  .catch(err => {
    console.error(err);
  });

Python

    # TODO(developer): Uncomment and set the following variables
    # project_id = '[PROJECT_ID]'
    # compute_region = '[COMPUTE_REGION]'
    # filter_ = '[DATASET_ID]'

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

    client = automl.AutoMlClient()

    # A resource that represents Google Cloud Platform location.
    project_location = client.location_path(project_id, compute_region)

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

    print("List of models:")
    for model in response:
        # Retrieve deployment state.
        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 create time: {}".format(datetime.fromtimestamp(model.create_time.seconds).strftime("%b %d %Y, %I:%M:%S %p")))
        print("Model deployment state: {}".format(deployment_state))

Deleting a model

The following example deletes a model.

Web UI

  1. In the AutoML Natural Language Entity Extraction 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.

Command-line

Replace model-name with the full name of your model, from the response when you created the model. The full name has the format: projects/{project-id}/locations/us-central1/models/{model-id}

curl \
  -X DELETE \
  -H "Authorization: Bearer $(gcloud auth application-default  \
print-access-token)" \
  -H "Content-Type: application/json" \
https://automl.googleapis.com/v1beta1/model-name

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/000000000000/locations/us-central1/operations/4422270194425422927",
  "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

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

class DeleteModel {

  // Delete a model
  static void deleteModel(String projectId, String computeRegion, String modelId)
      throws IOException, InterruptedException, ExecutionException {
    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // String modelId = "YOUR_MODEL_ID";

    // Instantiates a client
    try (AutoMlClient client = AutoMlClient.create()) {

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

      // Delete a model.
      OperationFuture<Empty, OperationMetadata> response = client.deleteModelAsync(modelName);

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

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., "TEN5200971474357190656";

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

    # TODO(developer): Uncomment and set the following variables
    # project_id = '[PROJECT_ID]'
    # compute_region = '[COMPUTE_REGION]'
    # model_id = '[MODEL_ID]'

    from google.cloud import automl_v1beta1 as automl

    client = automl.AutoMlClient()

    # Get the full path of the model.
    model_full_id = client.model_path(project_id, compute_region, model_id)

    # Delete a model.
    response = client.delete_model(model_full_id)

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

Var denne side nyttig? Giv os en anmeldelse af den:

Send feedback om...

AutoML Natural Language Entity Extraction