使用掃掠作業進行超參數微調

已完成

在 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 中監視掃掠作業。 掃描作業會針對每個要嘗試的超參數組合啟動試驗。 針對每個試驗,您可以檢閱所有記錄的指標。

此外,您可以藉由在 Studio 中可視化試用版來評估及比較模型。 您可以調整每個圖表,以顯示和比較每個試用版的超參數值和計量。

提示

深入瞭解如何 視覺化超參數微調作業