Managing models

You create a custom model by training it using a prepared dataset. AutoML Natural Language Sentiment Analysis 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 Sentiment Analysis 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 Sentiment Analysis UI and select the Launch app link in the AutoML Sentiment Analysis 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 sentiment values.

    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 Sentiment Analysis 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.

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",
    "textSentimentModelMetadata": {
    }
  }'

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/1979469554520652445",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2018-04-27T01:28:41.338120Z",
    "updateTime": "2018-04-27T01:28:41.338120Z",
    "cancellable": true
  }
}

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.

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 modelName the name of the model.
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public static void createModel(
    String projectId, String computeRegion, String datasetId, String modelName)
    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);

  // Set model meta data
  TextSentimentModelMetadata textSentimentModelMetadata =
      TextSentimentModelMetadata.newBuilder().build();

  // Set model name, dataset Id and model metadata.
  Model myModel =
      Model.newBuilder()
          .setDisplayName(modelName)
          .setDatasetId(datasetId)
          .setTextSentimentModelMetadata(textSentimentModelMetadata)
          .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., "TST8051890775971069952";
// const modelName = '[MODEL_NAME]' e.g., "myModel";

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

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

// 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_sentiment_model_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...")

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 an import operation:

{
  "name": "projects/000000000000/locations/us-central1/operations/2116326435840390257",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "progressPercentage": 100,
    "partialFailures": [
      {
        "code": 7,
        "message": "Duplicated files detected gs://my-project-lcm/training-data/train.jsonl
        and gs://my-project-lcm/training-data/test.jsonl have the same content"
      },
    ],
    "createTime": "2018-04-27T01:39:59.821460Z",
    "updateTime": "2018-04-27T01:43:09.564770Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

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",
    "textSentimentModelMetadata": {
     },
    "displayName": "a_98487760535e48319dd204e6394670"
  }
}

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

Java

/**
 * Demonstrates using the AutoML client to get operation status.
 *
 * @param operationFullId the complete name of a operation. For example, the name of your
 *     operation is projects/[projectId]/locations/us-central1/operations/[operationId].
 * @throws IOException
 */
public static void getOperationStatus(String operationFullId) throws IOException {
  // Instantiates a client
  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/<projectId>/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 0peration

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"

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",
      "textSentimentModelMetadata": {
       },
      "displayName": "test_model"
    },
}

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(
      String.format("TextSentimentModelMetadata: %s", model.getTextSentimentModelMetadata()));
  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., "TST5200971474357190656";

// 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 === `textSentimentModelMetadata`) {
      console.log(
        `TextSentimentModelMetadata: ${util.inspect(
          model.textSentimentModelMetadata,
          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 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("%Y-%m-%dT%H:%M:%SZ")))
    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 Sentiment Analysis 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",
      "textSentimentModelMetadata": {
      },
      "createTime": "2018-04-30T23:06:19.223230Z"
    },
    {
      "name": "projects/000000000000/locations/us-central1/models/6877109870585533885",
      "displayName": "test_201801111318",
      "textSentimentModelMetadata": {
      },
      "createTime": "2018-01-11T21:25:05.893590Z"
    }
  ]
}

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(
        String.format("TextSentimentModelMetadata: %s", model.getTextSentimentModelMetadata()));
    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., "textSentimentModelMetadata:*";

// 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 === `textSentimentModelMetadata`) {
        console.log(
          `TextSentimentModelMetadata: ${util.inspect(
            model[i].textSentimentModelMetadata,
            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 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("%Y-%m-%dT%H:%M:%SZ")))
        print("Model deployment state: {}".format(deployment_state))

Deploying or undeploying a model

AutoML Natural Language Sentiment Analysis automatically deploys a model when it has been trained. The following example shows how to undeploy a model or explicitly deploy a previously undeployed model.

Undeploy a model

Web UI

  1. Open the AutoML Natural Language Sentiment Analysis UI and select the Launch app link in the AutoML Sentiment Analysis 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/model-name: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().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., "TST5200971474357190656";

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

Deploy a model

Web UI

  1. Open the AutoML Natural Language Sentiment Analysis UI and select the Launch app link in the AutoML Sentiment Analysis box.

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

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

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

  4. Click Confirm in the confirmation dialog box.

Deploying a model can take some time. 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

  • 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/model-name: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., "TST5200971474357190656";

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

Deleting a model

The following example deletes a model.

Web UI

  1. In the AutoML Natural Language Sentiment Analysis 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

/**
 * 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 Exception
 */
public static void deleteModel(String projectId, String computeRegion, String modelId)
    throws InterruptedException, ExecutionException, IOException {
  // 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., "TST5200971474357190656";

// 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(`\t\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()))

Was this page helpful? Let us know how we did:

Send feedback about...

AutoML Natural Language Sentiment Analysis