動画動作認識モデルから予測を取得する

このページでは、Google Cloud コンソールまたは Vertex AI API を使用して、動画動作認識モデルからバッチ予測を取得する方法について説明します。バッチ予測は非同期リクエストです。エンドポイントにモデルをデプロイすることなく、モデルリソースからバッチ予測を直接リクエストします。

AutoML 動画モデルはオンライン予測をサポートしていません。

バッチ予測を取得する

バッチ予測リクエストでは、入力ソースと、Vertex AI が予測結果を格納する出力先を指定します。

入力データの要件

一括リクエストの入力では、予測用のモデルに送信するアイテムを指定します。AutoML 動画モデルタイプのバッチ予測では、JSON Lines ファイルを使用して予測を行う動画のリストを指定し、JSON Lines ファイルを Cloud Storage バケットに保存します。timeSegmentEnd フィールドに Infinity を指定すると、動画の終了を指定できます。次のサンプルは、入力 JSON Lines ファイルの 1 行を示しています。

{'content': 'gs://sourcebucket/datasets/videos/source_video.mp4', 'mimeType': 'video/mp4', 'timeSegmentStart': '0.0s', 'timeSegmentEnd': '2.366667s'}

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

バッチ予測リクエストの場合、Google Cloud Console または 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(省略可): モデルは、信頼スコアがこの値以上の予測のみを返します。
  • 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_ID/locations/LOCATION_ID/models/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
    },
    "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/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT_NUMBER/locations/us-central1/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 を使用してバッチジョブのステータスをポーリングできます。

Java

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

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

import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.protobuf.Value;
import java.io.IOException;

public class CreateBatchPredictionJobVideoActionRecognitionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String model = "MODEL";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobVideoActionRecognitionSample(
        project, displayName, model, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobVideoActionRecognitionSample(
      String project,
      String displayName,
      String model,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // 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 (JobServiceClient client = JobServiceClient.create(settings)) {
      Value modelParameters = ValueConverter.EMPTY_VALUE;
      GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
      BatchPredictionJob.InputConfig inputConfig =
          BatchPredictionJob.InputConfig.newBuilder()
              .setInstancesFormat("jsonl")
              .setGcsSource(gcsSource)
              .build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      BatchPredictionJob.OutputConfig outputConfig =
          BatchPredictionJob.OutputConfig.newBuilder()
              .setPredictionsFormat("jsonl")
              .setGcsDestination(gcsDestination)
              .build();

      String modelName = ModelName.of(project, location, model).toString();

      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(displayName)
              .setModel(modelName)
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      LocationName parent = LocationName.of(project, location);
      BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
      System.out.format("response: %s\n", response);
      System.out.format("\tName: %s\n", response.getName());
    }
  }
}

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、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 バケットに予測の出力が保存されます。

バッチ予測結果の例

動画動作認識モデルによるバッチ予測の例を以下に示します。

{
  "instance": {
   "content": "gs://bucket/video.mp4",
    "mimeType": "video/mp4",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s"
  }
  "prediction": [{
    "id": "1",
    "displayName": "swing",
    "timeSegmentStart": "1.2s",
    "timeSegmentEnd": "1.2s",
    "confidence": 0.7
  }, {
    "id": "2",
    "displayName": "jump",
    "timeSegmentStart": "3.4s",
    "timeSegmentEnd": "3.4s",
    "confidence": 0.5
  }]
}