在 R 中使用 tidymodels 建模
David Svancer
Data Scientist
决策树将自变量空间切分为矩形区域
递归二元划分

决策树将自变量空间切分为矩形区域
递归二元划分

决策树将自变量空间切分为矩形区域
递归二元划分

决策树将自变量空间切分为矩形区域
递归二元划分

决策树将自变量空间切分为矩形区域
递归二元划分
生成不同的矩形区域


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

在 parsnip 中指定模型
decision_tree()parsnip 中决策树模型的通用接口'rpart''classification' 或 'regression''classification'dt_model <- decision_tree() %>%set_engine('rpart') %>%set_mode('classification')
线索评分数据的特征变换
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()
workflows 包用于简化建模流程
parsnip 模型与 recipe 对象合并为单个 workflow 对象
使用 workflow() 初始化
add_model() 添加模型add_recipe() 添加 reciperecipeleads_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
训练 workflow 对象
workflow 传入 last_fit(),并提供数据切分对象collect_metrics() 查看评估结果幕后步骤
recipeleads_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
用 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
用 metric_set() 创建自定义指标集
将预测数据传入 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
银行消费贷款的金融数据
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 建模