使用 DVC 進行超參數調校

Machine Learning 的 CI/CD

Ravi Bhadauria

Machine Learning Engineer

超參數調校流程

  • 超參數調校

    • 輸入:參數掃描範圍
    • 輸出:最佳參數
  • 訓練

    • 輸入:最佳參數
    • 輸出:指標與圖表(前面已涵蓋)
  • 鬆耦合,便於獨立訓練

    • 超參數調校是充分但非必要條件
  • 兩項工作都依賴資料集

# Contents of hp configuration
{
    "n_estimators": [2, 4, 5],
    "max_depth": [10, 20, 50],
    "random_state": [1993]
}
# Contents of best parameters
{
    "n_estimators": 5,
    "max_depth": 20,
    "random_state": 1993
}
Machine Learning 的 CI/CD

訓練程式碼變更

Python 超參數調校腳本的變更
# Load hyperparameters from the JSON file
with open("rfc_best_params.json", "r") as params_file:
  rfc_params = json.load(params_file)

# Define and train model model = RandomForestClassifier(**rfc_params) model.fit(X_train, y_train)
Machine Learning 的 CI/CD

使用 GridSearch 的超參數調校

# Define the model and hyperparameter search space
model = RandomForestClassifier()
param_grid = json.load(open("hp_config.json", "r"))

# Perform GridSearch with five fold CV grid_search = GridSearchCV(model, param_grid, cv=5) grid_search.fit(X_train, y_train)
# Get the best hyperparameters best_params = grid_search.best_params_ with open("rfc_best_params.json", "w") as outfile: json.dump(best_params, outfile)
Machine Learning 的 CI/CD

DVC YAML 變更

超參數調校
stages:
  preprocess: ...
  train: ...
  hp_tune:
    cmd: python hp_tuning.py
    deps:
    - processed_dataset/weather.csv
    - hp_config.json
    - hp_tuning.py
    outs: # 不追蹤最佳參數
      - hp_tuning_results.md:
          cache: false
訓練
stages:
  preprocess: ...
  hp_tune: ...
  train:
    cmd: python train.py
    deps:
    - processed_dataset/weather.csv
    - rfc_best_params.json # 最佳參數
    - train.py
    metrics:
      - metrics.json:
          cache: false
Machine Learning 的 CI/CD

觸發個別階段

  • 可獨立觸發各階段:dvc repro <stage_name>

  • 強制執行超參數調校階段:dvc repro -f hp_tune

    • 確保最佳參數檔會更新
  • dvc repro train 執行訓練

  • 兩個階段都會因相依關係觸發前處理步驟

Machine Learning 的 CI/CD

超參數執行輸出

mean_test_score std_test_score max_depth n_estimators random_state
0.999733 0.000413118 20 5 1993
0.999307 0.000574418 50 5 1993
0.99888 0.000617378 10 5 1993
0.997813 0.00117333 10 4 1993

Python 超參數調校腳本的變更

# Save the results of hyperparameter tuning
cv_results = pd.DataFrame(grid_search.cv_results_)
markdown_table = cv_results.to_markdown(index=False)
with open("hp_tuning_results.md", "w") as markdown_file:
  markdown_file.write(markdown_table)
Machine Learning 的 CI/CD

重點總結

  • 超參數調校路徑

    • 分支名稱 hp_tune/<some-string>
    • 調整搜尋設定
    • 手動開 PR
      • 強制執行 DVC pipeline:dvc repro -f hp_tune
      • 使用 cml pr create 建立含最佳參數的新訓練 PR
    • 強制 push 訓練 PR 的一次提交以啟動模型訓練工作
  • 手動路徑

    • 分支名稱 train/<some-string>
    • 編輯最佳參數檔並提交變更
    • 手動開 PR 以啟動模型訓練工作
Machine Learning 的 CI/CD

一起來練習吧!

Machine Learning 的 CI/CD

Preparing Video For Download...