创建超参数调节作业

使用 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 示例浏览器