Mengelola model

Model dilatih menggunakan set data yang sudah disiapkan dan Anda berikan. AutoML Video Intelligence Classification menggunakan item dari set data Anda untuk melatih, menguji, dan evaluate performa model. Selanjutnya, Anda harus meninjau hasilnya, menyesuaikan set data pelatihan sesuai kebutuhan, dan melatih model baru menggunakan set data yang ditingkatkan.

Proses pelatihan model dapat memakan waktu beberapa jam untuk diselesaikan. Dengan AutoML API, Anda dapat memeriksa status pelatihan.

Karena AutoML Video Intelligence Classification membuat model baru setiap kali Anda memulai pelatihan, project Anda mungkin akan menyertakan banyak model. Anda bisa mendapatkan daftar model di project Anda dan dapat menghapus model yang tidak diperlukan lagi.

Masa pakai maksimum untuk model adalah dua tahun. Anda harus membuat dan melatih model baru untuk terus mengklasifikasikan konten setelah jangka waktu tersebut.

Menggunakan curl atau PowerShell

Agar lebih mudah untuk menjalankan contoh curl (atau PowerShell) dalam topik ini, tetapkan variabel lingkungan berikut. Ganti project-id dengan nama project Google Cloud Anda.

export PROJECT_ID="project-id"

Melatih model

Jika Anda memiliki set data dengan kumpulan item pelatihan berlabel yang solid, Anda siap untuk membuat dan melatih model.

UI Web

  1. Buka AutoML Video UI dan buka halaman Datasets.

    Halaman set data di Konsol Google Cloud
  2. Pilih set data yang ingin Anda gunakan untuk melatih model.

    Nama tampilan set data yang dipilih akan muncul di panel judul, dan halaman tersebut mencantumkan setiap item dalam set data beserta labelnya.

    Tab Video dengan dua video ditampilkan
  3. Setelah selesai meninjau set data, klik tab Train di bawah panel judul.

    Halaman pelatihan memberikan analisis dasar set data Anda dan memberi tahu Anda apakah set data tersebut memadai untuk pelatihan. Jika AutoML Video menyarankan perubahan, pertimbangkan untuk kembali ke halaman Video dan menambahkan item atau label.

  4. Setelah set data siap, klik Start Training untuk membuat model baru atau Train New Model jika ingin membuat model tambahan.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • dataset-id: ID adalah elemen terakhir dari nama set data Anda. Misalnya, jika nama set data Anda adalah projects/434039606874/locations/us-central1/datasets/VCN3104518874390609379, maka ID set data Anda adalah VCN3104518874390609379.
  • Catatan:
    • project-number: nomor project Anda
    • location-id: region Cloud tempat anotasi seharusnya dilakukan. Region cloud yang didukung adalah: us-east1, us-west1, europe-west1, asia-east1. Jika tidak ada wilayah yang ditentukan, wilayah akan ditentukan berdasarkan lokasi file video.

Metode HTTP dan URL:

POST https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models

Isi JSON permintaan:

{
  "displayName": "test_model",
  "dataset_id": "dataset-id",
  "videoClassificationModelMetadata": {}
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-number" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models"

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-number" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models" | Select-Object -Expand Content
operation-id diberikan dalam respons saat Anda memulai operasi, misalnya VCN123....
{
  "name": "projects/project-number/locations/location-id/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "progressPercentage": 100,
    "createTime": "2020-02-27T01:56:28.395640Z",
    "updateTime": "2020-02-27T02:04:12.336070Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.Model",
    "name": "projects/project-number/locations/location-id/models/operation-id",
    "createTime": "2020-02-27T02:00:22.329970Z",
    "videoClassificationModelMetadata": {
      "trainBudget": "1",
      "trainCost": "1",
      "stopReason": "BUDGET_REACHED"
    },
    "displayName": "a_98487760535e48319dd204e6394670"
  }
}

Java

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.Model;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.VideoClassificationModelMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VideoClassificationCreateModel {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String displayName = "YOUR_DATASET_NAME";
    createModel(projectId, datasetId, displayName);
  }

  // Create a model
  static void createModel(String projectId, String datasetId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // 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 (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");
      // Set model metadata.
      VideoClassificationModelMetadata metadata =
          VideoClassificationModelMetadata.newBuilder().build();
      Model model =
          Model.newBuilder()
              .setDisplayName(displayName)
              .setDatasetId(datasetId)
              .setVideoClassificationModelMetadata(metadata)
              .build();

      // Create a model with the model metadata in the region.
      OperationFuture<Model, OperationMetadata> future =
          client.createModelAsync(projectLocation, model);
      // OperationFuture.get() will block until the model is created, which may take several hours.
      // 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("Training operation name: %s%n", future.getInitialFuture().get().getName());
      System.out.println("Training started...");
    }
  }
}

Node.js

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const dataset_id = 'YOUR_DATASET_ID';
// const displayName = 'YOUR_DISPLAY_NAME';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;

// Instantiates a client
const client = new AutoMlClient();

async function createModel() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    model: {
      displayName: displayName,
      datasetId: datasetId,
      videoClassificationModelMetadata: {},
    },
  };

  // Don't wait for the LRO
  const [operation] = await client.createModel(request);
  console.log(`Training started... ${operation}`);
  console.log(`Training operation name: ${operation.name}`);
}

createModel();

Python

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import automl_v1beta1 as automl

def create_model(
    project_id="YOUR_PROJECT_ID",
    dataset_id="YOUR_DATASET_ID",
    display_name="your_models_display_name",
):
    """Create a automl video classification model."""
    client = automl.AutoMlClient()

    # A resource that represents Google Cloud Platform location.
    project_location = f"projects/{project_id}/locations/us-central1"
    # Leave model unset to use the default base model provided by Google
    metadata = automl.VideoClassificationModelMetadata()
    model = automl.Model(
        display_name=display_name,
        dataset_id=dataset_id,
        video_classification_model_metadata=metadata,
    )

    # Create a model with the model metadata in the region.
    response = client.create_model(parent=project_location, model=model)

    print(f"Training operation name: {response.operation.name}")
    print("Training started...")

Mendapatkan informasi tentang model

Setelah pelatihan selesai, Anda bisa mendapatkan informasi tentang model yang baru dibuat.

Contoh di bagian ini menampilkan metadata dasar tentang suatu model. Untuk mendapatkan detail tentang akurasi dan kesiapan model, silakan melihat Mengevaluasi model.

UI Web

  1. Buka halaman Models di AutoML Video UI.

    Halaman Model dengan satu model ditampilkan
  2. Klik nama model yang ingin Anda lihat.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • model-name: Nama lengkap model yang diberikan oleh respons saat Anda membuat model. Nama lengkapnya memiliki format: projects/project-number/locations/location-id/models/model-id
  • dataset-id: ganti dengan ID set data untuk set data Anda (bukan nama tampilan). Contoh: VCN3940649673949184000
  • project-number: jumlah project Anda

Metode HTTP dan URL:

GET https://automl.googleapis.com/v1beta1/model-name/modelEvaluations

Meminta isi JSON:

{
  "displayName": "test_model",
  "dataset_id": "dataset-id",
  "videoClassificationModelMetadata": {}
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

Java

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.Model;
import com.google.cloud.automl.v1beta1.ModelName;
import io.grpc.StatusRuntimeException;
import java.io.IOException;

class GetModel {

  static void getModel() throws IOException, StatusRuntimeException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    getModel(projectId, modelId);
  }

  // Get a model
  static void getModel(String projectId, String modelId)
      throws IOException, StatusRuntimeException {
    // 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 (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
      Model model = client.getModel(modelFullId);

      // Display the model information.
      System.out.format("Model name: %s%n", model.getName());
      // To get the model id, you have to parse it out of the `name` field. As models Ids are
      // required for other methods.
      // Name Format: `projects/{project_id}/locations/{location_id}/models/{model_id}`
      String[] names = model.getName().split("/");
      String retrievedModelId = names[names.length - 1];
      System.out.format("Model id: %s%n", retrievedModelId);
      System.out.format("Model display name: %s%n", model.getDisplayName());
      System.out.println("Model create time:");
      System.out.format("\tseconds: %s%n", model.getCreateTime().getSeconds());
      System.out.format("\tnanos: %s%n", model.getCreateTime().getNanos());
      System.out.format("Model deployment state: %s%n", model.getDeploymentState());
    }
  }
}

Node.js

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;

// Instantiates a client
const client = new AutoMlClient();

async function getModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [response] = await client.getModel(request);

  console.log(`Model name: ${response.name}`);
  console.log(
    `Model id: ${
      response.name.split('/')[response.name.split('/').length - 1]
    }`
  );
  console.log(`Model display name: ${response.displayName}`);
  console.log('Model create time');
  console.log(`\tseconds ${response.createTime.seconds}`);
  console.log(`\tnanos ${response.createTime.nanos / 1e9}`);
  console.log(`Model deployment state: ${response.deploymentState}`);
}

getModel();

Python

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import automl_v1beta1 as automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)
model = client.get_model(name=model_full_id)

# Retrieve deployment state.
if model.deployment_state == automl.Model.DeploymentState.DEPLOYED:
    deployment_state = "deployed"
else:
    deployment_state = "undeployed"

# Display the model information.
print(f"Model name: {model.name}")
print("Model id: {}".format(model.name.split("/")[-1]))
print(f"Model display name: {model.display_name}")
print(f"Model create time: {model.create_time}")
print(f"Model deployment state: {deployment_state}")

Membuat daftar model

Sebuah proyek dapat meliputi banyak model. Bagian ini menjelaskan cara mengambil daftar model yang tersedia untuk sebuah project.

UI Web

Buka halaman Models di UI Video AutoML untuk melihat model dalam project Anda.

Halaman Model dengan satu model dalam daftar

Untuk melihat model bagi project yang berbeda, pilih project dari menu drop-down di kanan atas kolom judul.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • model-name: Nama lengkap model yang diberikan oleh respons saat Anda membuat model. Nama lengkapnya memiliki format: projects/project-number/locations/location-id/models
  • Catatan:
    • project-number: nomor project Anda
    • location-id: region Cloud tempat anotasi seharusnya dilakukan. Region cloud yang didukung adalah: us-east1, us-west1, europe-west1, asia-east1. Jika tidak ada wilayah yang ditentukan, wilayah akan ditentukan berdasarkan lokasi file video.

Metode HTTP dan URL:

GET https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models

Untuk mengirim permintaan, perluas salah satu opsi berikut:

Anda akan menerima respons JSON yang mirip dengan yang berikut ini:

Java

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.ListModelsRequest;
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.Model;
import java.io.IOException;

class ListModels {

  static void listModels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    listModels(projectId);
  }

  // List the models available in the specified location
  static void listModels(String projectId) throws IOException {
    // 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 (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Create list models request.
      ListModelsRequest listModelsRequest =
          ListModelsRequest.newBuilder()
              .setParent(projectLocation.toString())
              .setFilter("")
              .build();

      // List all the models available in the region by applying filter.
      System.out.println("List of models:");
      for (Model model : client.listModels(listModelsRequest).iterateAll()) {
        // Display the model information.
        System.out.format("Model name: %s%n", model.getName());
        // To get the model id, you have to parse it out of the `name` field. As models Ids are
        // required for other methods.
        // Name Format: `projects/{project_id}/locations/{location_id}/models/{model_id}`
        String[] names = model.getName().split("/");
        String retrievedModelId = names[names.length - 1];
        System.out.format("Model id: %s%n", retrievedModelId);
        System.out.format("Model display name: %s%n", model.getDisplayName());
        System.out.println("Model create time:");
        System.out.format("\tseconds: %s%n", model.getCreateTime().getSeconds());
        System.out.format("\tnanos: %s%n", model.getCreateTime().getNanos());
        System.out.format("Model deployment state: %s%n", model.getDeploymentState());
      }
    }
  }
}

Node.js

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;

// Instantiates a client
const client = new AutoMlClient();

async function listModels() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    filter: 'translation_model_metadata:*',
  };

  const [response] = await client.listModels(request);

  console.log('List of models:');
  for (const model of response) {
    console.log(`Model name: ${model.name}`);
    console.log(`
      Model id: ${model.name.split('/')[model.name.split('/').length - 1]}`);
    console.log(`Model display name: ${model.displayName}`);
    console.log('Model create time');
    console.log(`\tseconds ${model.createTime.seconds}`);
    console.log(`\tnanos ${model.createTime.nanos / 1e9}`);
    console.log(`Model deployment state: ${model.deploymentState}`);
  }
}

listModels();

Python

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import automl_v1beta1 as automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"

client = automl.AutoMlClient()
# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
request = automl.ListModelsRequest(parent=project_location, filter="")
response = client.list_models(request=request)

print("List of models:")
for model in response:
    # Display the model information.
    if model.deployment_state == automl.Model.DeploymentState.DEPLOYED:
        deployment_state = "deployed"
    else:
        deployment_state = "undeployed"

    print(f"Model name: {model.name}")
    print("Model id: {}".format(model.name.split("/")[-1]))
    print(f"Model display name: {model.display_name}")
    print(f"Model create time: {model.create_time}")
    print(f"Model deployment state: {deployment_state}")

Menghapus model

Contoh berikut akan menghapus model.

UI Web

  1. Buka halaman Models di AutoML Video UI. Halaman Model dengan satu model ditampilkan
  2. Klik menu tiga titik di ujung kanan baris yang ingin Anda hapus, lalu pilih Delete.
  3. Klik Konfirmasi di kotak dialog konfirmasi.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • model-id: ganti dengan ID untuk model Anda
  • Catatan:
    • project-number: nomor project Anda
    • location-id: region Cloud tempat anotasi seharusnya dilakukan. Region cloud yang didukung adalah: us-east1, us-west1, europe-west1, asia-east1. Jika tidak ada wilayah yang ditentukan, wilayah akan ditentukan berdasarkan lokasi file video.

Metode HTTP dan URL:

DELETE https://automl.googleapis.com/v1beta1/projects/project-number/locations/test/models/model-id

Untuk mengirim permintaan, perluas salah satu opsi berikut:

Anda akan menerima respons JSON yang mirip dengan yang berikut ini:

Java

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeleteModel {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    deleteModel(projectId, modelId);
  }

  // Delete a model
  static void deleteModel(String projectId, String modelId)
      throws IOException, ExecutionException, InterruptedException {
    // 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 (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the model.
      ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);

      // Delete a model.
      Empty response = client.deleteModelAsync(modelFullId).get();

      System.out.println("Model deletion started...");
      System.out.println(String.format("Model deleted. %s", response));
    }
  }
}

Node.js

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;

// Instantiates a client
const client = new AutoMlClient();

async function deleteModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

  const [response] = await client.deleteModel(request);
  console.log(`Model deleted: ${response}`);
}

deleteModel();

Python

Untuk mengautentikasi ke AutoML Video, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import automl_v1beta1 as automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"

client = automl.AutoMlClient()
# Get the full path of the model.
model_full_id = client.model_path(project_id, "us-central1", model_id)
response = client.delete_model(name=model_full_id)

print(f"Model deleted. {response.result()}")