自动化建模流程

在 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 建模

Passons à la pratique !

在 R 中使用 tidymodels 建模

Preparing Video For Download...