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