使用 DVC 进行超参数调优

面向机器学习的 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
}
面向机器学习的 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)
面向机器学习的 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)
面向机器学习的 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
面向机器学习的 CI/CD

触发单个阶段

  • 可独立触发阶段 dvc repro <stage_name>

  • 强制运行超参调优阶段 dvc repro -f hp_tune

    • 确保最佳参数文件会更新
  • 使用 dvc repro train 运行训练

  • 两个阶段都会触发依赖的预处理步骤

面向机器学习的 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)
面向机器学习的 CI/CD

小结

  • 超参数调优路径

    • 分支名 hp_tune/<some-string>
    • 修改搜索配置
    • 手动打开 PR
      • 强制运行 DVC 流水线 dvc repro -f hp_tune
      • 使用 cml pr create 基于最佳参数创建新的训练 PR
    • 强制推送一次提交到训练 PR,触发训练作业
  • 手动路径

    • 分支名 train/<some-string>
    • 编辑最佳参数文件并提交
    • 手动打开 PR 触发训练作业
面向机器学习的 CI/CD

¡Vamos a practicar!

面向机器学习的 CI/CD

Preparing Video For Download...