在 R 中使用 tidymodels 建模
David Svancer
Data Scientist
创建训练集与测试集是建模的第一步
缺点
用于探索模型表现的重采样技术

用于探索模型表现的重采样技术

执行 5 折交叉验证

执行 5 折交叉验证

执行 5 折交叉验证

执行 5 折交叉验证
共得到五个模型表现估计

vfold_cv() 函数
vstratavfold_cv() 前执行 set.seed()splitsset.seed(214) leads_folds <- vfold_cv(leads_training,v = 10,strata = purchased)leads_folds
# 10-fold cross-validation using stratification
# A tibble: 10 x 2
splits id
<list> <chr>
1 <split [896/100]> Fold01
2 <split [896/100]> Fold02
3 <split [896/100]> Fold03
. ................ ......
9 <split [897/99]> Fold09
10 <split [897/99]> Fold10
fit_resamples() 函数
parsnip 模型或 workflow 对象resamplesmetrics
每个度量估计 10 次
mean 列leads_rs_fit <- leads_wkfl %>%fit_resamples(resamples = leads_folds,metrics = leads_metrics)leads_rs_fit %>% collect_metrics()
# A tibble: 3 x 5
.metric .estimator mean n std_err
<chr> <chr> <dbl> <int> <dbl>
1 roc_auc binary 0.823 10 0.0147
2 sens binary 0.786 10 0.0203
3 spec binary 0.855 10 0.0159
collect_metrics() 函数
summarize = FALSE 可返回每个折的全部度量估计.metric 列标识度量.estimate 列给出每折的估计值rs_metrics <- leads_rs_fit %>% collect_metrics(summarize = FALSE)rs_metrics
# A tibble: 30 x 4
id .metric .estimator .estimate
<chr> <chr> <chr> <dbl>
1 Fold01 sens binary 0.861
2 Fold01 spec binary 0.891
3 Fold01 roc_auc binary 0.885
4 Fold02 sens binary 0.778
5 Fold02 spec binary 0.969
6 Fold02 roc_auc binary 0.885
# ... with 24 more rows
collect_metrics() 返回 tibble
dplyr 汇总结果rs_metrics 开始.metric 分组summarize() 计算统计量rs_metrics %>%group_by(.metric) %>%summarize(min = min(.estimate), median = median(.estimate), max = max(.estimate), mean = mean(.estimate), sd = sd(.estimate))
# A tibble: 3 x 6
.metric min median max mean sd
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 roc_auc 0.758 0.806 0.885 0.823 0.0466
2 sens 0.667 0.792 0.861 0.786 0.0642
3 spec 0.810 0.843 0.969 0.855 0.0502
用 fit_resamples() 训练的模型无法对新数据给出预测
predict() 不接受重采样结果对象fit_resample() 的用途
predict(leads_rs_fit,
new_data = leads_test)
Error in UseMethod("predict") :
no applicable method for 'predict' applied to
an object of class
"c('resample_results',
'tune_results',
'tbl_df',
'tbl', 'data.frame')"
在 R 中使用 tidymodels 建模