透過自訂訓練模型取得線上推論結果

本頁面說明如何使用 Google Cloud CLI 或 Agent Platform API,從自訂訓練模型取得線上 (即時) 推論。

設定線上推論的輸入內容格式

本節說明如何將推論輸入執行個體格式化並編碼為 JSON,這是使用 predict 或 explain 方法時的必要步驟。如果您使用 rawPredict 方法,則不需要執行這項操作。如要瞭解應選擇哪種方法,請參閱「將要求傳送至端點」。

如果使用 Agent Platform SDK for Python 傳送推論要求,請指定執行個體清單,不含 instances 欄位。例如,指定 [ ["the","quick","brown"], ... ],而非 { "instances": [ ["the","quick","brown"], ... ] }。

如果模型使用自訂容器,輸入內容必須採用 JSON 格式,且有額外的 parameters 欄位可用於容器。進一步瞭解如何使用自訂容器設定推論輸入內容的格式。

將執行個體格式化為 JSON 字串

線上推論的基本格式是資料執行個體清單。這些值可以是純值清單,也可以是 JSON 物件的成員,具體取決於您在訓練應用程式中設定輸入內容的方式。TensorFlow 模型可接受更複雜的輸入內容,而大多數 scikit-learn 和 XGBoost 模型則預期輸入內容為數字清單。

這個範例顯示了 TensorFlow 模型的輸入張量和樣本鍵:

 {"values": [1, 2, 3, 4], "key": 1}

只要 JSON 字串的格式符合下列規則,其構成內容就可以較為複雜:

  • 執行個體資料的頂層必須是 JSON 物件:鍵/值組合的字典。

  • 樣本物件的個別值可以是字串、數字或清單。您無法嵌入 JSON 物件。

  • 清單僅能包含相同類型的項目 (包括其他清單)。不能混合使用字串和數值。

您會將線上推論的輸入執行個體,做為 projects.locations.endpoints.predict 呼叫的訊息內文傳遞。進一步瞭解要求主體的格式規定。

將每個執行個體設為 JSON 陣列中的項目,並將陣列做為 JSON 物件的 instances 欄位。例如:

{"instances": [
  {"values": [1, 2, 3, 4], "key": 1},
  {"values": [5, 6, 7, 8], "key": 2}
]}

編碼二進位資料,做為推論輸入

二進位資料無法採用 JSON 支援的 UTF-8 編碼字串格式。如果您的輸入內容含有二進位資料,則必須使用 base64 編碼來表示。下列是必要的特殊格式設定:

  • 編碼字串必須採用具有 b64 單一索引鍵的 JSON 物件格式。在 Python 3 中,base64 編碼會輸出位元組序列。您必須將其轉換為字串,才能將其序列化為 JSON:

    {'image_bytes': {'b64': base64.b64encode(jpeg_data).decode()}}
    
  • 在 TensorFlow 模型程式碼中,您必須為二進位輸入和輸出張量提供結尾為「_bytes」的別名。

要求和回應範例

本節說明推論要求主體和回應主體的格式,並提供 TensorFlow、scikit-learn 和 XGBoost 的範例。

要求主體詳細資料

TensorFlow

要求主體包含結構如下的資料 (JSON 表示法):

{
  "instances": [
    <value>|<simple/nested list>|<object>,
    ...
  ]
}

instances[] 物件為必要,且必須包含要取得推論的執行個體清單。

執行個體清單中每個元素的結構,取決於模型的輸入定義。執行個體可以包含具名輸入內容 (做為物件),也可以只包含未加上標籤的值。

只有部分資料會包含已命名的輸入。某些樣本屬於簡易的 JSON 值 (布林值、數值或字串),但樣本通常是包含簡單值或複雜巢狀結構的清單。

以下是幾個要求主體的範例。

將每一資料列都編碼為字串值的 CSV 資料:

{"instances": ["1.0,true,\\"x\\"", "-2.0,false,\\"y\\""]}

純文字:

{"instances": ["the quick brown fox", "the lazy dog"]}

編碼為字詞清單的語句 (字串向量):

{
  "instances": [
    ["the","quick","brown"],
    ["the","lazy","dog"],
    ...
  ]
}

浮點純量值:

{"instances": [0.0, 1.1, 2.2]}

整數向量:

{
  "instances": [
    [0, 1, 2],
    [3, 4, 5],
    ...
  ]
}

張量 (下列範例是二維張量):

{
  "instances": [
    [
      [0, 1, 2],
      [3, 4, 5]
    ],
    ...
  ]
}

可透過不同方式來表示的圖片。在此編碼配置中,前兩個維度代表圖片的列和欄,第三個維度則包含每個像素的 R、G、B 值的清單 (向量):

{
  "instances": [
    [
      [
        [138, 30, 66],
        [130, 20, 56],
        ...
      ],
      [
        [126, 38, 61],
        [122, 24, 57],
        ...
      ],
      ...
    ],
    ...
  ]
}

資料編碼

JSON 字串的編碼必須為 UTF-8。如要傳送二進位資料,您必須使用 base64 編碼並將資料標示為二進位。如要將 JSON 字串標示為二進位,請將其替換為具有單一屬性 b64 的 JSON 物件:

{"b64": "..."} 

以下範例顯示兩個序列化的 tf.Examples 執行個體,需要 base64 編碼 (假資料,僅供說明):

{"instances": [{"b64": "X5ad6u"}, {"b64": "IA9j4nx"}]}

下列範例顯示須採用 base64 編碼兩個 JPEG 圖片位元組字串 (此為僅供說明之用的偽資料):

{"instances": [{"b64": "ASa8asdf"}, {"b64": "JLK7ljk3"}]}

多個輸入張量

部分模型具有可接受多個輸入張量的基礎 TensorFlow 圖形。在這種情況下,請使用 JSON 名稱/值組合的名稱來識別輸入張量。

輸入張量別名為「tag」(字串) 和「image」(base64 編碼字串) 的圖表:

{
  "instances": [
    {
      "tag": "beach",
      "image": {"b64": "ASa8asdf"}
    },
    {
      "tag": "car",
      "image": {"b64": "JLK7ljk3"}
    }
  ]
}

輸入張量別名為「tag」(字串) 和「image」(8 位元整數的 3 維陣列) 的圖表:

{
  "instances": [
    {
      "tag": "beach",
      "image": [
        [
          [138, 30, 66],
          [130, 20, 56],
          ...
        ],
        [
          [126, 38, 61],
          [122, 24, 57],
          ...
        ],
        ...
      ]
    },
    {
      "tag": "car",
      "image": [
        [
          [255, 0, 102],
          [255, 0, 97],
          ...
        ],
        [
          [254, 1, 101],
          [254, 2, 93],
          ...
        ],
        ...
      ]
    },
    ...
  ]
}

scikit-learn

要求主體包含結構如下的資料 (JSON 表示法):

{
  "instances": [
    <simple list>,
    ...
  ]
}

instances[] 物件為必要,且必須包含要取得推論的執行個體清單。在以下範例中,每個輸入執行個體都是浮點數清單:

{
  "instances": [
    [0.0, 1.1, 2.2],
    [3.3, 4.4, 5.5],
    ...
  ]
}

輸入執行個體的維度必須符合模型預期。舉例來說,如果模型需要三個特徵,則每個輸入執行個體的長度必須為 3。

XGBoost

要求主體包含結構如下的資料 (JSON 表示法):

{
  "instances": [
    <simple list>,
    ...
  ]
}

instances[] 物件為必要,且必須包含要取得推論的執行個體清單。在以下範例中,每個輸入執行個體都是浮點數清單:

{
  "instances": [
    [0.0, 1.1, 2.2],
    [3.3, 4.4, 5.5],
    ...
  ]
}

輸入執行個體的維度必須符合模型預期。舉例來說,如果模型需要三個特徵,則每個輸入執行個體的長度必須為 3。

Agent Platform 不支援 XGBoost 輸入執行個體的稀疏表示法。

線上推論服務對零和 NaN 的解讀方式不同。如果特徵值為零,請在對應的輸入內容中使用 0.0。如果缺少特徵值,請在對應的輸入內容中使用 "NaN"。

下列範例代表具有單一輸入執行個體的推論要求,其中第一個特徵的值為 0.0,第二個特徵的值為 1.1,第三個特徵的值則遺失:

{"instances": [[0.0, 1.1, "NaN"]]}

PyTorch

如果模型使用 PyTorch 預先建構容器,TorchServe 的預設處理常式會預期每個執行個體都包裝在 data 欄位中。例如:

{
  "instances": [
    { "data": , <value> },
    { "data": , <value> }
  ]
}

回應主體詳細資料

如果呼叫成功,回應主體會包含要求主體中每個執行個體的一項推論項目,順序相同:

{
  "predictions": [
    {
      object
    }
  ],
  "deployedModelId": string
}

如果任何執行個體的推論失敗,回應主體就不會包含任何推論。而是包含一個錯誤項目:

{
  "error": string
}

predictions[] 物件包含推論清單,要求中的每個執行個體各有一個推論。

發生錯誤時,error 字串會包含描述問題的訊息。如果在處理任何執行個體時發生錯誤,系統會傳回錯誤,而非推論清單。

雖然每個執行個體都有一個推論,但推論的格式與執行個體的格式沒有直接關係。推論會採用模型定義的輸出內容集合中指定的格式。推論集合會以 JSON 清單形式傳回。清單中的每個成員都可以是簡單的值、清單或任何複雜度的 JSON 物件。如果模型有多個輸出張量,每項推論都會是 JSON 物件,其中包含每個輸出的名稱/值組合。這些名稱會識別圖表中的輸出別名。

回應主體範例

TensorFlow

下列範例顯示幾種可能的回應:

  • 針對三個輸入樣本產生一組簡單預測,其中每個預測都是整數值:

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 一組更複雜的預測,每個預測都包含兩個具名值,分別對應至名為 label 和 scores 的輸出張量。label 的值是預測類別 (「car」或「beach」),scores 則包含該執行個體在可能類別中的機率清單。

    {
      "predictions": [
        {
          "label": "beach",
          "scores": [0.1, 0.9]
        },
        {
          "label": "car",
          "scores": [0.75, 0.25]
        }
      ],
      "deployedModelId": 123456789012345678
    }
    
  • 如果處理輸入樣本時發生錯誤,則回應如下:

    {"error": "Divide by zero"}
    

scikit-learn

下列範例顯示幾種可能的回應:

  • 針對三個輸入樣本產生一組簡單預測,其中每個預測都是整數值:

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 如果處理輸入樣本時發生錯誤,則回應如下:

    {"error": "Divide by zero"}
    

XGBoost

下列範例顯示幾種可能的回應:

  • 針對三個輸入樣本產生一組簡單預測,其中每個預測都是整數值:

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 如果處理輸入樣本時發生錯誤,則回應如下:

    {"error": "Divide by zero"}
    

傳送要求至端點

傳送要求的方式有四種:

  • 推論要求:傳送要求至 predict,取得線上推論。

  • 原始推論要求:傳送要求至 rawPredict,可讓您使用任意 HTTP 酬載,而不必遵循本頁「設定輸入內容格式」一節所述的規範。在下列情況下,您可能需要取得原始推論:

    • 您使用自訂容器,但該容器接收要求和傳送回應的方式與指南不同。
    • 需要較低的延遲時間。rawPredict 會略過序列化步驟,直接將要求轉送至推論容器。
    • 您正在使用 NVIDIA Triton 提供推論。
  • 說明要求:傳送要求至 explain。如果您已為 Vertex Explainable AI 設定 Model,則可取得線上說明。線上解釋要求與線上推論要求的格式相同,傳回的回應也類似,唯一的差別在於線上解釋回應包含特徵歸因和推論。

  • 叫用要求:將任意要求轉送至模型伺服器。舉例來說,「/invoke/foo/bar」會以「/foo/bar」的形式轉送至模型伺服器。這項功能為公開預先發布版,僅支援專屬端點上的 HTTP 呼叫。如要建立可叫用的模型,請按照指示使用任意自訂路徑。

將線上推論要求傳送至專屬公開端點

專屬端點可使用 HTTP 和 gRPC 通訊協定進行通訊。如果是 gRPC 要求,則必須加入 x-vertex-ai-endpoint-id 標頭,確保端點識別資訊正確無誤。下列 API 支援這些專屬端點:

  • 預測
  • RawPredict
  • StreamRawPredict
  • Chat Completion (僅限 Gemini Enterprise Agent Platform Model Garden)
  • 叫用

專屬端點會使用新的網址路徑。您可以從 REST API 的 dedicatedEndpointDns 欄位,或 Agent Platform SDK for Python 的 Endpoint.dedicated_endpoint_dns 擷取這個路徑。

如要使用 Agent Platform SDK for Python 將推論傳送至專屬端點,請將 use_dedicated_endpoint 參數設為 True:

endpoint.predict(instances=instances, use_dedicated_endpoint=True)

將線上推論要求傳送至共用公開端點

gcloud

下列範例使用 gcloud ai endpoints predict 指令:

  1. 在本機環境中,將下列 JSON 物件寫入檔案。檔案名稱不重要,但在本範例中,請將檔案命名為 request.json。

    {
     "instances": INSTANCES
    }
    

    更改下列內容:

    • INSTANCES:要取得推論的執行個體 JSON 陣列。每個執行個體的格式取決於訓練好的機器學習模型預期的輸入內容。詳情請參閱「設定線上推論的輸入內容格式」。

  2. 執行下列指令:

    gcloud ai endpoints predict ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json

    更改下列內容:

    • ENDPOINT_ID:端點 ID。
    • LOCATION_ID:您使用 Agent Platform 的區域。

REST

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION_ID:您使用 Agent Platform 的區域。
  • PROJECT_ID:您的專案 ID。
  • ENDPOINT_ID:端點 ID。
  • INSTANCES:要取得推論的執行個體 JSON 陣列。每個執行個體的格式取決於訓練好的機器學習模型預期輸入的內容。詳情請參閱「設定線上推論的輸入內容格式」。

HTTP 方法和網址:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict

JSON 要求內文:

{
  "instances": INSTANCES
}

如要傳送要求,請選擇以下其中一個選項:

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict"

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content
如果成功,您會收到類似下方的 JSON 回應。在回覆中,預期會看到下列替換內容:
  • PREDICTIONS:預測結果的 JSON 陣列,要求主體中包含的每個執行個體各有一個。
  • DEPLOYED_MODEL_ID:提供預測結果的 DeployedModel ID。
{
  "predictions": PREDICTIONS,
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 Agent Platform Java API 參考文件。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictRequest;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.List;

public class PredictCustomTrainedModelSample {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String instance = "[{ “feature_column_a”: “value”, “feature_column_b”: “value”}]";
    String project = "YOUR_PROJECT_ID";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictCustomTrainedModel(project, endpointId, instance);
  }

  static void predictCustomTrainedModel(String project, String endpointId, String instance)
      throws IOException {
    PredictionServicPredictionServiceSettingsceSettings =
        PredictionServicPredictionServiceSettings          .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 (PredictionServicPredictionServiceClientceClient =
        PredictionServicPredictionServiceClientonServiceSettings)) {
      String location = "us-central1";
      EndpointName endEndpointNameEndpointName.of(EndpointNameation, endpointId);

      ListValue.BuildeListValueue = ListValue.newBuiListValue     JsonFormat.parseJsonFormatinstance, listValue);
      List<Value> instanListValuelistValue.getValuesList();

      PredictRequest pPredictRequest=
          PredictRequest.nPredictRequest            .setEndpoint(endpointName.toSendpointName.toString().addAllInstances(instanceList)
              .build();
      PredictResponse PredictResponse = predictionServiceClient.predict(predictRequest);

      System.out.println("Predict Custom Trained model Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.predictResponse.getDeployedModelId()out.println("Predictions");
      for (Value predictionValueedictResponse.predictResponse.getPredictionsList()em.out.format("\tPrediction: %s\n", prediction);
      }
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Node.js 設定說明操作。詳情請參閱 Agent Platform Node.js API 參考文件。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

// const filename = "YOUR_PREDICTION_FILE_NAME";
// const endpointId = "YOUR_ENDPOINT_ID";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const util = require('util');
const {readFile} = require('fs');
const readFileAsync = util.promisify(readFile);

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

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

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictCustomTrainedModel() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
  const parameters = {
    structValue: {
      fields: {},
    },
  };
  const instanceDict = await readFileAsync(filename, 'utf8');
  const instanceValue = JSON.parse(instanceDict);
  const instance = {
    structValue: {
      fields: {
        Age: {stringValue: instanceValue['Age']},
        Balance: {stringValue: instanceValue['Balance']},
        Campaign: {stringValue: instanceValue['Campaign']},
        Contact: {stringValue: instanceValue['Contact']},
        Day: {stringValue: instanceValue['Day']},
        Default: {stringValue: instanceValue['Default']},
        Deposit: {stringValue: instanceValue['Deposit']},
        Duration: {stringValue: instanceValue['Duration']},
        Housing: {stringValue: instanceValue['Housing']},
        Job: {stringValue: instanceValue['Job']},
        Loan: {stringValue: instanceValue['Loan']},
        MaritalStatus: {stringValue: instanceValue['MaritalStatus']},
        Month: {stringValue: instanceValue['Month']},
        PDays: {stringValue: instanceValue['PDays']},
        POutcome: {stringValue: instanceValue['POutcome']},
        Previous: {stringValue: instanceValue['Previous']},
      },
    },
  };

  const instances = [instance];
  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);

  console.log('Predict custom trained model response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}
predictCustomTrainedModel();

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

def endpoint_predict_sample(
    project: str, location: str, instances: list, endpoint: str
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint)

    prediction = endpoint.predict(instances=instances)
    print(prediction)
    return prediction

傳送線上原始推論要求

gcloud

以下範例使用 gcloud ai endpoints raw-predict 指令:

  • 如要使用在指令列中指定的 REQUEST JSON 物件要求推論,請執行下列指令:

     gcloud ai endpoints raw-predict ENDPOINT_ID \
         --region=LOCATION_ID \
         --request=REQUEST
     
  • 如要使用儲存在檔案 image.jpeg 中的圖片和適當的 Content-Type 標頭要求推論,請執行下列指令:

     gcloud ai endpoints raw-predict ENDPOINT_ID \
         --region=LOCATION_ID \
         --http-headers=Content-Type=image/jpeg \
         --request=@image.jpeg
     

    更改下列內容:

    • ENDPOINT_ID:端點 ID。
    • LOCATION_ID:您使用 Agent Platform 的區域。
    • REQUEST:要取得推論的要求內容。要求的格式取決於自訂容器預期的格式,不一定是 JSON 物件。

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

from google.cloud import aiplatform_v1


def sample_raw_predict():
    # Create a client
    client = aiplatform_v1.PredictionServiceClient()

    # Initialize request argument(s)
    request = aiplatform_v1.RawPredictRequest(
        endpoint="endpoint_value",
    )

    # Make the request
    response = client.raw_predict(request=request)

    # Handle the response
    print(response)

回應包含下列 HTTP 標頭:

  • X-Vertex-AI-Endpoint-Id:提供這項推論的 Endpoint ID。

  • X-Vertex-AI-Deployed-Model-Id:提供這項推論的端點 DeployedModel ID。

線上傳送說明要求

gcloud

下列範例使用 gcloud ai endpoints explain 指令:

  1. 在本機環境中,將下列 JSON 物件寫入檔案。檔案名稱不重要,但在本範例中,請將檔案命名為 request.json。

    {
     "instances": INSTANCES
    }
    

    更改下列內容:

    • INSTANCES:要取得推論的執行個體 JSON 陣列。每個執行個體的格式取決於訓練好的機器學習模型預期輸入的內容。詳情請參閱「設定線上推論的輸入內容格式」。

  2. 執行下列指令:

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION_ID \
      --json-request=request.json

    更改下列內容:

    • ENDPOINT_ID:端點 ID。
    • LOCATION_ID:您使用 Agent Platform 的區域。

    如要將說明要求傳送至 Endpoint 上的特定 DeployedModel,可以指定 --deployed-model-id 旗標:

    gcloud ai endpoints explain ENDPOINT_ID \
      --region=LOCATION \
      --deployed-model-id=DEPLOYED_MODEL_ID \
      --json-request=request.json

    除了上述預留位置外,請替換下列項目:

    • DEPLOYED_MODEL_ID 選用:要取得說明的已部署模型 ID。這個 ID 會包含在 predict 方法的回應中。如要要求特定模型的解釋,且您已將多個模型部署至同一個端點,則可使用這個 ID,確保系統傳回該特定模型的解釋。

REST

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION_ID:您使用 Agent Platform 的區域。
  • PROJECT_ID:
  • ENDPOINT_ID:端點 ID。
  • INSTANCES:要取得推論的執行個體 JSON 陣列。每個執行個體的格式取決於訓練好的機器學習模型預期輸入的內容。詳情請參閱「設定線上推論的輸入內容格式」。

HTTP 方法和網址:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain

JSON 要求內文:

{
  "instances": INSTANCES
}

如要傳送要求,請選擇以下其中一個選項:

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain"

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain" | Select-Object -Expand Content
如果成功,您會收到類似下方的 JSON 回應。在回覆中,預期會看到下列替換內容:
  • PREDICTIONS:預測結果的 JSON 陣列,要求主體中包含的每個執行個體各有一個。
  • EXPLANATIONS:說明的 JSON 陣列,每個預測各有一個。
  • DEPLOYED_MODEL_ID:提供預測結果的 DeployedModel ID。
{
  "predictions": PREDICTIONS,
  "explanations": EXPLANATIONS,
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

def explain_tabular_sample(
    project: str, location: str, endpoint_id: str, instance_dict: Dict
):

    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint(endpoint_id)

    response = endpoint.explain(instances=[instance_dict], parameters={})

    for explanation in response.explanations:
        print(" explanation")
        # Feature attributions.
        attributions = explanation.attributions
        for attribution in attributions:
            print("  attribution")
            print("   baseline_output_value:", attribution.baseline_output_value)
            print("   instance_output_value:", attribution.instance_output_value)
            print("   output_display_name:", attribution.output_display_name)
            print("   approximation_error:", attribution.approximation_error)
            print("   output_name:", attribution.output_name)
            output_index = attribution.output_index
            for output_index in output_index:
                print("   output_index:", output_index)

    for prediction in response.predictions:
        print(prediction)

傳送線上叫用要求

叫用路徑可讓您存取部署作業中的所有非根要求路徑。舉例來說,/invoke/foo/bar 會以 /foo/bar 的形式轉送至模型伺服器。存取路徑的方法有兩種。

自訂路由要求傳送至專屬端點

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

def invoke_tabular_sample(
    project: str,
    location: str,
    endpoint_id: str,
    request_path: str,
    http_request_body: Dict[str, Any],
    stream: bool = False,
):
    aiplatform.init(project=project, location=location)

    dedicated_endpoint = aiplatform.Endpoint(endpoint_id)
    if stream:
        for chunk in dedicated_endpoint.invoke(
            request_path=request_path,
            body=json.dumps(http_request_body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            stream=True,
        ):
            print(chunk)
    else:
        response = dedicated_endpoint.invoke(
            request_path=request_path,
            body=json.dumps(http_request_body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
        )
        print(response)

將自訂路徑要求直接傳送至已部署的模型

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

def invoke_direct_deployed_model_inference_tabular_sample(
    project: str,
    location: str,
    endpoint_id: str,
    request_path: str,
    http_request_body: Dict[str, Any],
    deployed_model_id: str,
    stream: bool = False,
):
    aiplatform.init(project=project, location=location)

    dedicated_endpoint = aiplatform.Endpoint(endpoint_id)
    if stream:
        for chunk in dedicated_endpoint.invoke(
            request_path=request_path,
            body=json.dumps(http_request_body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            deployed_model_id=deployed_model_id,
            stream=True,
        ):
            print(chunk)
    else:
        response = dedicated_endpoint.invoke(
            request_path=request_path,
            body=json.dumps(http_request_body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            deployed_model_id=deployed_model_id,
        )
        print(response)

後續步驟