完整建模流程

在 R 中使用 tidymodels 建模

David Svancer

Data Scientist

数据重采样

创建训练集与测试集

  • initial_split()
    • 创建数据切分对象
  • training()
    • 构建训练集
  • testing()
    • 构建测试集
leads_split <- initial_split(leads_df, 
                             strata = purchased)

leads_training <- leads_split %>% training()
leads_test <- leads_split %>% testing()
在 R 中使用 tidymodels 建模

模型规范(Specification)

parsnip 指定模型

  • logistic_reg()
    • 逻辑回归的通用接口
  • set_engine()
    • 'glm' 引擎
  • set_mode()
    • purchased 为名义型因变量
    • 模式应为 'classification'
logistic_model <- logistic_reg() %>%

set_engine('glm') %>%
set_mode('classification')
Logistic Regression Model 
Specification (classification)

Computational engine: glm
在 R 中使用 tidymodels 建模

特征工程

recipes 指定特征工程步骤

  • recipe()
    • 模型公式与训练数据
  • step_*() 函数
    • 顺序化的预处理步骤
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 建模

配方训练(Recipe training)

在训练集上训练特征工程步骤

  • prep()
    • recipe 对象传给 prep()
    • 使用训练数据 leads_training
leads_recipe_prep <- leads_recipe %>% 
  prep(training = leads_training)
leads_recipe_prep
Data Recipe
Inputs:
      role #variables
   outcome          1
 predictor          6
Training data contained 996 data points 
and no missing data.

Operations:
Correlation filter removed pages_per_visit [trained]
Centering and scaling for total_visits ... [trained]
Dummy variables from lead_source, us_location [trained]
在 R 中使用 tidymodels 建模

预处理训练数据

将已训练的 recipe 应用于训练集,并保存结果用于拟合模型

leads_training_prep <- leads_recipe_prep %>% 
  bake(new_data = NULL)

leads_training_prep
# A tibble: 996 x 11
total_visits  total_time   ... lead_source_email  lead_source_organic_search ...  us_location_west
     <dbl>      <dbl>                <dbl>                      <dbl>                    <dbl>        
 1    0.611      0.958      ...       0                          0            ...         1
 2    0.103     -0.747      ...       1                          0            ...         0
 3    0.611     -0.278      ...       0                          1            ...         1
 4   -0.151     -0.842      ...       0                          0            ...         1
 5   -0.659      1.19       ...       1                          0            ...         0 
# ... with 991 more rows
在 R 中使用 tidymodels 建模

预处理测试数据

将已训练的 recipe 应用于测试集,并保存结果用于评估

leads_test_prep <- leads_recipe_prep %>% 
  bake(new_data = leads_test)

leads_test_prep
# A tibble: 332 x 11
 total_visits  total_time  ...  lead_source_email  lead_source_organic_search ...  us_location_west
     <dbl>      <dbl>                <dbl>                      <dbl>                    <dbl>        
 1    0.864     -0.984     ...        0                          0            ...         1
 2   -0.151      1.33      ...        0                          0            ...         0
 3   -0.405     -0.843     ...        0                          1            ...         1
 4   -0.659     -1.14      ...        1                          0            ...         0
 5    1.12       0.725     ...        0                          0            ...         1   
# ... with 327 more rows
在 R 中使用 tidymodels 建模

模型拟合与预测

使用 fit() 训练逻辑回归模型

  • 使用"预处理后的训练集"leads_training_prep

 

predict() 获取预测

  • 预测类别与概率
  • 使用"预处理后的测试集"leads_test_prep
logistic_fit <- logistic_model %>% 
  fit(purchased ~ .,
      data = leads_training_prep)

 

class_preds <- predict(logistic_fit, 
                       new_data = leads_test_prep,
                       type = 'class')

prob_preds <- predict(logistic_fit, 
                      new_data = leads_test_prep,
                      type = 'prob')
在 R 中使用 tidymodels 建模

合并预测结果

将预测合成为 yardstick 指标函数可用的数据集

  • 从测试集选择真实标签 purchased
  • bind_cols() 绑定预测
leads_results <- leads_test %>% 
  select(purchased) %>%

bind_cols(class_preds, prob_preds)
leads_results
# A tibble: 332 x 4
   purchased .pred_class .pred_yes .pred_no
   <fct>     <fct>           <dbl>    <dbl>
 1 no        no             0.257     0.743
 2 yes       yes            0.896     0.104
 3 no        no             0.0852    0.915
 4 no        no             0.183     0.817
 5 yes       yes            0.776     0.224
# ... with 327 more rows
在 R 中使用 tidymodels 建模

模型评估

使用 yardstick 评估模型性能

  • 该结果数据可配合所有 yardstick 指标函数进行评估
  • 混淆矩阵、灵敏度、特异度等指标
leads_results %>% 
  conf_mat(truth = purchased, 
           estimate = .pred_class)

 

          Truth
Prediction yes  no
       yes  77  34
       no   43 178
在 R 中使用 tidymodels 建模

Passons à la pratique !

在 R 中使用 tidymodels 建模

Preparing Video For Download...