調整超參數

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...