機器學習工作流程

在 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

潛在客戶評分資料的轉換

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

結合模型與 recipes

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

用 workflows 擬合模型

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

一起來練習建立 workflows!

在 R 中使用 tidymodels 建立模型

Preparing Video For Download...