在线预测

本页面介绍如何利用 AutoML Tables 进行在线(单一、低延迟)预测。

简介

创建(训练)模型后,您可以部署该模型并请求在线(实时)预测。在线预测接受一行数据,并基于您的模型为该数据提供一个预测结果。如果需要预测结果作为业务逻辑流的输入,可以使用在线预测。

必须先部署您的模型,然后才能请求在线预测。部署的模型会产生费用。完成在线预测后,您可以取消部署模型以免产生更多部署费用。了解详情

模型必须每 6 个月重新训练一次,才能继续执行预测。

进行在线预测

控制台

通常,您使用在线预测从业务应用中获取预测结果。但是,您可以在 Google Cloud 控制台中使用 AutoML Tables,通过一组特定输入来测试数据格式或模型。

  1. 访问 Google Cloud 控制台中的 AutoML Tables 页面。

    转到 AutoML Tables 页面

  2. 选择模型并选择要使用的模型。

  3. 选择测试和使用标签页,然后点击在线预测

  4. 如果模型尚未部署,点击部署模型立即进行部署。

    您必须先部署模型才能使用在线预测。部署模型会产生费用。如需了解详情,请参阅价格页面

  5. 在提供的文本框中提供您的输入值。

    或者,您可以选择 JSON 代码视图,提供 JSON 格式的输入值。

  6. 如果您想了解每个特征如何对预测产生影响,请选择生成特征重要性

    为了便于阅读,Google Cloud 控制台会截断局部特征重要性值。如果您需要精确的值,请使用 Cloud AutoML API 发出预测请求。

    要了解特征重要性,请参阅局部特征重要性

  7. 点击预测以获取预测结果。

    AutoML Tables 预测页面

    要了解如何解读预测结果,请参阅解读预测结果。要了解局部特征重要性,请参阅局部特征重要性

  8. (可选)如果您不打算请求更多在线预测,可以点击取消部署模型来取消部署您的模型以避免部署费用。

curl

要请求对一组值进行预测,可使用特征值创建 JSON 对象,然后使用 model.predict 方法获取预测结果。

这些值必须包括您在训练中包含的相同列,并且必须与评估标签页上显示的顺序相同,点击包含的列链接即可获得。

如果要对值重新排序,可以视需要加入一组列规范 ID(按值的顺序排序)。您可以从模型对象中获取列规范 ID;它们位于 TablesModelMetadata.inputFeatureColumnSpecs 字段中。

Row 对象中每个值(特征)的数据类型取决于该特征的 AutoML Tables 数据类型。如需查看 AutoML Tables 数据类型接受的数据类型的列表,请参阅 Row 对象格式

  1. 如果尚未部署模型,请立即部署。了解详情

  2. 请求预测。

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

    • endpoint:全球位置为 automl.googleapis.com,欧盟地区为 eu-automl.googleapis.com
    • project-id:您的 Google Cloud 项目 ID。
    • location:资源的位置:全球位置为 us-central1,欧盟位置为 eu
    • model-id:模型的 ID。例如 TBL543
    • valueN:每列的值(按正确的顺序显示)。

    HTTP 方法和网址:

    POST https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict

    请求 JSON 正文:

    {
      "payload": {
        "row": {
          "values": [
            value1, value2,...
          ]
        }
      }
    }
    

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

    curl

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

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-user-project: project-id" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict"

    PowerShell

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

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://endpoint/v1beta1/projects/project-id/locations/location/models/model-id:predict" | Select-Object -Expand Content
    要包含局部特征重要性结果,请添加 feature_importance 参数。要详细了解局部特征重要性,请参阅局部特征重要性

  3. 查看结果。

    对于分类模型,您应该会看到如下例所示的输出。请注意,返回两个结果,每个结果都有一个置信度估计值 (score)。置信度估计值介于 0 到 1 之间,表示模型认为预测值正确的可能性。要详细了解如何使用置信度估算值,请参阅解读预测结果

    {
     "payload": [
       {
         "tables": {
           "score": 0.11210235,
           "value": "1"
         }
       },
       {
         "tables": {
           "score": 0.8878976,
           "value": "2"
         }
       }
     ]
    }
    

    对于回归模型,结果包括一个预测值和一个预测区间。预测区间提供一个范围,表示时间的真实值有 95% 的机会是在该范围内(根据用来训练模型的数据得出)。请注意,预测值可能不是以区间为中心(甚至可能位于区间之外),因为预测区间以中间值为中心,而预测值是预期值(或平均值)。

    {
     "payload": [
       {
         "tables": {
           "value": 207.18209838867188,
           "predictionInterval": {
             "start": 29.712770462036133,
             "end": 937.42041015625
           }
         }
       }
     ]
    }
    

    要了解局部特征重要性结果,请参阅局部特征重要性

  4. (可选)如果您已完成请求在线预测,则可以取消部署模型以免产生部署费用。了解详情

Java

如果资源位于欧盟区域,您必须明确设置端点。了解详情

import com.google.cloud.automl.v1beta1.AnnotationPayload;
import com.google.cloud.automl.v1beta1.ExamplePayload;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.PredictRequest;
import com.google.cloud.automl.v1beta1.PredictResponse;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import com.google.cloud.automl.v1beta1.Row;
import com.google.cloud.automl.v1beta1.TablesAnnotation;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class TablesPredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    // Values should match the input expected by your model.
    List<Value> values = new ArrayList<>();
    // values.add(Value.newBuilder().setBoolValue(true).build());
    // values.add(Value.newBuilder().setNumberValue(10).build());
    // values.add(Value.newBuilder().setStringValue("YOUR_STRING").build());
    predict(projectId, modelId, values);
  }

  static void predict(String projectId, String modelId, List<Value> values) throws IOException {
    // 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 (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);
      Row row = Row.newBuilder().addAllValues(values).build();
      ExamplePayload payload = ExamplePayload.newBuilder().setRow(row).build();

      // Feature importance gives you visibility into how the features in a specific prediction
      // request informed the resulting prediction. For more info, see:
      // https://cloud.google.com/automl-tables/docs/features#local
      PredictRequest request =
          PredictRequest.newBuilder()
              .setName(name.toString())
              .setPayload(payload)
              .putParams("feature_importance", "true")
              .build();

      PredictResponse response = client.predict(request);

      System.out.println("Prediction results:");
      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        TablesAnnotation tablesAnnotation = annotationPayload.getTables();
        System.out.format(
            "Classification label: %s%n", tablesAnnotation.getValue().getStringValue());
        System.out.format("Classification score: %.3f%n", tablesAnnotation.getScore());
        // Get features of top importance
        tablesAnnotation
            .getTablesModelColumnInfoList()
            .forEach(
                info ->
                    System.out.format(
                        "\tColumn: %s - Importance: %.2f%n",
                        info.getColumnDisplayName(), info.getFeatureImportance()));
      }
    }
  }
}

Node.js

如果资源位于欧盟区域,您必须明确设置端点。了解详情


/**
 * Demonstrates using the AutoML client to request prediction from
 * automl tables using csv.
 * 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., "TBL000000000000";
// const inputs = [{ numberValue: 1 }, { stringValue: 'value' }, { stringValue: 'value2' } ...]

const automl = require('@google-cloud/automl');

// Create client for prediction service.
const automlClient = new automl.v1beta1.PredictionServiceClient();

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

async function predict() {
  // Set the payload by giving the row values.
  const payload = {
    row: {
      values: inputs,
    },
  };

  // Params is additional domain-specific parameters.
  // Currently there is no additional parameters supported.
  const [response] = await automlClient.predict({
    name: modelFullId,
    payload: payload,
    params: {feature_importance: true},
  });
  console.log('Prediction results:');

  for (const result of response.payload) {
    console.log(`Predicted class name: ${result.displayName}`);
    console.log(`Predicted class score: ${result.tables.score}`);

    // Get features of top importance
    const featureList = result.tables.tablesModelColumnInfo.map(
      columnInfo => {
        return {
          importance: columnInfo.featureImportance,
          displayName: columnInfo.columnDisplayName,
        };
      }
    );
    // Sort features by their importance, highest importance first
    featureList.sort((a, b) => {
      return b.importance - a.importance;
    });

    // Print top 10 important features
    console.log('Features of top importance');
    console.log(featureList.slice(0, 10));
  }
}
predict();

Python

AutoML Tables 的客户端库包含其他 Python 方法,这些方法使用 AutoML Tables API 进行简化。这些方法按名称而不是 ID 来引用数据集和模型。您的数据集和模型的名称必须是唯一的。如需了解详情,请参阅客户端参考

如果资源位于欧盟区域,您必须明确设置端点。了解详情

# TODO(developer): Uncomment and set the following variables
# project_id = 'PROJECT_ID_HERE'
# compute_region = 'COMPUTE_REGION_HERE'
# model_display_name = 'MODEL_DISPLAY_NAME_HERE'
# inputs = {'value': 3, ...}

from google.cloud import automl_v1beta1 as automl

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

if feature_importance:
    response = client.predict(
        model_display_name=model_display_name,
        inputs=inputs,
        feature_importance=True,
    )
else:
    response = client.predict(model_display_name=model_display_name, inputs=inputs)

print("Prediction results:")
for result in response.payload:
    print(f"Predicted class name: {result.tables.value}")
    print(f"Predicted class score: {result.tables.score}")

    if feature_importance:
        # get features of top importance
        feat_list = [
            (column.feature_importance, column.column_display_name)
            for column in result.tables.tables_model_column_info
        ]
        feat_list.sort(reverse=True)
        if len(feat_list) < 10:
            feat_to_show = len(feat_list)
        else:
            feat_to_show = 10

        print("Features of top importance:")
        for feat in feat_list[:feat_to_show]:
            print(feat)

后续步骤