ハイパーパラメーターのチューニングにスイープ ジョブを使用する
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 Studio でスイープ ジョブを監視できます。 スイープ ジョブは、試行するハイパーパラメーターの組み合わせごとに試行を開始します。 試用版ごとに、ログに記録されたすべてのメトリックを確認できます。
さらに、スタジオで試用版を視覚化することで、モデルを評価および比較できます。 各グラフを調整して、各試用版のハイパーパラメーター値とメトリックを表示および比較できます。