하이퍼 매개 변수 튜닝에 스윕 작업 사용

완료됨

Azure Machine Learning에서 스윕 작업을 실행하여 하이퍼 매개 변수를 튜닝할 수 있습니다.

하이퍼 매개 변수 튜닝을 위한 학습 스크립트 만들기

스윕 작업을 실행하려면 다른 학습 작업과 마찬가지로 학습 스크립트를 만들어야 하지만, 스크립트는 반드시 다음을 수행해야 합니다.

  • 변경하려는 각 하이퍼 매개 변수에 대한 인수를 포함합니다.
  • MLflow를 사용하여 대상 성능 메트릭을 기록합니다. 기록된 메트릭은 스윕 작업이 시작한 실험의 성능을 평가하고, 가장 성능이 뛰어난 모델을 식별할 수 있게 합니다.

예를 들어 다음 예제 스크립트는 인수를 사용하여 --regularization 로지스틱 회귀 모델을 학습하여 정규화 속도 하이퍼 매개 변수를 설정하고 정확 메트릭을 이름으로 Accuracy기록합니다.

import argparse
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import mlflow

# get regularization hyperparameter
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01)
args = parser.parse_args()
reg = args.reg_rate

# load the training dataset
data = pd.read_csv("data.csv")

# separate features and labels, and split for training/validatiom
X = data[['feature1','feature2','feature3','feature4']].values
y = data['label'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

# train a logistic regression model with the reg hyperparameter
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)

# calculate and log accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
mlflow.log_metric("Accuracy", acc)

스윕 작업 구성 및 실행

스윕 작업을 준비하려면 먼저 실행할 스크립트를 지정하고 스크립트에서 사용하는 매개 변수를 정의하는 기본 명령 작업을 만들어야 합니다.

from azure.ai.ml import command

# configure command job as base
job = command(
    code="./src",
    command="python train.py --regularization ${{inputs.reg_rate}}",
    inputs={
        "reg_rate": 0.01,
    },
    environment="AzureML-sklearn-0.24-ubuntu18.04-py37-cpu@latest",
    compute="aml-cluster",
    )

그런 다음 검색 공간을 사용하여 입력 매개 변수를 재정의할 수 있습니다.

from azure.ai.ml.sweep import Choice

command_job_for_sweep = job(
    reg_rate=Choice(values=[0.01, 0.1, 1]),
)

마지막으로 명령 작업에 대해 sweep()을 호출하여 검색 공간을 스윕합니다.

from azure.ai.ml import MLClient

# apply the sweep parameter to obtain the sweep_job
sweep_job = command_job_for_sweep.sweep(
    compute="aml-cluster",
    sampling_algorithm="grid",
    primary_metric="Accuracy",
    goal="Maximize",
)

# set the name of the sweep job experiment
sweep_job.experiment_name="sweep-example"

# define the limits for this sweep
sweep_job.set_limits(max_total_trials=4, max_concurrent_trials=2, timeout=7200)

# submit the sweep
returned_sweep_job = ml_client.create_or_update(sweep_job)

스윕 작업 모니터링 및 검토

Azure Machine Learning 스튜디오에서 스윕 작업을 모니터링할 수 있습니다. 스윕 작업은 시도할 각 하이퍼매개변수 조합에 대한 실행을 시작합니다. 각 평가판에 대해 기록된 모든 메트릭을 검토할 수 있습니다.

또한 스튜디오에서 평가판을 시각화하여 모델을 평가하고 비교할 수 있습니다. 각 차트를 조정하여 각 평가판에 대한 하이퍼 매개 변수 값과 메트릭을 표시하고 비교할 수 있습니다.

팁 (조언)

하이퍼 매개 변수 튜닝 작업을 시각화하는 방법에 대해 자세히 알아봅니다.