画像オブジェクト検出モデルから予測を取得する

このページでは、Google Cloud コンソールまたは Vertex AI API を使用して、画像オブジェクト検出モデルからオンライン(リアルタイム)予測とバッチ予測を取得する方法について説明します。

オンライン予測とバッチ予測の違い

オンライン予測は、モデルのエンドポイントに対して行われる同期リクエストです。アプリケーションの入力に応じてリクエストを行う場合や、タイムリーな推論が必要な場合は、オンライン予測を使用します。

バッチ予測は非同期リクエストです。エンドポイントにモデルをデプロイすることなく、モデルリソースからバッチ予測を直接リクエストします。画像データで、すぐにレスポンスを必要とせず 1 回のリクエストで累積データを処理したい場合は、バッチ予測を使用します。

オンライン予測を取得する

エンドポイントにモデルをデプロイする

オンライン予測用にモデルを配信する前に、モデルをエンドポイントにデプロイする必要があります。モデルのデプロイでは、少ないレイテンシでオンライン予測を提供できるように、モデルに物理リソースを関連付けます。

1 つのエンドポイントに複数のモデルをデプロイすることも、モデルを複数のエンドポイントにデプロイすることもできます。モデルのデプロイにおけるオプションとユースケースの詳細については、モデルのデプロイについてをご覧ください。

モデルをデプロイするには、次のいずれかの方法を使用します。

Google Cloud コンソール

  1. Google Cloud コンソールの [Vertex AI] セクションで、[モデル] ページに移動します。

    [モデル] ページに移動

  2. デプロイするモデルの名前をクリックして、詳細ページを開きます。

  3. [デプロイとテスト] タブを選択します。

    モデルがいずれかのエンドポイントにデプロイされている場合は、[モデルのデプロイ] セクションに一覧表示されます。

  4. [エンドポイントへのデプロイ] をクリックします。

  5. 新しいエンドポイントにモデルをデプロイするには、[新しいエンドポイントを作成する] を選択し、新しいエンドポイントの名前を指定します。モデルを既存のエンドポイントにデプロイするには、[既存のエンドポイントに追加] を選択して、プルダウン リストからエンドポイントを選択します。

    1 つのエンドポイントに複数のモデルを追加することも、モデルを複数のエンドポイントに追加することもできます。詳細

  6. 1 つ以上のモデルがデプロイされている既存のエンドポイントにモデルをデプロイする場合は、すべての割合の合計が 100% になるように、デプロイするモデルとデプロイ済みのモデルのトラフィック分割の割合を更新する必要があります。

  7. [AutoML Image] を選択して、次のように構成します。

    1. モデルを新しいエンドポイントにデプロイする場合は、トラフィック分割を 100 にします。それ以外の場合は、合計が 100 になるように、エンドポイントにあるすべてのモデルのトラフィック分割値を調整します。

    2. モデルのコンピューティング ノードの数を入力します。

      これは、このモデルで使用可能なノードの数になります。予測トラフィックがなくても、ノードに課金されます。料金ページをご覧ください。

    3. 予測ロギングのデフォルト設定を変更する方法をご確認ください。

    4. 分類モデルのみ(省略可): [説明可能性のオプション] セクションで、[このモデルの特徴アトリビューションを有効にする] を選択して、Vertex Explainable AI を有効にします。既存の可視化設定をそのまま使用するか、新しい値を選択して [完了] をクリックします。

      Vertex Explainable AI が構成された AutoML 画像分類モデルのデプロイと説明付きの予測の実行はオプションです。デプロイ時に Vertex Explainable AI を有効にすると、デプロイされたノード数とデプロイ時間に基づいて追加費用が発生します。詳細は料金をご覧ください。

    5. モデルの [完了] をクリックします。すべてのトラフィック分割の割合が正しい場合は、[続行] をクリックします。

      モデルがデプロイされるリージョンが表示されます。これは、モデルを作成したリージョンにする必要があります。

    6. [デプロイ] をクリックして、エンドポイントにモデルをデプロイします。

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 メソッドと URL:

POST https://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();

Vertex AI SDK for Python

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Vertex AI SDK for Python 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 メソッドと URL:

GET https://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 コマンドを使用しています。

次の例では、複数の DeployedModel リソース間でトラフィックを分割せずに ModelEndpoint にデプロイします。

後述のコマンドデータを使用する前に、次のように置き換えます。

  • ENDPOINT_ID: エンドポイントの ID。
  • LOCATION_ID: Vertex AI を使用するリージョン。
  • MODEL_ID: デプロイするモデルの ID。
  • DEPLOYED_MODEL_NAME: DeployedModel の名前。DeployedModelModel の表示名を使用することもできます。
  • 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 \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=100

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=100

Windows(cmd.exe)

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=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)

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
 

REST

モデルをデプロイします。

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

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID。
  • MODEL_ID: デプロイするモデルの ID。
  • DEPLOYED_MODEL_NAME: DeployedModel の名前。DeployedModelModel の表示名を使用することもできます。
  • MIN_REPLICA_COUNT: このデプロイの最小ノード数。ノード数は、予測負荷に応じてノードの最大数まで増減できますが、この数より少なくすることはできません。
  • MAX_REPLICA_COUNT: このデプロイの最大ノード数。ノード数は、予測負荷に応じてこのノード数まで増減に応じて増減できますが、最大値を超えることはできません。
  • TRAFFIC_SPLIT_THIS_MODEL: このオペレーションでデプロイするモデルにルーティングされる、このエンドポイントへの予測トラフィックの割合。デフォルトは 100 です。すべてのトラフィックの割合の合計は 100 になる必要があります。トラフィック分割の詳細
  • DEPLOYED_MODEL_ID_N: 省略可。他のモデルがこのエンドポイントにデプロイされている場合は、すべての割合の合計が 100 になるように、トラフィック分割の割合を更新する必要があります。
  • TRAFFIC_SPLIT_MODEL_N: デプロイされたモデル ID キーのトラフィック分割の割合値。
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "deployedModel": {
    "model": "projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "automaticResources": {
       "minReplicaCount": MIN_REPLICA_COUNT,
       "maxReplicaCount": MAX_REPLICA_COUNT
     }
  },
  "trafficSplit": {
    "0": TRAFFIC_SPLIT_THIS_MODEL,
    "DEPLOYED_MODEL_ID_1": TRAFFIC_SPLIT_MODEL_1,
    "DEPLOYED_MODEL_ID_2": TRAFFIC_SPLIT_MODEL_2
  },
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-19T17:53:16.502088Z",
      "updateTime": "2020-10-19T17:53:16.502088Z"
    }
  }
}

Java

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

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.aiplatform.v1.AutomaticResources;
import com.google.cloud.aiplatform.v1.DedicatedResources;
import com.google.cloud.aiplatform.v1.DeployModelOperationMetadata;
import com.google.cloud.aiplatform.v1.DeployModelResponse;
import com.google.cloud.aiplatform.v1.DeployedModel;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.stub.EndpointServiceStubSettings;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.threeten.bp.Duration;

public class DeployModelSample {

  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 deployedModelDisplayName = "YOUR_DEPLOYED_MODEL_DISPLAY_NAME";
    String endpointId = "YOUR_ENDPOINT_NAME";
    String modelId = "YOUR_MODEL_ID";
    int timeout = 900;
    deployModelSample(project, deployedModelDisplayName, endpointId, modelId, timeout);
  }

  static void deployModelSample(
      String project,
      String deployedModelDisplayName,
      String endpointId,
      String modelId,
      int timeout)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {

    // Set long-running operations (LROs) timeout
    final OperationTimedPollAlgorithm operationTimedPollAlgorithm =
        OperationTimedPollAlgorithm.create(
            RetrySettings.newBuilder()
                .setInitialRetryDelay(Duration.ofMillis(5000L))
                .setRetryDelayMultiplier(1.5)
                .setMaxRetryDelay(Duration.ofMillis(45000L))
                .setInitialRpcTimeout(Duration.ZERO)
                .setRpcTimeoutMultiplier(1.0)
                .setMaxRpcTimeout(Duration.ZERO)
                .setTotalTimeout(Duration.ofSeconds(timeout))
                .build());

    EndpointServiceStubSettings.Builder endpointServiceStubSettingsBuilder =
        EndpointServiceStubSettings.newBuilder();
    endpointServiceStubSettingsBuilder
        .deployModelOperationSettings()
        .setPollingAlgorithm(operationTimedPollAlgorithm);
    EndpointServiceStubSettings endpointStubSettings = endpointServiceStubSettingsBuilder.build();
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.create(endpointStubSettings);
    endpointServiceSettings =
        endpointServiceSettings.toBuilder()
            .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";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);
      // key '0' assigns traffic for the newly deployed model
      // Traffic percentage values must add up to 100
      // Leave dictionary empty if endpoint should not accept any traffic
      Map<String, Integer> trafficSplit = new HashMap<>();
      trafficSplit.put("0", 100);
      ModelName modelName = ModelName.of(project, location, modelId);
      AutomaticResources automaticResourcesInput =
          AutomaticResources.newBuilder().setMinReplicaCount(1).setMaxReplicaCount(1).build();
      DeployedModel deployedModelInput =
          DeployedModel.newBuilder()
              .setModel(modelName.toString())
              .setDisplayName(deployedModelDisplayName)
              .setAutomaticResources(automaticResourcesInput)
              .build();

      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> deployModelResponseFuture =
          endpointServiceClient.deployModelAsync(endpointName, deployedModelInput, trafficSplit);
      System.out.format(
          "Operation name: %s\n", deployModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      DeployModelResponse deployModelResponse = deployModelResponseFuture.get(20, TimeUnit.MINUTES);

      System.out.println("Deploy Model Response");
      DeployedModel deployedModel = deployModelResponse.getDeployedModel();
      System.out.println("\tDeployed Model");
      System.out.format("\t\tid: %s\n", deployedModel.getId());
      System.out.format("\t\tmodel: %s\n", deployedModel.getModel());
      System.out.format("\t\tDisplay Name: %s\n", deployedModel.getDisplayName());
      System.out.format("\t\tCreate Time: %s\n", deployedModel.getCreateTime());

      DedicatedResources dedicatedResources = deployedModel.getDedicatedResources();
      System.out.println("\t\tDedicated Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", dedicatedResources.getMinReplicaCount());

      MachineSpec machineSpec = dedicatedResources.getMachineSpec();
      System.out.println("\t\t\tMachine Spec");
      System.out.format("\t\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      AutomaticResources automaticResources = deployedModel.getAutomaticResources();
      System.out.println("\t\tAutomatic Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", automaticResources.getMinReplicaCount());
      System.out.format("\t\t\tMax Replica Count: %s\n", automaticResources.getMaxReplicaCount());
    }
  }
}

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 modelId = "YOUR_MODEL_ID";
// const endpointId = 'YOUR_ENDPOINT_ID';
// const deployedModelDisplayName = 'YOUR_DEPLOYED_MODEL_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const modelName = `projects/${project}/locations/${location}/models/${modelId}`;
const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
// 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 deployModel() {
  // Configure the parent resource
  // key '0' assigns traffic for the newly deployed model
  // Traffic percentage values must add up to 100
  // Leave dictionary empty if endpoint should not accept any traffic
  const trafficSplit = {0: 100};
  const deployedModel = {
    // format: 'projects/{project}/locations/{location}/models/{model}'
    model: modelName,
    displayName: deployedModelDisplayName,
    automaticResources: {minReplicaCount: 1, maxReplicaCount: 1},
  };
  const request = {
    endpoint,
    deployedModel,
    trafficSplit,
  };

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

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

  console.log('Deploy model response');
  const modelDeployed = result.deployedModel;
  console.log('\tDeployed model');
  if (!modelDeployed) {
    console.log('\t\tId : {}');
    console.log('\t\tModel : {}');
    console.log('\t\tDisplay name : {}');
    console.log('\t\tCreate time : {}');

    console.log('\t\tDedicated resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMachine spec {}');
    console.log('\t\t\t\tMachine type : {}');
    console.log('\t\t\t\tAccelerator type : {}');
    console.log('\t\t\t\tAccelerator count : {}');

    console.log('\t\tAutomatic resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMax replica count : {}');
  } else {
    console.log(`\t\tId : ${modelDeployed.id}`);
    console.log(`\t\tModel : ${modelDeployed.model}`);
    console.log(`\t\tDisplay name : ${modelDeployed.displayName}`);
    console.log(`\t\tCreate time : ${modelDeployed.createTime}`);

    const dedicatedResources = modelDeployed.dedicatedResources;
    console.log('\t\tDedicated resources');
    if (!dedicatedResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMachine spec {}');
      console.log('\t\t\t\tMachine type : {}');
      console.log('\t\t\t\tAccelerator type : {}');
      console.log('\t\t\t\tAccelerator count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${dedicatedResources.minReplicaCount}`
      );
      const machineSpec = dedicatedResources.machineSpec;
      console.log('\t\t\tMachine spec');
      console.log(`\t\t\t\tMachine type : ${machineSpec.machineType}`);
      console.log(
        `\t\t\t\tAccelerator type : ${machineSpec.acceleratorType}`
      );
      console.log(
        `\t\t\t\tAccelerator count : ${machineSpec.acceleratorCount}`
      );
    }

    const automaticResources = modelDeployed.automaticResources;
    console.log('\t\tAutomatic resources');
    if (!automaticResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMax replica count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${automaticResources.minReplicaCount}`
      );
      console.log(
        `\t\t\tMax replica count : \
          ${automaticResources.maxReplicaCount}`
      );
    }
  }
}
deployModel();

Vertex AI SDK for Python

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

def deploy_model_with_automatic_resources_sample(
    project,
    location,
    model_name: str,
    endpoint: Optional[aiplatform.Endpoint] = None,
    deployed_model_display_name: Optional[str] = None,
    traffic_percentage: Optional[int] = 0,
    traffic_split: Optional[Dict[str, int]] = None,
    min_replica_count: int = 1,
    max_replica_count: int = 1,
    metadata: Optional[Sequence[Tuple[str, str]]] = (),
    sync: bool = True,
):
    """
    model_name: A fully-qualified model resource name or model ID.
          Example: "projects/123/locations/us-central1/models/456" or
          "456" when project and location are initialized or passed.
    """

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

    model = aiplatform.Model(model_name=model_name)

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    return model

予測ロギングのデフォルト設定を変更する方法をご確認ください。

オペレーションのステータスを取得する

一部のリクエストでは、完了までに長時間かかるオペレーションが実行されます。このようなリクエストではオペレーション名が返されます。そのオペレーション名を使用して、オペレーションのステータス確認やキャンセルを行うことができます。Vertex AI には、長時間実行オペレーションに対して呼び出しを行うためのヘルパー メソッドが用意されています。詳細については、長時間実行オペレーションによる作業をご覧ください。

デプロイされたモデルを使用してオンライン予測を行う

オンライン予測を行うには、モデルに分析のためのテスト項目を 1 つ以上送信し、モデルがモデルの目的に基づいて結果を返します。予測結果の詳細については、結果を解釈するをご覧ください。

コンソール

Google Cloud コンソールを使用してオンライン予測をリクエストします。モデルはエンドポイントにデプロイする必要があります。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[モデル] ページに移動します。

    [モデル] ページに移動

  2. モデルのリストで、予測をリクエストするモデルの名前をクリックします。

  3. [デプロイとテスト] タブを選択します。

  4. [モデルのテスト] セクションで、予測をリクエストするテスト項目を追加します。

    画像目的の AutoML モデルでは、画像をアップロードして予測をリクエストする必要があります。

    ローカル特徴量の重要度については、説明を取得するをご覧ください。

    予測が完了すると、Vertex AI がコンソールに結果を返します。

API

Vertex AI API を使用してオンライン予測をリクエストします。モデルはエンドポイントにデプロイする必要があります。

画像データタイプの目的としては、分類とオブジェクト検出があります。

Edge モデル予測: AutoML 画像の Edge モデルを予測に使用する場合は、予測リクエストを送信する前に、JPEG 以外の予測ファイルを JPEG ファイルに変換する必要があります。

gcloud

  1. 次の内容のファイルを request.json という名前で作成します。

    {
      "instances": [{
        "content": "CONTENT"
      }],
      "parameters": {
        "confidenceThreshold": THRESHOLD_VALUE,
        "maxPredictions": MAX_PREDICTIONS
      }
    }
    

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

    • CONTENT: base64 でエンコードされた画像コンテンツ。
    • THRESHOLD_VALUE(省略可): モデルは、信頼スコアがこの値以上の予測のみを返します。
    • MAX_PREDICTIONS(省略可): モデルが返す最高の信頼スコアを持つ予測の最大数。
  2. 次のコマンドを実行します。

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

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

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

REST

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

  • LOCATION_ID: エンドポイントが配置されているリージョン。例: us-central1
  • PROJECT_ID: 実際のプロジェクト ID
  • ENDPOINT_ID: エンドポイントの ID。
  • CONTENT: base64 でエンコードされた画像コンテンツ。
  • THRESHOLD_VALUE(省略可): モデルは、信頼スコアがこの値以上の予測のみを返します。
  • MAX_PREDICTIONS(省略可): モデルが返す最高の信頼スコアを持つ予測の最大数。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "instances": [{
    "content": "CONTENT"
  }],
  "parameters": {
    "confidenceThreshold": THRESHOLD_VALUE,
    "maxPredictions": MAX_PREDICTIONS
  }
}

リクエストを送信するには、次のいずれかのオプションを選択します。

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": [
    {
      "confidences": [
        0.975873291,
        0.972160876,
        0.879488528,
        0.866532683,
        0.686478078
      ],
      "displayNames": [
        "Salad",
        "Salad",
        "Tomato",
        "Tomato",
        "Salad"
      ],
      "ids": [
        "7517774415476555776",
        "7517774415476555776",
        "2906088397049167872",
        "2906088397049167872",
        "7517774415476555776"
      ],
      "bboxes": [
        [
          0.0869686604,
          0.977020741,
          0.395135701,
          1
        ],
        [
          0,
          0.488701463,
          0.00157663226,
          0.512249
        ],
        [
          0.361617863,
          0.509664357,
          0.772928834,
          0.914706349
        ],
        [
          0.310678929,
          0.45781514,
          0.565507233,
          0.711237729
        ],
        [
          0.584359646,
          1,
          0.00116168708,
          0.130817384
        ]
      ]
    }
  ],
  "deployedModelId": "3860570043075002368"
}

Java

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

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


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.cloud.aiplatform.v1.schema.predict.instance.ImageObjectDetectionPredictionInstance;
import com.google.cloud.aiplatform.v1.schema.predict.params.ImageObjectDetectionPredictionParams;
import com.google.cloud.aiplatform.v1.schema.predict.prediction.ImageObjectDetectionPredictionResult;
import com.google.protobuf.Value;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class PredictImageObjectDetectionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String fileName = "YOUR_IMAGE_FILE_PATH";
    String endpointId = "YOUR_ENDPOINT_ID";
    predictImageObjectDetection(project, fileName, endpointId);
  }

  static void predictImageObjectDetection(String project, String fileName, String endpointId)
      throws IOException {
    PredictionServiceSettings settings =
        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(settings)) {
      String location = "us-central1";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      byte[] contents = Base64.getEncoder().encode(Files.readAllBytes(Paths.get(fileName)));
      String content = new String(contents, StandardCharsets.UTF_8);

      ImageObjectDetectionPredictionParams params =
          ImageObjectDetectionPredictionParams.newBuilder()
              .setConfidenceThreshold((float) (0.5))
              .setMaxPredictions(5)
              .build();

      ImageObjectDetectionPredictionInstance instance =
          ImageObjectDetectionPredictionInstance.newBuilder().setContent(content).build();

      List<Value> instances = new ArrayList<>();
      instances.add(ValueConverter.toValue(instance));

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, ValueConverter.toValue(params));
      System.out.println("Predict Image Object Detection Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {

        ImageObjectDetectionPredictionResult.Builder resultBuilder =
            ImageObjectDetectionPredictionResult.newBuilder();

        ImageObjectDetectionPredictionResult result =
            (ImageObjectDetectionPredictionResult)
                ValueConverter.fromValue(resultBuilder, prediction);

        for (int i = 0; i < result.getIdsCount(); i++) {
          System.out.printf("\tDisplay name: %s\n", result.getDisplayNames(i));
          System.out.printf("\tConfidences: %f\n", result.getConfidences(i));
          System.out.printf("\tIDs: %d\n", result.getIds(i));
          System.out.printf("\tBounding boxes: %s\n", result.getBboxes(i));
        }
      }
    }
  }
}

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 aiplatform = require('@google-cloud/aiplatform');
const {instance, params, prediction} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.predict;

// Imports the Google Cloud Prediction Service Client library
const {PredictionServiceClient} = aiplatform.v1;

// 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 predictImageObjectDetection() {
  // Configure the endpoint resource
  const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;

  const parametersObj = new params.ImageObjectDetectionPredictionParams({
    confidenceThreshold: 0.5,
    maxPredictions: 5,
  });
  const parameters = parametersObj.toValue();

  const fs = require('fs');
  const image = fs.readFileSync(filename, 'base64');
  const instanceObj = new instance.ImageObjectDetectionPredictionInstance({
    content: image,
  });

  const instanceVal = instanceObj.toValue();
  const instances = [instanceVal];
  const request = {
    endpoint,
    instances,
    parameters,
  };

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

  console.log('Predict image object detection response');
  console.log(`\tDeployed model id : ${response.deployedModelId}`);
  const predictions = response.predictions;
  console.log('Predictions :');
  for (const predictionResultVal of predictions) {
    const predictionResultObj =
      prediction.ImageObjectDetectionPredictionResult.fromValue(
        predictionResultVal
      );
    for (const [i, label] of predictionResultObj.displayNames.entries()) {
      console.log(`\tDisplay name: ${label}`);
      console.log(`\tConfidences: ${predictionResultObj.confidences[i]}`);
      console.log(`\tIDs: ${predictionResultObj.ids[i]}`);
      console.log(`\tBounding boxes: ${predictionResultObj.bboxes[i]}\n\n`);
    }
  }
}
predictImageObjectDetection();

Vertex AI SDK for Python

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

import base64

from google.cloud import aiplatform
from google.cloud.aiplatform.gapic.schema import predict


def predict_image_object_detection_sample(
    project: str,
    endpoint_id: str,
    filename: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # 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.gapic.PredictionServiceClient(client_options=client_options)
    with open(filename, "rb") as f:
        file_content = f.read()

    # The format of each instance should conform to the deployed model's prediction input schema.
    encoded_content = base64.b64encode(file_content).decode("utf-8")
    instance = predict.instance.ImageObjectDetectionPredictionInstance(
        content=encoded_content,
    ).to_value()
    instances = [instance]
    # See gs://google-cloud-aiplatform/schema/predict/params/image_object_detection_1.0.0.yaml for the format of the parameters.
    parameters = predict.params.ImageObjectDetectionPredictionParams(
        confidence_threshold=0.5,
        max_predictions=5,
    ).to_value()
    endpoint = client.endpoint_path(
        project=project, location=location, endpoint=endpoint_id
    )
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )
    print("response")
    print(" deployed_model_id:", response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/image_object_detection_1.0.0.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:", dict(prediction))

バッチ予測を取得する

バッチ予測リクエストでは、入力ソースと、Vertex AI が予測結果を格納する出力先を指定します。AutoML 画像モデルタイプのバッチ予測を行うには、入力 JSON Lines ファイルと、出力を保存する Cloud Storage バケットの名前が必要です。

入力データの要件

一括リクエストの入力では、予測用のモデルに送信するアイテムを指定します。画像オブジェクト検出モデルでは、予測を行う画像のリストを JSON Lines ファイルに指定し、このファイルを Cloud Storage バケットに格納できます。次のサンプルは、入力 JSON Lines ファイルの 1 行を示しています。

{"content": "gs://sourcebucket/datasets/images/source_image.jpg", "mimeType": "image/jpeg"}

バッチ予測をリクエストする

バッチ予測リクエストの場合、Google Cloud コンソールまたは Vertex AI API を使用できます。送信した入力アイテム数によっては、バッチ予測タスクが完了するまでに時間がかかることがあります。

Google Cloud コンソール

Google Cloud コンソールを使用してバッチ予測をリクエストします。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[バッチ予測] ページに移動します。

    [バッチ予測] ページに移動

  2. [作成] をクリックして [新しいバッチ予測] ウィンドウを開き、次の操作を行います。

    1. バッチ予測の名前を入力します。
    2. [モデル名] で、このバッチ予測に使用するモデルの名前を選択します。
    3. [転送元のパス] に、JSON Lines 入力ファイルがある Cloud Storage のロケーションを指定します。
    4. [宛先のパス] に、バッチ予測結果が保存される Cloud Storage のロケーションを指定します。出力形式はモデルの目標によって決まります。画像目的の AutoML モデルは、JSON Lines ファイルを出力します。

API

Vertex AI API を使用してバッチ予測リクエストを送信します。

REST

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

  • LOCATION_ID: モデルを保存し、バッチ予測ジョブを実行するリージョン。例: us-central1
  • PROJECT_ID: 実際のプロジェクト ID
  • BATCH_JOB_NAME: バッチジョブの表示名
  • MODEL_ID: 予測に使用するモデルの ID
  • THRESHOLD_VALUE(省略可): Vertex AI は、この値以上の信頼スコアを持つ予測のみを返します。デフォルトは 0.0 です。
  • MAX_PREDICTIONS(省略可): Vertex AI が返す最高の信頼スコアを持つ予測の最大数。デフォルトは 10 です。
  • URI: 入力 JSON Lines ファイルが存在する Cloud Storage URI。
  • BUCKET: Cloud Storage バケット
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/batchPredictionJobs

リクエストの本文(JSON):

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT/locations/LOCATION/models/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
      "maxPredictions": MAX_PREDICTIONS
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

リクエストを送信するには、次のいずれかのオプションを選択します。

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/batchPredictionJobs"

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/batchPredictionJobs" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}

ジョブ stateJOB_STATE_SUCCEEDED になるまで、BATCH_JOB_ID を使用してバッチジョブのステータスをポーリングできます。

Vertex AI SDK for Python

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

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

バッチ予測の結果を取得する

Vertex AI は、指定された宛先にバッチ予測の出力を送信します。

バッチ予測タスクが完了すると、リクエストで指定した Cloud Storage バケットに予測の出力が保存されます。

バッチ予測結果の例

以下は、画像オブジェクト検出モデルによるバッチ予測の例です。

重要: 境界ボックスは、次のように指定します。

"bboxes": [ [xMin, xMax, yMin, yMax], ...]

ここで、xMinxMax は x の最小値と最大値、 yMinyMax は y の最小値と最大値です。

{
  "instance": {"content": "gs://bucket/image.jpg", "mimeType": "image/jpeg"},
  "prediction": {
    "ids": [1, 2],
    "displayNames": ["cat", "dog"],
    "bboxes":  [
      [0.1, 0.2, 0.3, 0.4],
      [0.2, 0.3, 0.4, 0.5]
    ],
    "confidences": [0.7, 0.5]
  }
}