하이퍼 매개 변수 튜닝에 스윕 작업 사용
Azure Machine Learning에서 스윕 작업을 실행하여 하이퍼 매개 변수를 튜닝할 수 있습니다.
하이퍼 매개 변수 튜닝을 위한 학습 스크립트 만들기
스윕 작업을 실행하려면 스크립트가 다음을 수행해야 한다는 점을 제외하고 다른 학습 작업에 대해 수행할 수 있는 방법으로만 학습 스크립트를 만들어야 합니다.
- 변경하려는 각 하이퍼 매개 변수에 대한 인수를 포함합니다.
- MLflow를 사용하여 대상 성능 메트릭을 로그합니다. 로그된 메트릭을 사용하면 스윕 작업이 시작하는 시험의 성능을 평가하고 최고의 성능 모델을 생성하는 시험을 식별할 수 있습니다.
참고
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 스튜디오에서 스윕 작업을 모니터링할 수 있습니다. 스윕 작업은 각 하이퍼 매개 변수 조합에 대한 시험을 시작합니다. 각 시험에 대해 기록된 모든 메트릭을 검토할 수 있습니다.
또한 스튜디오에서 시험을 시각화하여 모델을 평가하고 비교할 수 있습니다. 각 차트를 조정하여 각 시험의 하이퍼 매개 변수 값과 메트릭을 표시하고 비교할 수 있습니다.
팁
하이퍼 매개 변수 튜닝 작업을 시각화하는 방법에 대해 자세히 알아봅니다.