모델 관리

AutoML Vision 객체 감지는 학습을 시작할 때마다 새 모델을 만들기 때문에 프로젝트에 수많은 모델이 포함될 수 있습니다. 프로젝트에서 모델 목록을 가져오고 특정 모델을 가져오고 모델의 노드 번호를 업데이트하거나 더 이상 필요 없는 모델을 삭제할 수 있습니다.

모델 나열

프로젝트는 수많은 모델을 포함할 수 있습니다. 이 섹션에서는 프로젝트에 사용할 수 있는 모델 목록을 검색하는 방법에 대해 설명합니다.

웹 UI

AutoML Vision 객체 감지 UI를 사용해 사용 가능한 모델 목록을 표시하려면 왼쪽 탐색 메뉴 맨 위에 있는 모델 링크를 클릭합니다.

모델 나열 이미지

다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

REST

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

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

HTTP 메서드 및 URL:

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

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

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"

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" | Select-Object -Expand Content

다음 예시와 비슷한 JSON 응답이 표시됩니다. 이 응답은 2가지 클라우드 호스팅 모델에 대한 정보를 보여줍니다.



    {
  "model": [
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-1",
      "displayName": "display-name-1",
      "datasetId": "dataset-id",
      "createTime": "2019-07-26T21:10:18.338846Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-08-07T22:24:07.720068Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "cloud-low-latency-1",
        "nodeQps": 1.2987012987012987,
        "stopReason": "MODEL_CONVERGED",
        "trainBudgetMilliNodeHours": "216000",
        "trainCostMilliNodeHours": "8230"
      }
    },
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-2",
      "displayName": "display-name-2",
      "datasetId": "dataset-id",
      "createTime": "2019-07-22T18:35:06.881193Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-07-22T19:58:44.980357Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "mobile-versatile-1",
        "nodeQps": -1,
        "stopReason": "MODEL_CONVERGED",
        "trainBudgetMilliNodeHours": "24000",
        "trainCostMilliNodeHours": "9367"
      }
    },
    {
      "name": "projects/project-id/locations/us-central1/models/model-id-3",
      "displayName": "display-name-3",
      "datasetId": "dataset-id",
      "createTime": "2019-03-31T22:56:51.348238Z",
      "deploymentState": "UNDEPLOYED",
      "updateTime": "2019-07-22T18:42:44.594876Z",
      "imageObjectDetectionModelMetadata": {
        "modelType": "cloud-high-accuracy-1",
        "nodeQps": 0.6872852233676976
      }
    }
  ]
}

Go

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
	"google.golang.org/api/iterator"
)

// listModels lists existing models.
func listModels(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 := &automlpb.ListModelsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListModels(ctx, req)

	// Iterate over all results
	for {
		model, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListModels.Next: %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.ListModelsRequest;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.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

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

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

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

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"

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}")

추가 언어

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

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

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

모델 가져오기

수정하거나 예측을 위해 학습된 특정 모델을 가져올 수 있습니다.

웹 UI

AutoML Vision 객체 감지 UI를 사용해 사용 가능한 모델 목록을 표시하려면 왼쪽 탐색 메뉴 맨 위에 있는 모델 링크를 클릭합니다.

모델 나열 이미지

다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

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-07-26T21:10:18.338846Z",
  "deploymentState": "UNDEPLOYED",
  "updateTime": "2019-07-26T22:28:57.464076Z",
  "imageObjectDetectionModelMetadata": {
    "modelType": "cloud-low-latency-1",
    "nodeQps": 1.2987012987012987,
    "stopReason": "MODEL_CONVERGED",
    "trainBudgetMilliNodeHours": "216000",
    "trainCostMilliNodeHours": "8230"
  }
}

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 객체 감지 참조 문서를 참조하세요.

모델 노드 번호 업데이트

배포된 모델을 학습시켰으면 특정 트래픽 양에 대응하기 위해 모델이 배포된 노드 수를 업데이트할 수 있습니다. 예를 들어 예상한 것보다 초당 쿼리 수(QPS)가 많을 수 있습니다.

먼저 모델을 배포 취소하지 않아도 이 노드 수를 변경할 수 있습니다. 배포를 업데이트하면 제공된 예측 트래픽을 중단하지 않고도 노드 수가 변경됩니다.

웹 UI

  1. AutoML Vision Object Detection UI에서 왼쪽 탐색 메뉴의 모델 탭(전구 아이콘이 있음)을 선택하여 사용 가능한 모델을 표시합니다.

    다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 배포된 학습 모델을 선택합니다.
  3. 제목 표시줄 바로 아래에 있는 테스트 및 사용 탭을 선택합니다.
  4. 페이지 상단의 상자에 '모델이 배포되어 온라인 예측 요청에 사용할 수 있습니다'라는 메시지가 표시됩니다. 이 텍스트 옆의 배포 업데이트 옵션을 선택합니다.

    배포 업데이트 버튼의 이미지
  5. 배포 업데이트 창이 열리면 목록에서 모델을 배포할 새 노드 번호를 선택합니다. 노드 번호는 예상되는 예측 초당 쿼리 수(QPS)를 표시합니다. 배포 업데이트 팝업 창의 이미지
  6. 목록에서 새 노드 번호를 선택한 후 배포 업데이트를 선택하여 모델이 배포되는 노드 번호를 업데이트합니다.

    새 노드 번호를 선택한 후의 배포 업데이트 창
  7. 테스트 및 사용 창으로 돌아가게 되며, 텍스트 상자에 '모델 배포 중...'이라고 표시됩니다. 모델 배포
  8. 모델이 새 노드 번호에 성공적으로 배포되면 프로젝트와 연관된 주소로 이메일이 전송됩니다.

REST

처음에 모델을 배포하는 데 사용하는 것과 동일한 메서드를 사용하여 배포된 모델의 노드 번호를 변경합니다.

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

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

필드 고려사항:

  • nodeCount - 모델을 배포할 노드 수입니다. 값은 1에서 100 사이여야 합니다(양 끝 값 포함). 노드는 모델의 qps_per_node에서 지정된 온라인 예측의 초당 쿼리 수(QPS)를 처리할 수 있는 머신 리소스를 추상화한 것입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "imageObjectDetectionModelDeploymentMetadata": {
    "nodeCount": 2
  }
}

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

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/MODEL_ID:deploy"

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/MODEL_ID:deploy" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-08-07T22:00:20.692109Z",
    "updateTime": "2019-08-07T22:00:20.692109Z",
    "deployModelDetails": {}
  }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// visionObjectDetectionDeployModelWithNodeCount deploys a model with node count.
func visionObjectDetectionDeployModelWithNodeCount(w io.Writer, projectID string, location string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "IOD123456789..."

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

	req := &automlpb.DeployModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		ModelDeploymentMetadata: &automlpb.DeployModelRequest_ImageObjectDetectionModelDeploymentMetadata{
			ImageObjectDetectionModelDeploymentMetadata: &automlpb.ImageObjectDetectionModelDeploymentMetadata{
				NodeCount: 2,
			},
		},
	}

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

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Model deployed.\n")

	return nil
}

Java

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DeployModelRequest;
import com.google.cloud.automl.v1.ImageObjectDetectionModelDeploymentMetadata;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VisionObjectDetectionDeployModelNodeCount {

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

  // Deploy a model for prediction with a specified node count (can be used to redeploy a model)
  static void visionObjectDetectionDeployModelNodeCount(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);
      ImageObjectDetectionModelDeploymentMetadata metadata =
          ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
      DeployModelRequest request =
          DeployModelRequest.newBuilder()
              .setName(modelFullId.toString())
              .setImageObjectDetectionModelDeploymentMetadata(metadata)
              .build();
      OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

      future.get();
      System.out.println("Model deployment finished");
    }
  }
}

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 deployModelWithNodeCount() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    imageObjectDetectionModelDeploymentMetadata: {
      nodeCount: 2,
    },
  };

  const [operation] = await client.deployModel(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Model deployment finished. ${response}`);
}

deployModelWithNodeCount();

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)

# node count determines the number of nodes to deploy the model on.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#imageobjectdetectionmodeldeploymentmetadata
metadata = automl.ImageObjectDetectionModelDeploymentMetadata(node_count=2)

request = automl.DeployModelRequest(
    name=model_full_id,
    image_object_detection_model_deployment_metadata=metadata,
)
response = client.deploy_model(request=request)

print(f"Model deployment finished. {response.result()}")

추가 언어

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

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

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

모델 삭제

모델 ID를 사용하여 모델 리소스를 삭제할 수 있습니다.

웹 UI

  1. AutoML Vision 객체 감지 UI의 왼쪽 탐색 메뉴에서 전구 아이콘을 클릭해 사용 가능한 모델 목록을 표시합니다.

  2. 삭제하려는 행 맨 오른쪽에 있는 점 3개로 된 메뉴를 클릭하고 모델 삭제를 클릭합니다.

  3. 확인 대화상자에서 삭제를 클릭합니다.

    모델 이미지 삭제

REST

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

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

HTTP 메서드 및 URL:

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

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

curl

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

curl -X DELETE \
-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 DELETE `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us- central1/models/MODEL_ID" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-11-01T15:59:36.196506Z",
    "updateTime": "2018-11-01T15:59:36.196506Z",
    "deleteDetails": {}
  }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// deleteModel deletes a model.
func deleteModel(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.DeleteModelRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

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

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Model deleted.\n")

	return nil
}

Java

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

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.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

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

/**
 * 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 deleteModel() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
  };

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

deleteModel();

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)
response = client.delete_model(name=model_full_id)

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

추가 언어

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

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

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