Klassifizierungsmodell für Videos trainieren

Auf dieser Seite wird gezeigt, wie Sie mithilfe der Google Cloud Console oder der Vertex AI API ein AutoML-Klassifizierungsmodell aus einem Video-Dataset trainieren.

AutoML-Modell trainieren

Google Cloud Console

  1. Rufen Sie in der Google Cloud Console im Abschnitt "Vertex AI" die Seite Datasets auf.

    Zur Seite „Datasets“

  2. Klicken Sie auf den Namen des Datasets, das Sie zum Trainieren Ihres Modells verwenden möchten, um dessen Detailseite zu öffnen.

  3. Klicken Sie auf Neues Modell trainieren.

  4. Geben Sie den Anzeigenamen für das neue Modell ein.

  5. Wenn Sie die Aufteilung Ihrer Trainingsdaten manuell festlegen möchten, maximieren Sie Erweiterte Optionen und wählen Sie eine Option für die Datenaufteilung aus. Weitere Informationen

  6. Klicken Sie auf Weiter.

  7. Wählen Sie die Modelltrainingsmethode aus.

    • AutoML ist eine gute Wahl für eine Vielzahl von Anwendungsfällen.
    • Seq2seq+ ist eine gute Wahl für Experimente. Der Algorithmus konvergiert vermutlich schneller als AutoML, da seine Architektur einfacher ist und einen kleineren Suchbereich verwendet. Unsere Experimente haben ergeben, dass Seq2Seq+ mit einem kleinen Budget und Datasets mit einer Größe von weniger als 1 GB gut funktioniert.
    Klicken Sie auf Weiter.

  8. Klicken Sie auf Training starten.

    Das Modelltraining kann viele Stunden dauern, je nach Größe und Komplexität Ihrer Daten und Ihres Trainingsbudgets, sofern Sie eines angegeben haben. Sie können diesen Tab schließen und später zu ihm zurückkehren. Wenn das Training für Ihr Modell abgeschlossen ist, erhalten eine E-Mail.

    Einige Minuten nach dem Start des Trainings können Sie die Schätzung der Knotenstunden für das Training anhand der Attribute des Modells prüfen. Wenn Sie das Training abbrechen, fallen für das aktuelle Produkt keine Kosten an.

API

Wählen Sie unten den Tab für Ihre Sprache oder Umgebung aus:

REST

Ersetzen Sie dabei folgende Werte für die Anfragedaten:

  • LOCATION: Region, in der sich das Dataset befindet und das Modell gespeichert wird. Beispiel: us-central1.
  • PROJECT: Ihre Projekt-ID.
  • MODEL_DISPLAY_NAME: Anzeigename für das neu trainierte Modell.
  • DATASET_ID: ID für das Trainings-Dataset.
  • Das filterSplit-Objekt ist optional. um die Datenaufteilung zu steuern. Weitere Informationen zur Steuerung der Datenaufteilung finden Sie unter Datenaufteilung mit REST steuern.
  • PROJECT_NUMBER: Die automatisch generierte Projektnummer Ihres Projekts

HTTP-Methode und URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/trainingPipelines

JSON-Text anfordern:

{
    "displayName": "MODE_DISPLAY_NAME",
    "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_classification_1.0.0.yaml",
    "trainingTaskInputs": {},
    "modelToUpload": {"displayName": "MODE_DISPLAY_NAME"},
    "inputDataConfig": {
      "datasetId": "DATASET_ID",
      "filterSplit": {
        "trainingFilter": "labels.ml_use = training",
        "validationFilter": "labels.ml_use = -",
        "testFilter": "labels.ml_use = test"
      }
    }
}

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/trainingPipelines/2307109646608891904",
  "displayName": "myModelName",
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_classification_1.0.0.yaml",
  "modelToUpload": {
    "displayName": "myModelName"
  },
  "state": "PIPELINE_STATE_PENDING",
  "createTime": "2020-04-18T01:22:57.479336Z",
  "updateTime": "2020-04-18T01:22:57.479336Z"
}

Java

Bevor Sie dieses Beispiel anwenden, folgen Sie den Java-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Java API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.FilterSplit;
import com.google.cloud.aiplatform.v1.FractionSplit;
import com.google.cloud.aiplatform.v1.InputDataConfig;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.PipelineServiceClient;
import com.google.cloud.aiplatform.v1.PipelineServiceSettings;
import com.google.cloud.aiplatform.v1.PredefinedSplit;
import com.google.cloud.aiplatform.v1.TimestampSplit;
import com.google.cloud.aiplatform.v1.TrainingPipeline;
import com.google.rpc.Status;
import java.io.IOException;

public class CreateTrainingPipelineVideoClassificationSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String videoClassificationDisplayName =
        "YOUR_TRAINING_PIPELINE_VIDEO_CLASSIFICATION_DISPLAY_NAME";
    String datasetId = "YOUR_DATASET_ID";
    String modelDisplayName = "YOUR_MODEL_DISPLAY_NAME";
    String project = "YOUR_PROJECT_ID";
    createTrainingPipelineVideoClassification(
        videoClassificationDisplayName, datasetId, modelDisplayName, project);
  }

  static void createTrainingPipelineVideoClassification(
      String videoClassificationDisplayName,
      String datasetId,
      String modelDisplayName,
      String project)
      throws IOException {
    PipelineServiceSettings pipelineServiceSettings =
        PipelineServiceSettings.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 (PipelineServiceClient pipelineServiceClient =
        PipelineServiceClient.create(pipelineServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      String trainingTaskDefinition =
          "gs://google-cloud-aiplatform/schema/trainingjob/definition/"
              + "automl_video_classification_1.0.0.yaml";

      InputDataConfig inputDataConfig =
          InputDataConfig.newBuilder().setDatasetId(datasetId).build();
      Model model = Model.newBuilder().setDisplayName(modelDisplayName).build();

      TrainingPipeline trainingPipeline =
          TrainingPipeline.newBuilder()
              .setDisplayName(videoClassificationDisplayName)
              .setTrainingTaskDefinition(trainingTaskDefinition)
              .setTrainingTaskInputs(ValueConverter.EMPTY_VALUE)
              .setInputDataConfig(inputDataConfig)
              .setModelToUpload(model)
              .build();

      TrainingPipeline trainingPipelineResponse =
          pipelineServiceClient.createTrainingPipeline(locationName, trainingPipeline);

      System.out.println("Create Training Pipeline Video Classification Response");
      System.out.format("\tName: %s\n", trainingPipelineResponse.getName());
      System.out.format("\tDisplay Name: %s\n", trainingPipelineResponse.getDisplayName());
      System.out.format(
          "\tTraining Task Definition: %s\n", trainingPipelineResponse.getTrainingTaskDefinition());
      System.out.format(
          "\tTraining Task Inputs: %s\n", trainingPipelineResponse.getTrainingTaskInputs());
      System.out.format(
          "\tTraining Task Metadata: %s\n", trainingPipelineResponse.getTrainingTaskMetadata());
      System.out.format("\tState: %s\n", trainingPipelineResponse.getState());
      System.out.format("\tCreate Time: %s\n", trainingPipelineResponse.getCreateTime());
      System.out.format("\tStart Time: %s\n", trainingPipelineResponse.getStartTime());
      System.out.format("\tEnd Time: %s\n", trainingPipelineResponse.getEndTime());
      System.out.format("\tUpdate Time: %s\n", trainingPipelineResponse.getUpdateTime());
      System.out.format("\tLabels: %s\n", trainingPipelineResponse.getLabelsMap());

      InputDataConfig inputDataConfigResponse = trainingPipelineResponse.getInputDataConfig();
      System.out.println("\tInput Data Config");
      System.out.format("\t\tDataset Id: %s\n", inputDataConfigResponse.getDatasetId());
      System.out.format(
          "\t\tAnnotations Filter: %s\n", inputDataConfigResponse.getAnnotationsFilter());

      FractionSplit fractionSplit = inputDataConfigResponse.getFractionSplit();
      System.out.println("\t\tFraction Split");
      System.out.format("\t\t\tTraining Fraction: %s\n", fractionSplit.getTrainingFraction());
      System.out.format("\t\t\tValidation Fraction: %s\n", fractionSplit.getValidationFraction());
      System.out.format("\t\t\tTest Fraction: %s\n", fractionSplit.getTestFraction());

      FilterSplit filterSplit = inputDataConfigResponse.getFilterSplit();
      System.out.println("\t\tFilter Split");
      System.out.format("\t\t\tTraining Fraction: %s\n", filterSplit.getTrainingFilter());
      System.out.format("\t\t\tValidation Fraction: %s\n", filterSplit.getValidationFilter());
      System.out.format("\t\t\tTest Fraction: %s\n", filterSplit.getTestFilter());

      PredefinedSplit predefinedSplit = inputDataConfigResponse.getPredefinedSplit();
      System.out.println("\t\tPredefined Split");
      System.out.format("\t\t\tKey: %s\n", predefinedSplit.getKey());

      TimestampSplit timestampSplit = inputDataConfigResponse.getTimestampSplit();
      System.out.println("\t\tTimestamp Split");
      System.out.format("\t\t\tTraining Fraction: %s\n", timestampSplit.getTrainingFraction());
      System.out.format("\t\t\tValidation Fraction: %s\n", timestampSplit.getValidationFraction());
      System.out.format("\t\t\tTest Fraction: %s\n", timestampSplit.getTestFraction());
      System.out.format("\t\t\tKey: %s\n", timestampSplit.getKey());

      Model modelResponse = trainingPipelineResponse.getModelToUpload();
      System.out.println("\tModel To Upload");
      System.out.format("\t\tName: %s\n", modelResponse.getName());
      System.out.format("\t\tDisplay Name: %s\n", modelResponse.getDisplayName());
      System.out.format("\t\tDescription: %s\n", modelResponse.getDescription());
      System.out.format("\t\tMetadata Schema Uri: %s\n", modelResponse.getMetadataSchemaUri());
      System.out.format("\t\tMeta Data: %s\n", modelResponse.getMetadata());
      System.out.format("\t\tTraining Pipeline: %s\n", modelResponse.getTrainingPipeline());
      System.out.format("\t\tArtifact Uri: %s\n", modelResponse.getArtifactUri());
      System.out.format(
          "\t\tSupported Deployment Resources Types: %s\n",
          modelResponse.getSupportedDeploymentResourcesTypesList().toString());
      System.out.format(
          "\t\tSupported Input Storage Formats: %s\n",
          modelResponse.getSupportedInputStorageFormatsList().toString());
      System.out.format(
          "\t\tSupported Output Storage Formats: %s\n",
          modelResponse.getSupportedOutputStorageFormatsList().toString());
      System.out.format("\t\tCreate Time: %s\n", modelResponse.getCreateTime());
      System.out.format("\t\tUpdate Time: %s\n", modelResponse.getUpdateTime());
      System.out.format("\t\tLables: %s\n", modelResponse.getLabelsMap());

      Status status = trainingPipelineResponse.getError();
      System.out.println("\tError");
      System.out.format("\t\tCode: %s\n", status.getCode());
      System.out.format("\t\tMessage: %s\n", status.getMessage());
    }
  }
}

Node.js

Bevor Sie dieses Beispiel anwenden, folgen Sie den Node.js-Einrichtungsschritten in der Vertex AI-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Vertex AI Node.js API.

Richten Sie zur Authentifizierung bei Vertex AI Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

// const datasetId = 'YOUR_DATASET_ID';
// const modelDisplayName = 'YOUR_MODEL_DISPLAY_NAME';
// const trainingPipelineDisplayName = 'YOUR_TRAINING_PIPELINE_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');
const {definition} =
  aiplatform.protos.google.cloud.aiplatform.v1.schema.trainingjob;

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

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

// Instantiates a client
const pipelineServiceClient = new PipelineServiceClient(clientOptions);

async function createTrainingPipelineVideoClassification() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  // Values should match the input expected by your model.
  const trainingTaskInputObj = new definition.AutoMlVideoClassificationInputs(
    {}
  );
  const trainingTaskInputs = trainingTaskInputObj.toValue();

  const modelToUpload = {displayName: modelDisplayName};
  const inputDataConfig = {datasetId: datasetId};
  const trainingPipeline = {
    displayName: trainingPipelineDisplayName,
    trainingTaskDefinition:
      'gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_classification_1.0.0.yaml',
    trainingTaskInputs,
    inputDataConfig,
    modelToUpload,
  };
  const request = {
    parent,
    trainingPipeline,
  };

  // Create training pipeline request
  const [response] =
    await pipelineServiceClient.createTrainingPipeline(request);

  console.log('Create training pipeline video classification response');
  console.log(`Name : ${response.name}`);
  console.log('Raw response:');
  console.log(JSON.stringify(response, null, 2));
}
createTrainingPipelineVideoClassification();

Python

Informationen zum Installieren oder Aktualisieren von Python finden Sie unter Vertex AI SDK für Python installieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Python API.

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

def create_training_pipeline_video_classification_sample(
    project: str,
    display_name: str,
    dataset_id: str,
    model_display_name: 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.PipelineServiceClient(client_options=client_options)
    training_task_inputs = (
        trainingjob.definition.AutoMlVideoClassificationInputs().to_value()
    )

    training_pipeline = {
        "display_name": display_name,
        "training_task_definition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_classification_1.0.0.yaml",
        # Training task inputs are empty for video classification
        "training_task_inputs": training_task_inputs,
        "input_data_config": {"dataset_id": dataset_id},
        "model_to_upload": {"display_name": model_display_name},
    }
    parent = f"projects/{project}/locations/{location}"
    response = client.create_training_pipeline(
        parent=parent, training_pipeline=training_pipeline
    )
    print("response:", response)

Datenaufteilung mit REST steuern

Sie können steuern, wie Ihre Trainingsdaten auf die Trainings-, Validierungs- und Test-Datasets aufgeteilt werden. Verwenden Sie bei der Vertex AI API das Objekt Split, um die Datenaufteilung zu bestimmen. Das Split-Objekt kann als einer von mehreren Objekttypen in das InputConfig-Objekt aufgenommen werden. Jedes Objekt bietet eine andere Möglichkeit zur Aufteilung der Trainingsdaten. Sie können nur eine Methode auswählen.

  • FractionSplit:
    • TRAINING_FRACTION: Der Anteil der Trainingsdaten, die für das Trainings-Dataset verwendet werden sollen.
    • VALIDATION_FRACTION: Der Anteil der Trainingsdaten, die für das Validierungs-Dataset verwendet werden sollen. Nicht für Videodaten verwendet.
    • TEST_FRACTION: Der Anteil der Trainingsdaten, die für das Test-Dataset verwendet werden sollen.

    Wenn Bruchzahlen angegeben werden, müssen alle angegeben werden. Die Bruchwerte müssen zusammengenommen 1,0 ergeben. Die Standardwerte für die Brüche variieren je nach Datentyp. Weitere Informationen

    "fractionSplit": {
      "trainingFraction": TRAINING_FRACTION,
      "validationFraction": VALIDATION_FRACTION,
      "testFraction": TEST_FRACTION
    },
    
  • FilterSplit:
    • TRAINING_FILTER: Datenelemente, die diesem Filter entsprechen, werden für das Trainings-Dataset verwendet.
    • VALIDATION_FILTER: Datenelemente, die diesem Filter entsprechen, werden für das Validierungs-Dataset verwendet. Muss für Videodaten „-” sein.
    • TEST_FILTER: Datenelemente, die diesem Filter entsprechen, werden für das Test-Dataset verwendet.

    Diese Filter können mit dem Label ml_use oder mit anderen Labels verwendet werden, die Sie auf Ihre Daten anwenden. Weitere Informationen zum Filtern von Daten finden Sie unter Labels für ml-use verwenden und weitere Labels.

    Das folgende Beispiel zeigt, wie das Objekt filterSplit mit dem Label ml_use verwendet wird, wobei das Validierungs-Dataset enthalten ist:

    "filterSplit": {
    "trainingFilter": "labels.aiplatform.googleapis.com/ml_use=training",
    "validationFilter": "labels.aiplatform.googleapis.com/ml_use=validation",
    "testFilter": "labels.aiplatform.googleapis.com/ml_use=test"
    }