カスタム トレーニング モデルからオンライン予測を取得する

このページでは、Google Cloud コンソールまたは Vertex AI API を使用して、カスタム トレーニング済みのモデルからオンライン(リアルタイム)予測を取得する方法について説明します。

オンライン予測の入力をフォーマットする

このセクションでは、予測入力インスタンスを JSON 形式にフォーマットしてエンコードする方法について説明します。この操作は、predict または explain メソッドを使用する場合に必要です。rawPredict メソッドの場合は必要ありません。メソッドの選択については、エンドポイントにリクエストを送信するをご覧ください。

Python 用 Vertex AI SDK を使用して予測リクエストを送信する場合は、instances フィールドなしでインスタンスのリストを指定します。たとえば、{ "instances": [ ["the","quick","brown"], ... ] } ではなく [ ["the","quick","brown"], ... ] と指定します。

モデルでカスタム コンテナを使用する場合は、入力を JSON 形式で記述する必要があります。また、コンテナで使用できる parameters フィールドを追加する必要があります。詳細については、カスタム コンテナを含む予測入力をフォーマットするをご覧ください。

JSON 文字列としてインスタンスをフォーマットする

オンライン予測の基本的な形式はデータ インスタンスのリストです。これらは、トレーニング アプリケーションで入力を構成した方法に応じて、値のプレーンリストまたは JSON オブジェクトのメンバーのいずれかになります。scikit-learn と XGBoost のほとんどのモデルは入力として数値のリストを想定していますが、TensorFlow モデルはより複雑な入力にも対応しています。

次の例は、TensorFlow モデルの入力テンソルとインスタンス キーを示しています。

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

次の規則に従う限り、JSON 文字列の構成は複雑になってもかまいません。

  • インスタンス データの最上位レベルは、Key-Value ペアの辞書である 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 という 1 つのキーを持つ 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],
    ...
  ]
}

テンソル(この場合、2 次元のテンソル):

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

画像は、さまざまな方法で表現できます。次のエンコード スキームでは、最初の 2 つの次元は画像の行と列を表し、3 つ目の次元に各ピクセルの R、G、B 値のリスト(ベクトル)が含まれます。

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

データのエンコード

JSON 文字列は UTF-8 としてエンコードする必要があります。バイナリデータを送信するには、データを Base64 エンコードし、バイナリとしてマークする必要があります。JSON 文字列をバイナリとしてマークするには、b64 という名前の単一の属性の JSON オブジェクトに置き換えます。

{"b64": "..."} 

次の例は、Base64 エンコードを必要とする 2 つのシリアル化された tf.Examples インスタンスを示しています(例示のための架空データ)。

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

次の例は、base64 エンコードを必要とする、JPEG 画像の 2 つのバイト文字列を示しています(例示のための架空のデータ)。

{"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 つの特徴が必要な場合、各入力インスタンスの長さは 3 である必要があります。

XGBoost

リクエストの本文には、次の構造をしたデータが含まれています(JSON 表現)。

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

instances[] オブジェクトは必須であり、予測の取得対象となるインスタンスのリストをこれに含める必要があります。次の例では、各入力インスタンスは浮動小数点数のリストです。

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

入力インスタンスの次元は、モデルが想定している次元と一致している必要があります。たとえば、モデルに 3 つの特徴が必要な場合、各入力インスタンスの長さは 3 である必要があります。

Vertex AI は、XGBoost の入力インスタンスのスパース表現をサポートしていません。

オンライン予測サービスは、ゼロと NaN を区別して解釈します。特徴値がゼロの場合、対応する入力で 0.0 を使用します。特徴値が不足している場合は、対応する入力で "NaN" を使用します。

次の例は、単一入力インスタンスを含む予測リクエストを表しています。ここで最初の特徴値は 0.0、2 番目の特徴値は 1.1、3 番目の特徴値はありません。

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

PyTorch

モデルが PyTorch のビルド済みコンテナを使用する場合、TorchServe のデフォルト ハンドラは、各インスタンスが data フィールドでラップされることを想定しています。例:

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

レスポンス本文の詳細

呼び出しが成功した場合、レスポンスの本文には、リクエストの本文内のインスタンスごとに、同じ順序で 1 つの予測エントリが含まれます。

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

いずれかのインスタンスの予測に失敗した場合、レスポンスの本文には予測が含まれません。代わりに、単一のエラーエントリが含まれています。

{
  "error": string
}

predictions[] オブジェクトには、リクエストのインスタンスごとに 1 つの予測からなるリストが含まれます。

エラーの場合、error 文字列には問題を説明するメッセージが含まれます。インスタンスの処理中にエラーが発生した場合は、予測リストではなくエラーが返されます。

インスタンスごとに 1 つの予測があっても、予測の形式はインスタンスの形式に直接関係しません。予測には、モデルに定義された出力コレクションで指定されている形式が適用されます。予測のコレクションは JSON リストで返されます。リストの各メンバーは、単純な値、リスト、多様な複雑度の JSON オブジェクトのいずれかです。モデルに複数の出力テンソルがある場合、各予測は各出力の名前と値のペアを含む JSON オブジェクトになります。名前はグラフの出力エイリアスを識別します。

レスポンス本文の例

TensorFlow

次の例は、いくつかの可能なレスポンスを示しています。

  • 3 つの入力インスタンスの単純な予測セット。各予測は整数値です。

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • より複雑な予測セット。予測のそれぞれに、出力テンソルに対応する labelscores という 2 つの名前付き値が含まれます。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

次の例は、いくつかの可能なレスポンスを示しています。

  • 3 つの入力インスタンスの単純な予測セット。各予測は整数値です。

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 入力インスタンスの処理中にエラーが発生した場合のレスポンス:

    {"error": "Divide by zero"}
    

XGBoost

次の例は、いくつかの可能なレスポンスを示しています。

  • 3 つの入力インスタンスの単純な予測セット。各予測は整数値です。

    {"predictions":
       [5, 4, 3],
       "deployedModelId": 123456789012345678
    }
    
  • 入力インスタンスの処理中にエラーが発生した場合のレスポンス:

    {"error": "Divide by zero"}
    

エンドポイントにリクエストを送信する

リクエストを送信するには、次の 3 つの方法があります。

  • 予測リクエスト: オンライン予測を取得するリクエストを predict に送信します。

  • 未加工の予測リクエスト: rawPredict にリクエストを送信します。これにより、このページの入力形式に記載されているガイドラインに従うのではなく、任意の HTTP ペイロードを使用できます。未加工の予測は、次のような場合に取得できます。

    • カスタム コンテナを使用しており、ガイドラインとは異なるリクエストを受信し、レスポンスを送信している場合。
    • 低レイテンシを必要とする場合。rawPredict は、シリアル化のステップをスキップし、リクエストを予測コンテナに直接転送します。
    • NVIDIA Triton で予測を行っている場合。
  • 説明リクエスト: リクエストを explain に送信します。Vertex Explainable AI 用に Model を構成している場合は、オンライン説明を取得できます。オンライン説明リクエストはオンライン予測リクエストと同じ形式で、同様のレスポンスを返します。唯一の違いは、オンライン説明レスポンスには予測のほかに特徴アトリビューションが含まれる点です。

オンライン予測リクエストを送信する

gcloud

次の例では、gcloud ai endpoints predict コマンドを使用します。

  1. ローカル環境のファイルに書き込むには、次の JSON オブジェクトを作成します。ファイル名は任意です。この例では、request.json という名前を使用しています。

    {
     "instances": INSTANCES
    }
    

    次のように置き換えます。

    • INSTANCES: 予測を取得するインスタンスの JSON 配列。各インスタンスの形式は、トレーニング済みの ML モデルが想定する入力によって異なります。詳細については、オンライン予測の入力形式をご覧ください。

  2. 次のコマンドを実行します。

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

    次のように置き換えます。

    • ENDPOINT_ID: エンドポイントの ID。
    • LOCATION_ID: Vertex AI を使用するリージョン。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID。
  • INSTANCES: 予測を取得するインスタンスの JSON 配列。各インスタンスの形式は、トレーニング済みの ML モデルが想定する入力によって異なります。詳細については、オンライン予測の入力形式をご覧ください。

HTTP メソッドと URL:

POST http://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 \
"http://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 "http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:predict" | Select-Object -Expand Content
成功すると、次のような JSON レスポンスが返されます。ただし、レスポンスでは次の置換が行われています。
  • PREDICTIONS: リクエスト本文に含めたインスタンスごとに 1 つの予測が存在する JSON 配列。
  • DEPLOYED_MODEL_ID: 予測を行った DeployedModel の ID。
{
  "predictions": PREDICTIONS,
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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 {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      ListValue.Builder listValue = ListValue.newBuilder();
      JsonFormat.parser().merge(instance, listValue);
      List<Value> instanceList = listValue.getValuesList();

      PredictRequest predictRequest =
          PredictRequest.newBuilder()
              .setEndpoint(endpointName.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.getDeployedModelId());
      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        System.out.format("\tPrediction: %s\n", prediction);
      }
    }
  }
}

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 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
    --request REQUEST
  • image.jpeg ファイルに保存されている画像と適切な Content-Type ヘッダーを使用して予測をリクエストするには:

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

    次のように置き換えます。

    • ENDPOINT_ID: エンドポイントの ID。
    • LOCATION_ID: Vertex AI を使用するリージョン。
    • REQUEST: 予測を取得するリクエストのコンテンツ。リクエストの形式は、カスタム コンテナが想定するものによって異なります。JSON オブジェクトとは限りません。

Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Python API リファレンス ドキュメントをご覧ください。

# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for RawPredict
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.

# To install the latest published package dependency, execute the following:
#   python3 -m pip install google-cloud-aiplatform

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 配列。各インスタンスの形式は、トレーニング済みの ML モデルが想定する入力によって異なります。詳細については、オンライン予測の入力形式をご覧ください。

  2. 次のコマンドを実行します。

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

    次のように置き換えます。

    • ENDPOINT_ID: エンドポイントの ID。
    • LOCATION_ID: Vertex AI を使用するリージョン。

    必要に応じて、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: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID。
  • INSTANCES: 予測を取得するインスタンスの JSON 配列。各インスタンスの形式は、トレーニング済みの ML モデルが想定する入力によって異なります。詳細については、オンライン予測の入力形式をご覧ください。

HTTP メソッドと URL:

POST http://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 \
"http://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 "http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:explain" | Select-Object -Expand Content
成功すると、次のような JSON レスポンスが返されます。ただし、レスポンスでは次の置換が行われています。
  • PREDICTIONS: リクエスト本文に含めたインスタンスごとに 1 つの予測が存在する JSON 配列。
  • EXPLANATIONS: 説明の JSON 配列(予測ごとに 1 つ)。
  • 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)

次のステップ