导出 AutoML 表格模型

本页面介绍如何使用 Gemini Enterprise Agent Platform 将 AutoML 表格模型导出到 Cloud Storage,将模型下载到本地服务器或由其他云服务提供商托管的服务器,然后使用 Docker 提供模型以执行预测。

如需了解如何导出图片和视频 Edge 模型,请参阅 导出 AutoML Edge 模型

导出表格模型后,如果要将其重新导入 Agent Platform,请参阅 将模型导入 Agent Platform

限制

导出 AutoML 表格模型存在以下限制:

  • 您只能导出 AutoML 表格分类和回归模型。不支持导出 AutoML 表格预测模型。

  • 使用导出的表格模型时无法使用 Vertex Explainable AI。如果您需要使用 Vertex Explainable AI,则必须使用 Agent Platform 托管的模型提供预测。

  • 导出的表格模型只能在支持 Advanced Vector Extensions (AVX) 指令集的 x86 架构 CPU 上运行。

导出过程

以下为模型导出步骤:

  1. 设置您的环境
  2. 导出模型
  3. 拉取并运行模型服务器
  4. 请求预测

准备工作

在完成此任务之前,您必须首先完成以下任务:

导出模型

控制台

  1. 在 Google Cloud 控制台的 Agent Platform 部分中,前往 模型 页面。

    转到“模型”页面

  2. 点击要导出的表格模型,以打开其详情页面。

  3. 点击按钮栏中的导出以导出模型。

  4. 在目标位置中选择或创建 Cloud Storage 文件夹。

    存储桶必须符合存储桶要求

    您无法将模型导出到顶级存储桶。您必须至少使用一级文件夹。

    为获得最佳效果,请新建一个空文件夹。您将在后续步骤中复制该文件夹的全部内容。

  5. 点击导出

    下一部分中,您需将已导出的模型下载到您的服务器。

REST

您可以使用 models.export 方法将模型导出到 Cloud Storage。

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

  • LOCATION:您的区域。
  • PROJECT: 您的 [项目 ID](/resource-manager/docs/creating-managing-projects#identifiers)。 。
  • MODEL_ID:要导出的模型的 ID。
  • GCS_DESTINATION:Cloud Storage 中的目标文件夹。例如 gs://export-bucket/exports

    您无法将模型导出到顶级存储桶。您必须至少使用一级文件夹。

    该文件夹必须符合存储桶要求

    为获得最佳效果,请新建一个文件夹。您将在后续步骤中复制该文件夹的全部内容。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export

请求 JSON 正文:

{
  "outputConfig": {
    "exportFormatId": "tf-saved-model",
    "artifactDestination": {
      "outputUriPrefix": "GCS_DESTINATION"
    }
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.ExportModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-12T20:53:40.130785Z",
      "updateTime": "2020-10-12T20:53:40.130785Z"
    },
    "outputInfo": {
      "artifactOutputUri": "gs://OUTPUT_BUCKET/model-MODEL_ID/EXPORT_FORMAT/YYYY-MM-DDThh:mm:ss.sssZ"
    }
  }
}

Java

试用此示例之前,请按照 Java 设置说明进行操作,具体请参阅 Agent Platform 快速入门:使用 客户端库

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.ExportModelOperationMetadata;
import com.google.cloud.aiplatform.v1.ExportModelRequest;
import com.google.cloud.aiplatform.v1.ExportModelResponse;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportModelTabularClassificationSample {
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String gcsDestinationOutputUriPrefix = "gs://your-gcs-bucket/destination_path";
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    exportModelTableClassification(gcsDestinationOutputUriPrefix, project, modelId);
  }

  static void exportModelTableClassification(
      String gcsDestinationOutputUriPrefix, String project, String modelId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.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 (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      ModelName modelName = ModelName.of(project, location, modelId);

      GcsDestination.Builder gcsDestination = GcsDestination.newBuilder();
      gcsDestination.setOutputUriPrefix(gcsDestinationOutputUriPrefix);
      ExportModelRequest.OutputConfig outputConfig =
          ExportModelRequest.OutputConfig.newBuilder()
              .setExportFormatId("tf-saved-model")
              .setArtifactDestination(gcsDestination)
              .build();

      OperationFuture<ExportModelResponse, ExportModelOperationMetadata> exportModelResponseFuture =
          modelServiceClient.exportModelAsync(modelName, outputConfig);
      System.out.format(
          "Operation name: %s\n", exportModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      ExportModelResponse exportModelResponse =
          exportModelResponseFuture.get(300, TimeUnit.SECONDS);
      System.out.format(
          "Export Model Tabular Classification Response: %s", exportModelResponse.toString());
    }
  }
}

Node.js

试用此示例之前,请按照 Node.js 设置说明进行操作,请参阅 Agent Platform 快速入门:使用客户端库

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

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

// const gcsDestinationOutputUriPrefix ='YOUR_GCS_DESTINATION_\
// OUTPUT_URI_PREFIX'; eg. "gs://<your-gcs-bucket>/destination_path"
// const modelId = 'YOUR_MODEL_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

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

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

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function exportModelTabularClassification() {
  // Configure the name resources
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  // Configure the outputConfig resources
  const outputConfig = {
    exportFormatId: 'tf-saved-model',
    artifactDestination: {
      outputUriPrefix: gcsDestinationOutputUriPrefix,
    },
  };
  const request = {
    name,
    outputConfig,
  };

  // Export Model request
  const [response] = await modelServiceClient.exportModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  console.log(`Export model response : ${JSON.stringify(response.result)}`);
}
exportModelTabularClassification();

Python

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

from google.cloud import aiplatform_v1beta1


def export_model_tabular_classification_sample(
    project: str,
    model_id: str,
    gcs_destination_output_uri_prefix: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform_v1beta1.ModelServiceClient(client_options=client_options)
    gcs_destination = {"output_uri_prefix": gcs_destination_output_uri_prefix}
    output_config = {
        "artifact_destination": gcs_destination,
        "export_format_id": "tf-saved-model",
    }
    name = client.model_path(project=project, location=location, model=model_id)
    response = client.export_model(name=name, output_config=output_config)
    print("Long running operation:", response.operation.name)
    print("output_info:", response.metadata.output_info)
    export_model_response = response.result(timeout=timeout)
    print("export_model_response:", export_model_response)

获取导出操作的状态

某些请求会启动需要一些时间才能完成的长时间运行的操作。这些请求会返回操作名称,您可以使用该名称查看操作状态或取消操作。Colab Enterprise 提供辅助方法来调用长时间运行的操作。如需了解详情,请参阅使用长时间运行 的操作

拉取并运行模型服务器

在此任务中,您将从 Cloud Storage 下载已导出的模型并启动 Docker 容器,以使您的模型可以接收预测请求。

如需拉取并运行模型服务器,请执行以下操作:

  1. 在要运行模型的计算机上,切换到要保存导出模型的目录。

  2. 下载导出的模型:

    gcloud storage cp <var>gcs-destination</var> . --recursive
    

    其中,gcs-destination 是 Cloud Storage 中导出模型的位置路径。

    模型会复制到您的当前目录,即位于以下路径下:

    ./model-<model-id>/tf-saved-model/<export-timestamp>

    路径可以包含 tf-saved-modelcustom-trained

  3. 重命名目录,以移除时间戳。

    mv model-<model-id>/tf-saved-model/<export-timestamp> model-<model-id>/tf-saved-model/<new-dir-name>
    

    此时间戳会导致该目录对 Docker 无效。

  4. 拉取模型服务器 Docker 映像。

    sudo docker pull MODEL_SERVER_IMAGE
    

    要拉取的模型服务器映像位于导出的模型目录的 environment.json 文件中。该文件应具有以下路径:

    ./model-<model-id>/tf-saved-model/<new-dir-name>/environment.json

  5. 使用您刚创建的目录名启动 Docker 容器:

    docker run -v `pwd`/model-<model-id>/tf-saved-model/<new-dir-name>:/models/default -p 8080:8080 -it MODEL_SERVER_IMAGE
    

您随时可以使用 Ctrl-C 停止模型服务器。

更新模型服务器 Docker 容器

因为您在导出模型时下载模型服务器 Docker 容器,所以必须明确更新模型服务器以获取更新和问题修复。您应该使用以下命令定期更新模型服务器:

docker pull MODEL_SERVER_IMAGE

确保 Docker 映像 URI 与您之前拉取的 Docker 映像的 URI 匹配。

从已导出的模型进行预测

Agent Platform 映像容器中的模型服务器处理预测请求并返回预测结果。

批量预测不适用于导出的模型。

预测数据的格式

您对预测请求提供的数据(payload 字段)应具有以下 JSON 格式:

{ "instances": [ { "column_name_1": value, "column_name_2": value, … } , … ] }

以下示例展示了一个包含三列的请求:分类列、数值数组和结构体。该请求包含两行。

{
  "instances": [
    {
      "categorical_col": "mouse",
      "num_array_col": [
        1,
        2,
        3
      ],
      "struct_col": {
        "foo": "piano",
        "bar": "2019-05-17T23:56:09.05Z"
      }
    },
    {
      "categorical_col": "dog",
      "num_array_col": [
        5,
        6,
        7
      ],
      "struct_col": {
        "foo": "guitar",
        "bar": "2019-06-17T23:56:09.05Z"
      }
    }
  ]
}

发出预测请求

  1. 将您的请求数据放入文本文件,例如 tmp/request.json

    预测请求中的数据行数(称为小批次大小)会影响预测延迟时间和吞吐量。小批次大小越大,延迟时间就越长且吞吐量就越高。要缩短延迟时间,请降低小批次大小。要提高吞吐量,请增加小批次大小。最常用的小批次大小是 1、32、64、128、256、512 和 1024。

  2. 请求预测:

    curl -X POST --data @/tmp/request.json http://localhost:8080/predict
    

预测结果的格式

结果的格式取决于模型目标。

分类模型结果

分类模型(二元和多类别)的预测结果会为目标列的每个可能值返回一个概率分数。您必须确定如何使用这些分数。 例如,要通过提供的分数获得二元分类,您需要确定阈值。假设有“A”和“B”这两类,如果“A”的得分大于所选阈值,则应将示例归为“A”类,否则应归为“B”类。对于不平衡数据集,阈值可能接近 100% 或 0%。

分类模型的结果负载类似于以下示例:

{
  "predictions": [
    {
      "scores": [
        0.539999994635582,
        0.2599999845027924,
        0.2000000208627896
      ],
      "classes": [
        "apple",
        "orange",
        "grape"
      ]
    },
    {
      "scores": [
        0.23999999463558197,
        0.35999998450279236,
        0.40000002086278963
      ],
      "classes": [
        "apple",
        "orange",
        "grape"
      ]
    }
  ]
}

回归模型结果

为预测请求的每个有效行返回预测值。对于导出的模型,不会返回预测间隔。

回归模型的结果负载类似于以下示例:

{
  "predictions": [
    {
      "value": -304.3663330078125,
      "lower_bound": -56.32196807861328,
      "upper_bound": 126.51904296875
    },
    {
      "value": -112.3663330078125,
      "lower_bound": 16.32196807861328,
      "upper_bound": 255.51904296875
    }
  ]
}

后续步骤