tidymodels 生態系統

在 R 中使用 tidymodels 建立模型

David Svancer

Data Scientist

機器學習套件集合

tidymodels 套件

在 R 中使用 tidymodels 建立模型

機器學習套件集合

使用 rsample 進行資料重抽樣

在 R 中使用 tidymodels 建立模型

機器學習套件集合

使用 recipes 進行特徵工程

在 R 中使用 tidymodels 建立模型

機器學習套件集合

使用 parnsip 進行模型擬合

在 R 中使用 tidymodels 建立模型

機器學習套件集合

使用 tune 與 dials 進行模型調參

在 R 中使用 tidymodels 建立模型

機器學習套件集合

使用 yardstick 進行模型評估

在 R 中使用 tidymodels 建立模型

監督式機器學習

使用標註資料來擬合模型的機器學習分支

回歸

  • 預測「連續數值」結果
    • 例如房屋成交價

 

分類

  • 預測「類別型」結果
    • 例如員工是否會離職
left_company miles_from_home salary
no 1 84500
yes 10 64820
no 5 76490
yes 19 68540

 

tidymodels「變數角色」

  • 「left_company」是結果變數
  • 「miles_from_home」與「salary」是預測變數
在 R 中使用 tidymodels 建立模型

資料重抽樣

 

建立訓練集與測試集

  • 可防止「過度擬合」
  • 常見比率為 75% 訓練、25% 測試

訓練資料

  • 特徵工程
  • 模型擬合與調參

測試資料

  • 估計模型在新資料上的表現

建立訓練與測試資料集

在 R 中使用 tidymodels 建立模型

燃油效率資料

美國環保署的車輛燃油效率資料

  • 結果變數為 hwy:高速公路油耗(每加侖英里數,mpg)
mpg
# A tibble: 234 x 11
     hwy   cty displ   cyl manufacturer model       year trans      drv   fl    class  
   <int> <int> <dbl> <int> <chr>        <chr>      <int> <chr>      <chr> <chr> <chr>  
 1    29    18   1.8     4 audi         a4          1999 auto(l5)   f     p     compact
 2    29    21   1.8     4 audi         a4          1999 manual(m5) f     p     compact
 3    31    20   2       4 audi         a4          2008 manual(m6) f     p     compact
 4    30    21   2       4 audi         a4          2008 auto(av)   f     p     compact
 5    26    16   2.8     6 audi         a4          1999 auto(l5)   f     p     compact
# ... with 224 more rows
在 R 中使用 tidymodels 建立模型

使用 tidymodels 進行資料重抽樣

  • initial_split()

    • 指定建立訓練與測試資料集的方式
    • prop 指定放入訓練集的比例
    • strata 依結果變數進行分層
  • 將 split 物件傳入 training() 函式

 

  • 將 split 物件傳入 testing() 函式
library(tidymodels)
mpg_split <- initial_split(mpg,
                           prop = 0.75,
                           strata = hwy)

 

mpg_training <- mpg_split %>%
  training()
mpg_test <- mpg_split %>%
  testing()
在 R 中使用 tidymodels 建立模型

房屋交易資料

2015–2016 年美國華盛頓州西雅圖地區的房屋交易

home_sales
# A tibble: 1,492 x 8
   selling_price home_age bedrooms bathrooms sqft_living sqft_lot sqft_basement floors
           <dbl>    <dbl>    <dbl>     <dbl>       <dbl>    <dbl>         <dbl>  <dbl>
 1        487000       10        4      2.5         2540     5001             0      2
 2        465000       10        3      2.25        1530     1245           480      2
 3        411000       18        2      2           1130     1148           330      2
 4        635000        4        3      2.5         3350     4007           800      2
 5        380000       24        5      2.5         2130     8428             0      2
# ... with 1,482 more rows
在 R 中使用 tidymodels 建立模型

一起來練習吧!

在 R 中使用 tidymodels 建立模型

Preparing Video For Download...