机器学习工作流

在 R 中使用 tidymodels 建模

David Svancer

Data Scientist

用决策树做分类

决策树将自变量空间切分为矩形区域

递归二元划分

  • 将自变量空间划分为不重叠的矩形区域的算法

线索评分数据散点图

在 R 中使用 tidymodels 建模

用决策树做分类

决策树将自变量空间切分为矩形区域

递归二元划分

  • 将自变量空间划分为不重叠的矩形区域的算法
  • 迭代添加划分
    • 水平或垂直切分点

带有第一次决策树划分的散点图

在 R 中使用 tidymodels 建模

用决策树做分类

决策树将自变量空间切分为矩形区域

递归二元划分

  • 将自变量空间划分为不重叠的矩形区域的算法
  • 迭代添加划分
    • 水平或垂直切分点

带有第二次决策树划分的散点图

在 R 中使用 tidymodels 建模

用决策树做分类

决策树将自变量空间切分为矩形区域

递归二元划分

  • 将自变量空间划分为不重叠的矩形区域的算法
  • 迭代添加划分
    • 水平或垂直切分点

带有第三次决策树划分的散点图

在 R 中使用 tidymodels 建模

用决策树做分类

决策树将自变量空间切分为矩形区域

递归二元划分

  • 将自变量空间划分为不重叠的矩形区域的算法
  • 迭代添加划分
    • 水平或垂直切分点

 

生成不同的矩形区域

  • 分类时预测多数类

包含四个矩形预测区域的散点图

在 R 中使用 tidymodels 建模

树形图

  • 内部节点
    • 决策树的划分(深色框)
  • 终端节点
    • 不再继续划分的区域
    • 绿色和紫色框

决策树示意图

内部节点为虚线,终端节点为高亮的矩形区域

包含四个矩形预测区域的散点图

在 R 中使用 tidymodels 建模

模型规范

parsnip 中指定模型

  • decision_tree()
    • parsnip 中决策树模型的通用接口
    • 常用引擎为 'rpart'
    • 模式可为 'classification''regression'
      • 线索评分数据需使用 'classification'
dt_model <- decision_tree() %>% 

set_engine('rpart') %>%
set_mode('classification')
在 R 中使用 tidymodels 建模

特征工程配方

线索评分数据的特征变换

  • 编码在 recipe 对象中
    • 去除多重共线性
    • 对数值型自变量标准化
    • 为名义型自变量创建虚拟变量

需要管理两个 R 对象

  • parsnip 模型与 recipe 规范
  • 合并为一个对象更便于管理
leads_recipe <- recipe(purchased ~ .,
                       data = leads_training) %>%

step_corr(all_numeric(), threshold = 0.9) %>% step_normalize(all_numeric()) %>% step_dummy(all_nominal(), -all_outcomes())
leads_recipe
Data Recipe
Inputs:
      role #variables
   outcome          1
 predictor          6

Operations:
Correlation filter on all_numeric()
Centering and scaling for all_numeric()
Dummy variables from all_nominal(), -all_outcomes()
在 R 中使用 tidymodels 建模

合并模型与配方

workflows 包用于简化建模流程

  • parsnip 模型与 recipe 对象合并为单个 workflow 对象

 

使用 workflow() 初始化

  • add_model() 添加模型
  • add_recipe() 添加 recipe
    • 必须是规范,而非已训练的 recipe
leads_wkfl <- workflow() %>%

add_model(dt_model) %>%
add_recipe(leads_recipe)
leads_wkfl
== Workflow =====================
Preprocessor: Recipe
Model: decision_tree()
-- Preprocessor -----------------
3 Recipe Steps
* step_corr()
* step_normalize()
* step_dummy()
-- Model --------------------------
Decision Tree Model Specification (classification)
Computational engine: rpart
在 R 中使用 tidymodels 建模

使用 workflow 拟合模型

训练 workflow 对象

  • workflow 传入 last_fit(),并提供数据切分对象
  • collect_metrics() 查看评估结果

幕后步骤

  • 创建训练集与测试集
  • 训练并应用 recipe
  • 用训练集训练决策树
  • 在测试集上生成预测与指标
leads_wkfl_fit <- leads_wkfl %>% 
  last_fit(split = leads_split)

leads_wkfl_fit %>% collect_metrics()
# A tibble: 2 x 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.771
2 roc_auc  binary         0.775
在 R 中使用 tidymodels 建模

收集预测结果

last_fit() 训练的 workflow 可传入 collect_predictions()

  • 生成测试集的详细结果
  • 可与 yardstick 函数结合,计算自定义性能指标
leads_wkfl_preds <- leads_wkfl_fit %>% 
  collect_predictions()

leads_wkfl_preds
# A tibble: 332 x 6
   id          .pred_yes .pred_no  .row .pred_class purchased
  <chr>           <dbl>   <dbl>    <int>   <fct>       <fct>
train/test split  0.120    0.880     2      no          no
train/test split  0.755    0.245    17      yes         yes
train/test split  0.120    0.880    21      no          no
train/test split  0.120    0.880    22      no          no
train/test split  0.755    0.245    24      yes         yes
# ... with 327 more rows
在 R 中使用 tidymodels 建模

探索自定义指标

metric_set() 创建自定义指标集

  • ROC 曲线下面积、灵敏度、特异度

 

将预测数据传入 leads_metrics() 计算指标

leads_metrics <- metric_set(roc_auc, sens, spec)

leads_wkfl_preds %>% leads_metrics(truth = purchased, estimate = .pred_class, .pred_yes)
# A tibble: 3 x 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 sens    binary         0.75 
2 spec    binary         0.783
3 roc_auc binary         0.775
在 R 中使用 tidymodels 建模

贷款违约数据集

银行消费贷款的金融数据

  • 因变量为 loan_default

 

loans_df
# A tibble: 872 x 8
loan_default  loan_purpose   missed_payment_2_yr loan_amount interest_rate installment annual_income debt_to_income
 <fct>           <fct>            <fct>             <int>        <dbl>         <dbl>         <dbl>       <dbl>
 no        debt_consolidation      no              25000         5.47          855.         62823        39.4 
 yes       medical                 no              10000        10.2           364.         40000        24.1 
 no        small_business          no              13000         6.22          442.         65000        14.0 
 no        small_business          no              36000         5.97         1152.        125000         8.09
 yes       small_business          yes             12000        11.8           308.         65000        20.1 
# ... with 867 more rows
在 R 中使用 tidymodels 建模

让我们来构建工作流并练习!

在 R 中使用 tidymodels 建模

Preparing Video For Download...