自動化建模流程

在 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() 需要這三者,最後一個參數用 .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 建立模型

一起來練習吧!

在 R 中使用 tidymodels 建立模型

Preparing Video For Download...