从文本分类模型获取预测结果

本页面介绍如何使用 Google Cloud 控制台或 Vertex AI API 从文本分类模型获取在线(实时)预测和批量预测结果。

在线预测与批量预测之间的区别

在线预测是向模型端点发出的同步请求。如果您要发出请求以响应应用输入,或者在其他需要及时推断的情况下,可以使用在线预测。

批量预测是异步请求。您可以直接从模型资源请求批量预测,而无需将模型部署到端点。对于文本数据,如果您不需要获得即时响应并且希望通过一个请求处理累积数据,则可以使用批量预测。

获取在线预测结果

将模型部署到端点

您必须先将模型部署到端点,然后才能使用该模型执行在线预测。部署模型会将物理资源与模型相关联,以便以低延迟方式执行在线预测。

您可以将多个模型部署到一个端点,也可以将一个模型部署到多个端点。如需详细了解部署模型的方法和使用场景,请参阅部署模型简介

请使用以下方法之一部署模型:

Google Cloud 控制台

  1. 在 Google Cloud 控制台的 Vertex AI 部分中,转到模型页面。

    转到“模型”页面

  2. 点击要部署的模型名称以打开其详情页面。

  3. 选择部署和测试标签页。

    如果模型已部署到任何端点,部署模型 (Deploy your model) 部分中会列出这些端点。

  4. 点击部署到端点

  5. 如需将模型部署到新的端点,请选择创建新端点并为新端点提供名称。如需将模型部署到现有端点,请选择 添加到现有端点,然后从下拉列表中选择端点。

    您可以将多个模型添加到一个端点,也可以将一个模型添加到多个端点。了解详情

  6. 如果您将模型部署到已部署有一个或多个模型的现有端点,则必须为要部署的模型和已部署模型更新流量拆分,以使所有百分比的总和为 100%。

  7. 选择 AutoML 文本,然后按如下方式进行配置:

    1. 如果您要将模型部署到新端点,请接受 100 的流量拆分值。否则,请为端点上所有模型调整流量拆分值,使它们的总和为 100。

    2. 为模型点击完成,当所有流量分配百分比均正确无误时,点击继续

      随即将显示在其中部署模型的区域。此区域必须是您在其中创建模型的区域。

    3. 点击部署,将模型部署到端点。

API

使用 Vertex AI API 部署模型时,请完成以下步骤:

  1. 根据需要创建端点。
  2. 获取端点 ID。
  3. 将模型部署到端点。

创建端点

如果要将模型部署到现有端点,您可以跳过此步骤。

gcloud

以下示例使用 gcloud ai endpoints create 命令

gcloud ai endpoints create \
  --region=LOCATION \
  --display-name=ENDPOINT_NAME

请替换以下内容:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • ENDPOINT_NAME:端点的显示名称。

Google Cloud CLI 工具可能需要几秒钟才能创建端点。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION_ID:您的区域。
  • PROJECT_ID:您的项目 ID。
  • ENDPOINT_NAME:端点的显示名称。

HTTP 方法和网址:

POST http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints

请求 JSON 正文:

{
  "display_name": "ENDPOINT_NAME"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateEndpointOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-11-05T17:45:42.812656Z",
      "updateTime": "2020-11-05T17:45:42.812656Z"
    }
  }
}
您可以轮询操作状态,直到响应包含 "done": true

Java

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。如需了解详情,请参阅 Vertex AI Java API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateEndpointOperationMetadata;
import com.google.cloud.aiplatform.v1.Endpoint;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateEndpointSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String endpointDisplayName = "YOUR_ENDPOINT_DISPLAY_NAME";
    createEndpointSample(project, endpointDisplayName);
  }

  static void createEndpointSample(String project, String endpointDisplayName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (EndpointServiceClient endpointServiceClient =
        EndpointServiceClient.create(endpointServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      Endpoint endpoint = Endpoint.newBuilder().setDisplayName(endpointDisplayName).build();

      OperationFuture<Endpoint, CreateEndpointOperationMetadata> endpointFuture =
          endpointServiceClient.createEndpointAsync(locationName, endpoint);
      System.out.format("Operation name: %s\n", endpointFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Endpoint endpointResponse = endpointFuture.get(300, TimeUnit.SECONDS);

      System.out.println("Create Endpoint Response");
      System.out.format("Name: %s\n", endpointResponse.getName());
      System.out.format("Display Name: %s\n", endpointResponse.getDisplayName());
      System.out.format("Description: %s\n", endpointResponse.getDescription());
      System.out.format("Labels: %s\n", endpointResponse.getLabelsMap());
      System.out.format("Create Time: %s\n", endpointResponse.getCreateTime());
      System.out.format("Update Time: %s\n", endpointResponse.getUpdateTime());
    }
  }
}

Node.js

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Node.js 设置说明执行操作。如需了解详情,请参阅 Vertex AI Node.js API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const endpointDisplayName = 'YOUR_ENDPOINT_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Endpoint Service Client library
const {EndpointServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const endpointServiceClient = new EndpointServiceClient(clientOptions);

async function createEndpoint() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const endpoint = {
    displayName: endpointDisplayName,
  };
  const request = {
    parent,
    endpoint,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] = await endpointServiceClient.createEndpoint(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log('Create endpoint response');
  console.log(`\tName : ${result.name}`);
  console.log(`\tDisplay name : ${result.displayName}`);
  console.log(`\tDescription : ${result.description}`);
  console.log(`\tLabels : ${JSON.stringify(result.labels)}`);
  console.log(`\tCreate time : ${JSON.stringify(result.createTime)}`);
  console.log(`\tUpdate time : ${JSON.stringify(result.updateTime)}`);
}
createEndpoint();

Python 版 Vertex AI SDK

如需了解如何安装 Python 版 Vertex AI SDK,请参阅安装 Python 版 Vertex AI SDK。如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档

def create_endpoint_sample(
    project: str,
    display_name: str,
    location: str,
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint.create(
        display_name=display_name,
        project=project,
        location=location,
    )

    print(endpoint.display_name)
    print(endpoint.resource_name)
    return endpoint

检索端点 ID

您需要端点 ID 才能部署模型。

gcloud

以下示例使用 gcloud ai endpoints list 命令

gcloud ai endpoints list \
  --region=LOCATION \
  --filter=display_name=ENDPOINT_NAME

请替换以下内容:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • ENDPOINT_NAME:端点的显示名称。

请注意 ENDPOINT_ID 列中显示的数字。请在以下步骤中使用此 ID。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • PROJECT_ID:您的项目 ID。
  • ENDPOINT_NAME:端点的显示名称。

HTTP 方法和网址:

GET http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints?filter=display_name=ENDPOINT_NAME

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "endpoints": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID",
      "displayName": "ENDPOINT_NAME",
      "etag": "AMEw9yPz5pf4PwBHbRWOGh0PcAxUdjbdX2Jm3QO_amguy3DbZGP5Oi_YUKRywIE-BtLx",
      "createTime": "2020-04-17T18:31:11.585169Z",
      "updateTime": "2020-04-17T18:35:08.568959Z"
    }
  ]
}
请记下 ENDPOINT_ID

部署模型

在下面选择您的语言或环境对应的标签页:

gcloud

以下示例使用 gcloud ai endpoints deploy-model 命令

以下示例将 Model 部署到 Endpoint,但没有在多个 DeployedModel 资源之间拆分流量:

在使用下面的命令数据之前,请先进行以下替换:

  • ENDPOINT_ID:端点的 ID。
  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • MODEL_ID:要部署的模型的 ID。
  • DEPLOYED_MODEL_NAMEDeployedModel 的名称。您还可以将 Model 的显示名用于 DeployedModel
  • MIN_REPLICA_COUNT:此部署的最小节点数。 节点数可根据预测负载的需要而增加或减少,直至达到节点数上限并且绝不会少于此节点数。
  • MAX_REPLICA_COUNT:此部署的节点数上限。 节点数可根据预测负载的需要而增加或减少,直至达到此节点数并且绝不会少于节点数下限。如果您省略 --max-replica-count 标志,则节点数上限将设置为 --min-replica-count 的值。

执行 gcloud ai endpoints deploy-model 命令:

Linux、macOS 或 Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --traffic-split=0=100

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --traffic-split=0=100

Windows (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --traffic-split=0=100
 

拆分流量

上述示例中的 --traffic-split=0=100 标志会将 Endpoint 接收的 100% 预测流量发送到新 DeployedModel(使用临时 ID 0 表示)。如果您的 Endpoint 已有其他 DeployedModel 资源,那么您可以在新 DeployedModel 和旧资源之间拆分流量。例如,如需将 20% 的流量发送到新 DeployedModel,将 80% 发送到旧版本,请运行以下命令。

在使用下面的命令数据之前,请先进行以下替换:

  • OLD_DEPLOYED_MODEL_ID:现有 DeployedModel 的 ID。

执行 gcloud ai endpoints deploy-model 命令:

Linux、macOS 或 Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (cmd.exe)