動画動作認識モデルのトレーニング用のデータセットを作成する

このページでは、動作認識モデルのトレーニングを開始できるように、動画データから Vertex AI データセットを作成する方法について説明します。データセットは、Google Cloud コンソールまたは Vertex AI API を使用して作成できます。

空のデータセットを作成してデータをインポートまたは関連付ける

Google Cloud コンソール

次の手順で空のデータセットを作成し、データをインポートまたは関連付けます。

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

    [データセット] ページに移動

  2. [作成] をクリックして [データセットを作成] の詳細ページを開きます。
  3. [データセット名] フィールドを変更して、わかりやすいデータセットの表示名を作成します。
  4. [動画] タブを選択します。
  5. [動画動作認識] を選択します。
  6. [リージョン] プルダウン リストからリージョンを選択します。
  7. [作成] をクリックして空のデータセットを作成し、データの [インポート] ページに進みます。
  8. [インポート方法を選択] セクションで、次のいずれかのオプションを選択します。

    パソコンからデータをアップロードする

    1. [インポート方法を選択] セクションで、パソコンからデータのアップロードを選択します。
    2. [ファイルを選択] をクリックし、Cloud Storage バケットにアップロードするすべてのローカル ファイルを選択します。
    3. [Cloud Storage パスの選択] セクションで、[参照] をクリックして、データをアップロードする Cloud Storage バケットのロケーションを選択します。

    パソコンからインポート ファイルをアップロードする

    1. [パソコンからインポート ファイルをアップロード] をクリックします。
    2. [ファイルを選択] をクリックし、Cloud Storage バケットにアップロードするローカル インポート ファイルを選択します。
    3. [Cloud Storage パスの選択] セクションで、[参照] をクリックして、ファイルをアップロードする Cloud Storage バケットのロケーションを選択します。

    インポート ファイルを Cloud Storage から選択する

    1. [インポート ファイルを Cloud Storage から選択] をクリックします。
    2. [Cloud Storage パスの選択] セクションで、[参照] をクリックして Cloud Storage のインポート ファイルを選択します。
  9. [続行] をクリックします。

    データのサイズによっては、データのインポートに数時間かかる場合があります。このタブを閉じて、後で戻ってくることもできます。データがインポートされると、メールが届きます。

API

ML モデルを作成するには、最初にトレーニングに使用する代表的なデータの収集が必要です。データのインポート後、変更を加え、モデル トレーニングを開始できます。

データセットを作成する

次のサンプルを使用して、データのデータセットを作成します。

REST

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

  • LOCATION: データセットが格納されるリージョン。これは、データセット リソースをサポートしているリージョンにする必要があります。例: us-central1利用可能なロケーションの一覧をご覧ください。
  • PROJECT: 実際のプロジェクト ID
  • DATASET_NAME: データセットの名前。
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets

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

{
  "display_name": "DATASET_NAME",
  "metadata_schema_uri": "gs://google-cloud-aiplatform/schema/dataset/metadata/video_1.0.0.yaml"
}

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

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-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets"

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-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets" | Select-Object -Expand Content

出力は次のようになります。レスポンスの OPERATION_ID を使用して、オペレーションのステータスを取得できます。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateDatasetOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-07-07T21:27:35.964882Z",
      "updateTime": "2020-07-07T21:27:35.964882Z"
    }
  }
}

Terraform

次のサンプルでは、google_vertex_ai_dataset Terraform リソースを使用して、video-dataset という名前の動画データセットを作成します。

Terraform 構成を適用または削除する方法については、基本的な Terraform コマンドをご覧ください。

resource "google_vertex_ai_dataset" "video_dataset" {
  display_name        = "video-dataset"
  metadata_schema_uri = "gs://google-cloud-aiplatform/schema/dataset/metadata/video_1.0.0.yaml"
  region              = "us-central1"
}

Java

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

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateDatasetOperationMetadata;
import com.google.cloud.aiplatform.v1.Dataset;
import com.google.cloud.aiplatform.v1.DatasetServiceClient;
import com.google.cloud.aiplatform.v1.DatasetServiceSettings;
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 CreateDatasetVideoSample {

  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 datasetVideoDisplayName = "YOUR_DATASET_VIDEO_DISPLAY_NAME";
    createDatasetSample(datasetVideoDisplayName, project);
  }

  static void createDatasetSample(String datasetVideoDisplayName, String project)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    DatasetServiceSettings datasetServiceSettings =
        DatasetServiceSettings.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 (DatasetServiceClient datasetServiceClient =
        DatasetServiceClient.create(datasetServiceSettings)) {
      String location = "us-central1";
      String metadataSchemaUri =
          "gs://google-cloud-aiplatform/schema/dataset/metadata/video_1.0.0.yaml";
      LocationName locationName = LocationName.of(project, location);
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(datasetVideoDisplayName)
              .setMetadataSchemaUri(metadataSchemaUri)
              .build();

      OperationFuture<Dataset, CreateDatasetOperationMetadata> datasetFuture =
          datasetServiceClient.createDatasetAsync(locationName, dataset);
      System.out.format("Operation name: %s\n", datasetFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Dataset datasetResponse = datasetFuture.get(300, TimeUnit.SECONDS);

      System.out.println("Create Dataset Video Response");
      System.out.format("Name: %s\n", datasetResponse.getName());
      System.out.format("Display Name: %s\n", datasetResponse.getDisplayName());
      System.out.format("Metadata Schema Uri: %s\n", datasetResponse.getMetadataSchemaUri());
      System.out.format("Metadata: %s\n", datasetResponse.getMetadata());
      System.out.format("Create Time: %s\n", datasetResponse.getCreateTime());
      System.out.format("Update Time: %s\n", datasetResponse.getUpdateTime());
      System.out.format("Labels: %s\n", datasetResponse.getLabelsMap());
    }
  }
}

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 datasetDisplayName = "YOUR_DATASTE_DISPLAY_NAME";
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

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

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

// Instantiates a client
const datasetServiceClient = new DatasetServiceClient(clientOptions);

async function createDatasetVideo() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  // Configure the dataset resource
  const dataset = {
    displayName: datasetDisplayName,
    metadataSchemaUri:
      'gs://google-cloud-aiplatform/schema/dataset/metadata/video_1.0.0.yaml',
  };
  const request = {
    parent,
    dataset,
  };

  // Create Dataset Request
  const [response] = await datasetServiceClient.createDataset(request);
  console.log(`Long running operation: ${response.name}`);

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

  console.log('Create dataset video response');
  console.log(`Name : ${result.name}`);
  console.log(`Display name : ${result.displayName}`);
  console.log(`Metadata schema uri : ${result.metadataSchemaUri}`);
  console.log(`Metadata : ${JSON.stringify(result.metadata)}`);
  console.log(`Labels : ${JSON.stringify(result.labels)}`);
}
createDatasetVideo();

Python

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

次のサンプルでは、Vertex AI SDK for Python を使用してデータセットを作成し、データをインポートします。このサンプルコードを実行する場合は、このガイドのデータのインポート セクションをスキップできます。

この特定のサンプルでは、分類用のデータをインポートします。モデルに異なる目標がある場合は、コードを調整する必要があります。

def create_and_import_dataset_video_sample(
    project: str,
    location: str,
    display_name: str,
    src_uris: Union[str, List[str]],
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    ds = aiplatform.VideoDataset.create(
        display_name=display_name,
        gcs_source=src_uris,
        import_schema_uri=aiplatform.schema.dataset.ioformat.video.classification,
        sync=sync,
    )

    ds.wait()

    print(ds.display_name)
    print(ds.resource_name)
    return ds

データをインポートする

空のデータセットを作成したら、データセットにデータをインポートできます。Vertex AI SDK for Python を使用してデータセットを作成した場合は、データセットの作成時にデータをインポートしている可能性があります。その場合は、このセクションをスキップできます。

REST

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

  • LOCATION: データセットが格納されるリージョン。例: us-central1
  • PROJECT: 実際のプロジェクト ID
  • DATASET_ID: データセットの ID。
  • IMPORT_FILE_URI: Cloud Storage に格納されたモデル トレーニング用データ項目のリストを含む Cloud Storage 上の CSV または JSON Lines ファイルのパス。インポートできるファイル形式と制限については、動画データの準備をご覧ください。
  • OBJECTIVE: モデルの目標。classification、object_tracking、または action recognition のいずれかを指定します。
  • PROJECT_NUMBER: プロジェクトに自動生成されたプロジェクト番号

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/datasets/DATASET_ID:import

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

{
  "import_configs": [
    {
      "gcs_source": {
        "uris": "IMPORT_FILE_URI"
      },
     "import_schema_uri" : "gs://google-cloud-aiplatform/schema/dataset/ioformat/automl_video_OBJECTIVE_io_format_1.0.0.yaml"
    }
  ]
}

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

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-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/datasets/DATASET_ID:import"

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-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/datasets/DATASET_ID:import" | Select-Object -Expand Content

出力は次のようになります。レスポンスの OPERATION_ID を使用して、オペレーションのステータスを取得できます。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/datasets/DATASET_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.ImportDataOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-08T20:32:02.543801Z",
      "updateTime": "2020-10-08T20:32:02.543801Z"
    }
  }
}

Java

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

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.DatasetName;
import com.google.cloud.aiplatform.v1.DatasetServiceClient;
import com.google.cloud.aiplatform.v1.DatasetServiceSettings;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.ImportDataConfig;
import com.google.cloud.aiplatform.v1.ImportDataOperationMetadata;
import com.google.cloud.aiplatform.v1.ImportDataResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class ImportDataVideoActionRecognitionSample {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String datasetId = "DATASET_ID";
    String gcsSourceUri = "GCS_SOURCE_URI";
    importDataVideoActionRecognitionSample(project, datasetId, gcsSourceUri);
  }

  static void importDataVideoActionRecognitionSample(
      String project, String datasetId, String gcsSourceUri)
      throws IOException, ExecutionException, InterruptedException {
    DatasetServiceSettings settings =
        DatasetServiceSettings.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 (DatasetServiceClient client = DatasetServiceClient.create(settings)) {
      GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
      ImportDataConfig importConfig0 =
          ImportDataConfig.newBuilder()
              .setGcsSource(gcsSource)
              .setImportSchemaUri(
                  "gs://google-cloud-aiplatform/schema/dataset/ioformat/"
                      + "video_action_recognition_io_format_1.0.0.yaml")
              .build();
      List<ImportDataConfig> importConfigs = new ArrayList<>();
      importConfigs.add(importConfig0);
      DatasetName name = DatasetName.of(project, location, datasetId);
      OperationFuture<ImportDataResponse, ImportDataOperationMetadata> response =
          client.importDataAsync(name, importConfigs);

      // You can use OperationFuture.getInitialFuture to get a future representing the initial
      // response to the request, which contains information while the operation is in progress.
      System.out.format("Operation name: %s\n", response.getInitialFuture().get().getName());

      // OperationFuture.get() will block until the operation is finished.
      ImportDataResponse importDataResponse = response.get();
      System.out.format("importDataResponse: %s\n", importDataResponse);
    }
  }
}

Python

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

def import_data_video_action_recognition_sample(
    project: str,
    location: str,
    dataset_name: str,
    src_uris: Union[str, List[str]],
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    ds = aiplatform.VideoDataset(dataset_name=dataset_name)

    ds.import_data(
        gcs_source=src_uris,
        import_schema_uri=aiplatform.schema.dataset.ioformat.video.action_recognition,
        sync=sync,
    )

    ds.wait()

    print(ds.display_name)
    print(ds.resource_name)
    return ds

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

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