モデリング作業の自動化

R での tidymodels によるモデリング

David Svancer

Data Scientist

ワークフローの効率化

last_fit() 関数

  • 分類モデルにも対応
  • モデリングを高速化
  • 学習データで学習し、テストデータで予測を生成

 

fit() と同様、最初の手順:

  • rsample でデータ分割を作成
  • parsnip でモデルを指定
leads_split <- initial_split(leads_df, 
                             strata = purchased)

logistic_model <- logistic_reg() %>% set_engine('glm') %>% set_mode('classification')
R での tidymodels によるモデリング

モデルの学習と指標の収集

last_fit() 関数

  • parsnip のモデルオブジェクト
  • モデル式
  • データ分割オブジェクト

 

collect_metrics() はテストデータで指標を算出

  • 既定で Accuracy と ROC AUC
logistic_last_fit <- logistic_model %>% 
  last_fit(purchased ~ total_visits + total_time,
           split = leads_split)

logistic_last_fit %>% collect_metrics()

 

# A tibble: 2 x 3
  .metric  .estimator .estimate
  <chr>      <chr>       <dbl>
1 accuracy   binary      0.759
2 roc_auc    binary      0.763
R での tidymodels によるモデリング

予測の収集

collect_predictions()

  • yardstick 用に必要な列を持つ tibble を作成
  • テストデータの実測と予測を含む
  • すべてのクラスの推定確率列を含む
last_fit_results <- logistic_last_fit %>% 
  collect_predictions()
last_fit_results
# A tibble: 332 x 6
   id             .pred_yes .pred_no .row .pred_class purchased
   <chr>            <dbl>    <dbl>   <int>   <fct>      <fct>
 1 train/test split  0.134    0.866     2      no        no
 2 train/test split  0.729    0.271    17      yes       yes
 3 train/test split  0.133    0.867    21      no        no
 4 train/test split  0.0916   0.908    22      no        no
 5 train/test split  0.598    0.402    24      yes       yes
# ... with 327 more rows
R での tidymodels によるモデリング

カスタム指標セット

metric_set() 関数

  • accuracy(), sens(), spec()
    • 引数 truthestimate が必要
  • roc_auc()
    • truth と確率列が必要

 

custom_metrics() では3つすべてを使用し、最後の引数は .pred_yes とします

custom_metrics <- metric_set(accuracy, sens,
                             spec, roc_auc)
custom_metrics(last_fit_results,
               truth = purchased,
               estimate = .pred_class,
               .pred_yes)
# A tibble: 4 x 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.759
2 sens     binary         0.617
3 spec     binary         0.840
4 roc_auc  binary         0.763
R での tidymodels によるモデリング

Passons à la pratique !

R での tidymodels によるモデリング

Preparing Video For Download...