초매개변수 조정 작업 만들기

create_hyperparameter_tuning_job 메서드를 사용하여 초매개변수 조정 작업을 만듭니다.

코드 샘플

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.aiplatform.v1.AcceleratorType;
import com.google.cloud.aiplatform.v1.ContainerSpec;
import com.google.cloud.aiplatform.v1.CustomJobSpec;
import com.google.cloud.aiplatform.v1.HyperparameterTuningJob;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.StudySpec;
import com.google.cloud.aiplatform.v1.WorkerPoolSpec;
import java.io.IOException;

public class CreateHyperparameterTuningJobSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String containerImageUri = "CONTAINER_IMAGE_URI";
    createHyperparameterTuningJobSample(project, displayName, containerImageUri);
  }

  static void createHyperparameterTuningJobSample(
      String project, String displayName, String containerImageUri) throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (JobServiceClient client = JobServiceClient.create(settings)) {
      StudySpec.MetricSpec metric0 =
          StudySpec.MetricSpec.newBuilder()
              .setMetricId("accuracy")
              .setGoal(StudySpec.MetricSpec.GoalType.MAXIMIZE)
              .build();
      StudySpec.ParameterSpec.DoubleValueSpec doubleValueSpec =
          StudySpec.ParameterSpec.DoubleValueSpec.newBuilder()
              .setMinValue(0.001)
              .setMaxValue(0.1)
              .build();
      StudySpec.ParameterSpec parameter0 =
          StudySpec.ParameterSpec.newBuilder()
              // Learning rate.
              .setParameterId("lr")
              .setDoubleValueSpec(doubleValueSpec)
              .build();
      StudySpec studySpec =
          StudySpec.newBuilder().addMetrics(metric0).addParameters(parameter0).build();
      MachineSpec machineSpec =
          MachineSpec.newBuilder()
              .setMachineType("n1-standard-4")
              .setAcceleratorType(AcceleratorType.NVIDIA_TESLA_K80)
              .setAcceleratorCount(1)
              .build();
      ContainerSpec containerSpec =
          ContainerSpec.newBuilder().setImageUri(containerImageUri).build();
      WorkerPoolSpec workerPoolSpec0 =
          WorkerPoolSpec.newBuilder()
              .setMachineSpec(machineSpec)
              .setReplicaCount(1)
              .setContainerSpec(containerSpec)
              .build();
      CustomJobSpec trialJobSpec =
          CustomJobSpec.newBuilder().addWorkerPoolSpecs(workerPoolSpec0).build();
      HyperparameterTuningJob hyperparameterTuningJob =
          HyperparameterTuningJob.newBuilder()
              .setDisplayName(displayName)
              .setMaxTrialCount(2)
              .setParallelTrialCount(1)
              .setMaxFailedTrialCount(1)
              .setStudySpec(studySpec)
              .setTrialJobSpec(trialJobSpec)
              .build();
      LocationName parent = LocationName.of(project, location);
      HyperparameterTuningJob response =
          client.createHyperparameterTuningJob(parent, hyperparameterTuningJob);
      System.out.format("response: %s\n", response);
      System.out.format("Name: %s\n", response.getName());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 * (Not necessary if passing values as arguments)
 */
/*
const displayName = 'YOUR HYPERPARAMETER TUNING JOB;
const containerImageUri = 'TUNING JOB CONTAINER URI;
const project = 'YOUR PROJECT ID';
const location = 'us-central1';
  */
// Imports the Google Cloud Pipeline Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform');

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

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createHyperParameterTuningJob() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;

  // Create the hyperparameter tuning job configuration
  const hyperparameterTuningJob = {
    displayName,
    maxTrialCount: 2,
    parallelTrialCount: 1,
    maxFailedTrialCount: 1,
    studySpec: {
      metrics: [
        {
          metricId: 'accuracy',
          goal: 'MAXIMIZE',
        },
      ],
      parameters: [
        {
          parameterId: 'lr',
          doubleValueSpec: {
            minValue: 0.001,
            maxValue: 0.1,
          },
        },
      ],
    },
    trialJobSpec: {
      workerPoolSpecs: [
        {
          machineSpec: {
            machineType: 'n1-standard-4',
            acceleratorType: 'NVIDIA_TESLA_K80',
            acceleratorCount: 1,
          },
          replicaCount: 1,
          containerSpec: {
            imageUri: containerImageUri,
            command: [],
            args: [],
          },
        },
      ],
    },
  };

  const [response] = await jobServiceClient.createHyperparameterTuningJob({
    parent,
    hyperparameterTuningJob,
  });

  console.log('Create hyperparameter tuning job response:');
  console.log(`\tDisplay name: ${response.displayName}`);
  console.log(`\tTuning job resource name: ${response.name}`);
  console.log(`\tJob status: ${response.state}`);
}

createHyperParameterTuningJob();

Python

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Vertex AI Python API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import aiplatform

def create_hyperparameter_tuning_job_sample(
    project: str,
    display_name: str,
    container_image_uri: 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.JobServiceClient(client_options=client_options)
    hyperparameter_tuning_job = {
        "display_name": display_name,
        "max_trial_count": 2,
        "parallel_trial_count": 1,
        "max_failed_trial_count": 1,
        "study_spec": {
            "metrics": [
                {
                    "metric_id": "accuracy",
                    "goal": aiplatform.gapic.StudySpec.MetricSpec.GoalType.MAXIMIZE,
                }
            ],
            "parameters": [
                {
                    # Learning rate.
                    "parameter_id": "lr",
                    "double_value_spec": {"min_value": 0.001, "max_value": 0.1},
                },
            ],
        },
        "trial_job_spec": {
            "worker_pool_specs": [
                {
                    "machine_spec": {
                        "machine_type": "n1-standard-4",
                        "accelerator_type": aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_K80,
                        "accelerator_count": 1,
                    },
                    "replica_count": 1,
                    "container_spec": {
                        "image_uri": container_image_uri,
                        "command": [],
                        "args": [],
                    },
                }
            ]
        },
    }
    parent = f"projects/{project}/locations/{location}"
    response = client.create_hyperparameter_tuning_job(
        parent=parent, hyperparameter_tuning_job=hyperparameter_tuning_job
    )
    print("response:", response)

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.