Edge 내보내기 가능 모델 학습

준비된 데이터 세트로 학습시켜 커스텀 모델을 만듭니다. AutoML API는 데이터 세트의 항목을 이용해 모델을 학습시키고, 테스트하고, 모델의 성능을 평가합니다. 결과를 검토하고 필요하면 학습 데이터세트를 조정하며 향상된 데이터세트를 사용하여 새 모델을 학습시킵니다.

모델 학습이 완료되기까지 몇 시간 정도 걸릴 수 있습니다. AutoML API를 사용하면 학습의 상태를 확인할 수 있습니다.

학습을 시작할 때마다 AutoML Vision이 새 모델을 생성하므로 프로젝트에 수많은 모델이 포함될 수 있습니다. 프로젝트에 포함된 모델의 목록을 가져오고 더 이상 필요 없는 모델을 삭제할 수 있습니다. 또는 Cloud AutoML Vision UI를 사용해서 AutoML API를 통해 생성된 모델을 나열하고 더 이상 필요하지 않은 모델을 삭제할 수 있습니다.

모델은 Google의 최첨단 연구를 기반으로 합니다. 모델은 TF Lite 패키지로 제공됩니다. TensorFlow Lite SDK를 사용하여 TensorFlow Lite 모델을 통합하는 방법에 대한 자세한 내용은 다음의 iOSAndroid 링크를 참조하세요.

Edge 모델 학습

라벨이 지정된 학습 항목이 다수 포함된 데이터 세트가 있으면 커스텀 Edge 모델을 만들고 학습시킬 준비가 된 것입니다.

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 참조 문서를 참조하세요.

TensorFlow Serving 및 TF Lite 모델

학습 시에는 특정 사용 사례에 따라 원하는 Edge 모델 유형을 선택할 수 있습니다.

  • 짧은 지연 시간(mobile-low-latency-1)
  • 범용 용도(mobile-versatile-1)
  • 예측 품질 개선(mobile-high-accuracy-1)

웹 UI

  1. Vision Dashboard을 엽니다.

    데이터 세트 페이지에는 현재 프로젝트에 사용 가능한 데이터 세트가 표시됩니다.

    데이터 세트 페이지 나열
  2. 커스텀 모델 학습에 사용할 데이터 세트를 선택합니다.
  3. 데이터세트가 준비되면 학습 탭과 새 모델 학습 버튼을 선택합니다.

    그러면 학습 옵션이 포함된 '새 모델 학습' 측면 창이 열립니다.

  4. 학습의 모델 정의 섹션에서 모델 이름을 변경하고(또는 기본값 사용), 모델 유형으로 Edge를 선택합니다. Edge 모델을 학습하도록 선택한 후 계속을 선택합니다. 에지 모델 학습 라디오 버튼 이미지
  5. 다음 모델 최적화 세션에서 원하는 최적화 기준( 더 높은 정확성, 최적의 절충, 더 빠른 예측)을 선택합니다. 최적화 사양을 선택한 후 계속을 선택합니다.

    최적의 균형 라디오 버튼 이미지
  6. 다음 노드 시간 예산 설정 섹션에서 권장 노드 시간 예산을 사용하거나 다른 값을 지정합니다.

    기본적으로 대부분의 데이터세트는 24 노드 시간이면 모델을 학습하는 데 충분합니다. 이 권장 값은 모델을 완전히 수렴하기 위한 예상 값입니다. 하지만 다른 값을 선택할 수도 있습니다. 이미지 분류에 대한 노드 시간의 최솟값은 8입니다. 객체 감지의 경우에는 최솟값이 20입니다.

    노드 예산 설정 섹션
  7. 학습 시작을 선택하여 모델 학습을 시작합니다.

모델 학습이 완료되기까지 몇 시간 정도 걸릴 수 있습니다. 모델 학습이 끝나면 Google Cloud Platform 프로젝트에 사용된 이메일 주소로 메시지가 수신됩니다.

REST

Edge 모델을 학습시킬 때 모델에 무엇이 필요한지에 따라 modelType 필드에서 세 가지 값을 지정할 수 있습니다.

  • 짧은 지연 시간의 경우 mobile-low-latency-1
  • 범용 용도의 경우 mobile-versatile-1
  • 예측 품질 개선의 경우 mobile-high-accuracy-1

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • display-name: 선택한 문자열 표시 이름입니다.
  • dataset-id: 데이터 세트의 ID입니다. ID는 데이터 세트 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 데이터 세트 이름: projects/project-id/locations/location-id/datasets/3104518874390609379
    • 데이터 세트 ID: 3104518874390609379

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models

JSON 요청 본문:

{
  "displayName": "DISPLAY_NAME",
  "datasetId": "DATASET_ID",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1"
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 ICN2106290444865378475)를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN2106290444865378475",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-30T20:06:08.253243Z",
    "updateTime": "2019-10-30T20:06:08.253243Z",
    "createModelDetails": {}
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// visionClassificationCreateModel creates a model for image classification.
func visionClassificationCreateModel(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateModel: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())
	fmt.Fprintf(w, "Training started...\n")

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

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

class VisionClassificationCreateModel {

  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.
      ImageClassificationModelMetadata metadata =
          ImageClassificationModelMetadata.newBuilder().setTrainBudgetMilliNodeHours(24000).build();
      Model model =
          Model.newBuilder()
              .setDisplayName(displayName)
              .setDatasetId(datasetId)
              .setImageClassificationModelMetadata(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

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * 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').v1;

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

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

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

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

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

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
# train_budget_milli_node_hours: The actual train_cost will be equal or
# less than this value.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#imageclassificationmodelmetadata
metadata = automl.ImageClassificationModelMetadata(
    train_budget_milli_node_hours=24000
)
model = automl.Model(
    display_name=display_name,
    dataset_id=dataset_id,
    image_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...")

작업 상태 나열

다음 코드 샘플을 사용하여 프로젝트의 작업을 나열하고 결과를 필터링합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations"

PowerShell

다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations" | Select-Object -Expand Content

표시되는 결과는 요청한 작업에 따라 다릅니다.

선택한 쿼리 매개변수(operationId, done, worksOn)를 사용하여 반환되는 작업을 필터링할 수도 있습니다. 예를 들어 실행이 완료된 작업 목록을 반환하려면 다음과 같이 URL을 수정하세요.

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations?filter="done=true"

Go

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	longrunning "cloud.google.com/go/longrunning/autogen/longrunningpb"
	"google.golang.org/api/iterator"
)

// listOperationStatus lists existing operations' status.
func listOperationStatus(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &longrunning.ListOperationsRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.LROClient.ListOperations(ctx, req)

	// Iterate over all results
	for {
		op, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListOperations.Next: %w", err)
		}

		fmt.Fprintf(w, "Name: %v\n", op.GetName())
		fmt.Fprintf(w, "Operation details:\n")
		fmt.Fprintf(w, "%v", op)
	}

	return nil
}

Java

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.LocationName;
import com.google.longrunning.ListOperationsRequest;
import com.google.longrunning.Operation;
import java.io.IOException;

class ListOperationStatus {

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

  // Get the status of an operation
  static void listOperationStatus(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 operations request.
      ListOperationsRequest listrequest =
          ListOperationsRequest.newBuilder().setName(projectLocation.toString()).build();

      // List all the operations names available in the region by applying filter.
      for (Operation operation :
          client.getOperationsClient().listOperations(listrequest).iterateAll()) {
        System.out.println("Operation details:");
        System.out.format("\tName: %s\n", operation.getName());
        System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
        System.out.format("\tDone: %s\n", operation.getDone());
        if (operation.hasResponse()) {
          System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
        }
        if (operation.hasError()) {
          System.out.println("\tResponse:");
          System.out.format("\t\tError code: %s\n", operation.getError().getCode());
          System.out.format("\t\tError message: %s\n\n", operation.getError().getMessage());
        }
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * 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').v1;

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

async function listOperationStatus() {
  // Construct request
  const request = {
    name: client.locationPath(projectId, location),
    filter: `worksOn=projects/${projectId}/locations/${location}/models/*`,
  };

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

  console.log('List of operation status:');
  for (const operation of response) {
    console.log(`Name: ${operation.name}`);
    console.log('Operation details:');
    console.log(`${operation}`);
  }
}

listOperationStatus();

Python

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import 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"
# List all the operations names available in the region.
response = client._transport.operations_client.list_operations(
    name=project_location, filter_="", timeout=5
)

print("List of operations:")
for operation in response:
    print(f"Name: {operation.name}")
    print("Operation details:")
    print(operation)

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

장기 실행 작업 다루기

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • operation-id: 작업의 ID입니다. ID는 작업 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 작업 이름: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • 작업 ID: IOD5281059901324392598

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"

PowerShell

다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID" | Select-Object -Expand Content
가져오기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

모델 만들기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-07-22T18:35:06.881193Z",
    "updateTime": "2019-07-22T19:58:44.972235Z",
    "createModelDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
    "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID"
  }
}

Go

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getOperationStatus gets an operation's status.
func getOperationStatus(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Name: %v\n", op.Name())

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
		return err
	}
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
		return err
	}
	fmt.Fprintf(w, "Response: %v\n", resp)

	return nil
}

Java

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  static void getOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
    getOperationStatus(operationFullId);
  }

  // Get the status of an operation
  static void getOperationStatus(String operationFullId) 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()) {
      // Get the latest state of a long-running operation.
      Operation operation = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println("Operation details:");
      System.out.format("\tName: %s\n", operation.getName());
      System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
      System.out.format("\tDone: %s\n", operation.getDone());
      if (operation.hasResponse()) {
        System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
      }
      if (operation.hasError()) {
        System.out.println("\tResponse:");
        System.out.format("\t\tError code: %s\n", operation.getError().getCode());
        System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

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

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

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

async function getOperationStatus() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
  };

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

  console.log(`Name: ${response.name}`);
  console.log('Operation details:');
  console.log(`${response}`);
}

getOperationStatus();

Python

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# operation_full_id = \
#     "projects/[projectId]/locations/us-central1/operations/[operationId]"

client = automl.AutoMlClient()
# Get the latest state of a long-running operation.
response = client._transport.operations_client.get_operation(operation_full_id)

print(f"Name: {response.name}")
print("Operation details:")
print(response)

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 참조 문서를 참조하세요.

작업 취소

작업 ID를 사용해 가져오기 또는 학습 작업을 취소할 수 있습니다.

REST

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • operation-id: 작업의 ID입니다. ID는 작업 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 작업 이름: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • 작업 ID: IOD5281059901324392598

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel"

PowerShell

다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID:cancel" | Select-Object -Expand Content
요청에 성공하면 빈 JSON 객체가 반환됩니다.
{}

모델 정보 가져오기

다음 코드 샘플을 사용하여 특정 학습된 모델에 대한 정보를 가져옵니다. 이 요청에서 반환된 정보를 사용하여 모드를 수정하거나 예측 요청을 보낼 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • model-id: 모델을 만들 때의 응답에서 모델의 ID입니다. ID는 모델 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 모델 이름: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • 모델 ID: IOD4412217016962778756

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id"

PowerShell

다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/models/model-id" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.



    {
  "name": "projects/project-id/locations/us-central1/models/model-id",
  "displayName": "display-name",
  "datasetId": "dataset-id",
  "createTime": "2019-10-30T20:06:08.253243Z",
  "deploymentState": "UNDEPLOYED",
  "updateTime": "2019-10-30T20:54:50.472328Z",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1",
    "nodeQps": 3.2
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getModel gets a model.
func getModel(w io.Writer, projectID string, location string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TRL123456789..."

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.GetModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	model, err := client.GetModel(ctx, req)
	if err != nil {
		return fmt.Errorf("GetModel: %w", err)
	}

	// Retrieve deployment state.
	deploymentState := "undeployed"
	if model.GetDeploymentState() == automlpb.Model_DEPLOYED {
		deploymentState = "deployed"
	}

	// Display the model information.
	fmt.Fprintf(w, "Model name: %v\n", model.GetName())
	fmt.Fprintf(w, "Model display name: %v\n", model.GetDisplayName())
	fmt.Fprintf(w, "Model create time:\n")
	fmt.Fprintf(w, "\tseconds: %v\n", model.GetCreateTime().GetSeconds())
	fmt.Fprintf(w, "\tnanos: %v\n", model.GetCreateTime().GetNanos())
	fmt.Fprintf(w, "Model deployment state: %v\n", deploymentState)

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Model;
import com.google.cloud.automl.v1.ModelName;
import java.io.IOException;

class GetModel {

  static void getModel() throws IOException {
    // 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 {
    // 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

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * 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').v1;

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

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import 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}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

재개 가능 학습

이제 대규모 데이터세트(이미지 1,000개 이상 포함)의 경우 커스텀 모델 학습을 일시 중지하고 재개할 수 있습니다. 모델 학습 일시중지는 일시중지 버튼과 관련된 직접 조치가 아닙니다. 대신 사용자는 노드 시간 예산을 지정된 시간(예: 2시간)으로 설정합니다. 이 시간에 도달하면 모델 상태와 상관없이 학습이 자동으로 중지됩니다.

재개 가능한 학습은 다음과 같은 제한사항과 함께 제공됩니다.

  • 기본 모델 시간 제한 - 지난 14일 이내에 학습한 모델에서만 학습을 재개할 수 있습니다. 요청 14일 전에 생성된 기본 모델은 재개 가능한 학습이 적용되지 않습니다.
  • 라벨 수정 없음 - 기본 모델의 데이터 세트에서 라벨을 변경하면 재개 가능한 학습이 실패합니다.
  • 성능 향상 보장 없음 - 모델에서 재개 가능한 학습을 사용하더라도 모델 성능 향상이 보장되지 않습니다.

웹 UI

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

  1. AutoML Vision UI을 엽니다.

    데이터 세트 페이지에는 현재 프로젝트에 사용 가능한 데이터 세트가 표시됩니다.

    데이터 세트 목록 페이지
  2. 커스텀 모델 학습에 사용할 데이터 세트를 선택합니다.

    선택한 데이터세트의 표시 이름이 제목 표시줄에 나타나고 페이지에는 데이터세트에 있는 개별 항목이 라벨과 함께 나열됩니다.

    이미지 항목 페이지
  3. 데이터 세트 검토가 끝났으면 제목 표시줄 바로 아래에 있는 학습 탭을 클릭합니다.

    이전에 학습한 모델은 이 탭의 목록에 나타납니다.

    학습한 모델 목록
  4. 모델에 재개 가능한 학습이 있으면 전체 평가 보기 옵션 근처에 옵션으로 표시됩니다.

    학습 재개를 선택하여 해당 모델의 학습을 재개합니다.

    학습 재개 옵션
  5. 원래 모델을 학습시키는 것과 마찬가지로 학습 재개를 선택하면 '새 모델 학습' 측면 창이 열립니다. 모델 정의 섹션에서 새 모델의 이름을 변경할 수 있습니다. 이 모델을 학습시키는 데 사용되는 기본 모델의 이름도 표시됩니다.

    모델 측면 창 정의

    모델을 정의한 후 계속을 선택하여 다음 섹션으로 이동합니다.

  6. 다음 노드 시간 예산 설정 섹션에서 노드 시간 예산을 지정합니다. 이 예산에는 초기 모델 학습과 유사한 가격 책정 구조 및 할당량 제한이 적용됩니다.

    학습 예산을 지정한 후 학습 시작을 선택합니다. 재개 가능한 학습이 완료되면 이메일이 전송됩니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • base-model-id: 기본(기존) 모델의 ID입니다. 새 모델은 이 기본 모델을 기준으로 생성됩니다. 다음 새 모델 사양이 기본 모델과 일치해야 합니다.

    * 기본 및 새 modelType은 이 필드가 새 모델 요청에서 생략된 경우에도 확인됩니다.

  • project-id: GCP 프로젝트 ID입니다.
  • display-name: 선택한 문자열 표시 이름입니다.
  • dataset-id: 데이터 세트의 ID입니다. ID는 데이터 세트 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 데이터 세트 이름: projects/project-id/locations/location-id/datasets/3104518874390609379
    • 데이터 세트 ID: 3104518874390609379

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models

JSON 요청 본문:

{
  "baseModelId": BASE_MODEL_ID,
  "displayName": "DISPLAY_NAME",
  "datasetId": "DATASET_ID",
  "imageClassificationModelMetadata": {
    "trainBudget": "1",
    "modelType": "mobile-low-latency-1"
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 ICN2106290444865378475)를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN2106290444865378475",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-30T20:06:08.253243Z",
    "updateTime": "2019-10-30T20:06:08.253243Z",
    "createModelDetails": {}
  }
}