调整超参数

R 中的树模型机器学习

Sandro Raabe

Data Scientist

超参数

  • 影响树的形状与复杂度
  • 在训练前设置、控制模型复杂度的模型参数

parsnip 决策树的超参数:

  • min_n:分裂节点所需的最小样本数
  • tree_depth:树的最大深度
  • cost_complexity:对树复杂度的惩罚
R 中的树模型机器学习

为何调参?

parsnip 的默认值:

decision_tree(min_n = 20, tree_depth = 30, cost_complexity = 0.01)
  • 多数情况下效果良好,但未必适用于所有数据集

 

调参的目标是找到超参数的最优组合。

R 中的树模型机器学习

使用 tune 包在 tidymodels 中调参

空的调参网格

R 中的树模型机器学习

使用 tidymodels 调参

占位的模型规范

R 中的树模型机器学习

使用 tidymodels 调参

每个网格点训练一个模型的调参网格

R 中的树模型机器学习

使用 tidymodels 调参

选择表现最佳的网格点

R 中的树模型机器学习

步骤 1:创建占位符:tune()

spec_untuned <- decision_tree(

min_n = tune(), tree_depth = tune()
) %>% set_engine("rpart") %>% set_mode("classification")
Decision Tree Model Specification 
(classification)


Main Arguments: tree_depth = tune() min_n = tune()
  • tune() 标记待调参的参数
  • 其余规范按常规设置
R 中的树模型机器学习

步骤 2:创建调参网格:grid_regular()

tree_grid <- grid_regular(

parameters(spec_untuned),
levels = 3 )
# A tibble: 9 x 2
  min_n tree_depth
1     2          1
2    21          1
3    40          1
4     2          8
5    21          8
6    40          8
7     2         15
8    21         15
9    40         15
  • 辅助函数 parameters()
  • levels:每个超参数的网格点数
R 中的树模型机器学习

步骤 3:调参:tune_grid()

  • 为每个网格点训练一个模型
  • 对每个模型做样本外评估(CV)

 

用法与参数:

  • 未调参的树规范
  • 模型公式
  • CV 折
  • 调参网格
  • metric_set() 包装的指标列表
tune_results <- tune_grid(

spec_untuned,
outcome ~ .,
resamples = my_folds,
grid = tree_grid,
metrics = metric_set(accuracy))
R 中的树模型机器学习

可视化调参结果

autoplot(tune_results)

调参结果

R 中的树模型机器学习

步骤 4:使用最佳参数:finalize_model()

# 选择表现最佳的参数
final_params <- select_best(tune_results)

final_params
# A tibble: 1 x 3
    min_n    tree_depth    .config
    <int>         <int>      <chr>
1      2              8     Model4
# 填入规范中
best_spec <- finalize_model(spec_untuned, 
                            final_params)

best_spec
Decision Tree Model Specification 
                 (classification)

Main Arguments:
  tree_depth = 8
  min_n = 2

Computational engine: rpart
R 中的树模型机器学习

开始调参!

R 中的树模型机器学习

Preparing Video For Download...