ハイパーパラメータのチューニング

Rで学ぶTree-Based ModelsによるMachine Learning

Sandro Raabe

Data Scientist

ハイパーパラメータ

  • 木の形状と複雑さに影響
  • 学習前に設定し、モデルの複雑さを制御するパラメータ

parsnip の決定木のハイパーパラメータ:

  • min_n: ノード分割に必要な最小サンプル数
  • tree_depth: 木の最大深さ
  • cost_complexity: 複雑さへのペナルティ
Rで学ぶTree-Based ModelsによるMachine Learning

なぜチューニングするのか

parsnip のデフォルト値:

decision_tree(min_n = 20, tree_depth = 30, cost_complexity = 0.01)
  • 多くの場合は有効だが、すべてのデータに最適とは限らない

 

チューニングの目的は、最適なハイパーパラメータの組合せを見つけることです。

Rで学ぶTree-Based ModelsによるMachine Learning

tune パッケージでの tidymodels によるチューニング

空のチューニンググリッド

Rで学ぶTree-Based ModelsによるMachine Learning

tidymodels でのチューニング

ダミーの仕様

Rで学ぶTree-Based ModelsによるMachine Learning

tidymodels でのチューニング

各グリッド点ごとに学習済みモデルがあるチューニンググリッド

Rで学ぶTree-Based ModelsによるMachine Learning

tidymodels でのチューニング

最良のグリッド点が選択される

Rで学ぶTree-Based ModelsによるMachine Learning

手順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で学ぶTree-Based ModelsによるMachine Learning

手順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で学ぶTree-Based ModelsによるMachine Learning

手順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で学ぶTree-Based ModelsによるMachine Learning

チューニング結果を可視化

autoplot(tune_results)

チューニング結果

Rで学ぶTree-Based ModelsによるMachine Learning

手順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で学ぶTree-Based ModelsによるMachine Learning

チューニングしてみましょう!

Rで学ぶTree-Based ModelsによるMachine Learning

Preparing Video For Download...