評估模型效能

在 R 中使用 tidymodels 建立模型

David Svancer

Data Scientist

yardstick 函式的輸入

所有 yardstick 函式都需要含模型結果的 tibble

  • 具有真實應變數的欄位
    • mpg 資料中的 hwy
  • 具有模型預測的欄位
    • .pred
mpg_test_results
# A tibble: 57 x 3
     hwy   cty .pred
   <int> <int> <dbl>
 1    29    18  25.0
 2    31    20  27.7
 3    27    18  25.0
 4    26    18  25.0
 5    25    16  22.3
# ... with 47 more rows
在 R 中使用 tidymodels 建立模型

均方根誤差(RMSE)

RMSE 估計平均預測誤差

  • 使用 yardstickrmse() 計算
    • 輸入含模型結果的 tibble
    • truth 為真實目標值的欄位
    • estimate 為預測值的欄位
mpg_test_results %>% 
  rmse(truth = hwy, estimate = .pred)
# A tibble: 1 x 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard        1.93
在 R 中使用 tidymodels 建立模型

R squared 指標

衡量實際值與預測值的平方相關

  • 也稱為 決定係數
  • 介於 0 到 1
    • 若所有預測等於真實值,R squared 為 1
  • 使用 yardstickrsq() 計算
mpg_test_results %>% 
  rsq(truth = hwy, estimate = .pred)
# A tibble: 1 x 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rsq     standard       0.904
在 R 中使用 tidymodels 建立模型

R squared 圖

R squared 指標的視覺化

  • 模型預測對上真實結果
  • 直線 y = x
    • 代表 R squared 為 1
  • 用來發現模型效能的潛在問題
    • 非線性型態
    • 預測表現不佳的區域

Mpg 模型 R squared 圖

在 R 中使用 tidymodels 建立模型

繪製 R squared 圖

ggplot2 繪製 R squared 圖

  • 模型結果的 tibble
  • geom_point()
  • geom_abline()
  • coord_obs_pred()
ggplot(mpg_test_results, aes(x = hwy, y = .pred)) +

geom_point() +
geom_abline(color = 'blue', linetype = 2) +
coord_obs_pred() + labs(title = 'R-Squared Plot', y = 'Predicted Highway MPG', x = 'Actual Highway MPG')

Mpg 模型 R squared 圖

在 R 中使用 tidymodels 建立模型

簡化模型訓練流程

last_fit() 函式

  • 接收模型規格、模型公式與資料切分物件
  • 會執行:
    1. 建立訓練集與測試集
    2. 將模型套用於訓練資料
    3. 在測試資料計算指標與預測
    4. 回傳含所有結果的物件
lm_last_fit <- lm_model %>% 
  last_fit(hwy ~ cty, 
           split = mpg_split)
在 R 中使用 tidymodels 建立模型

彙整指標

collect_metrics() 函式

  • 接收 last_fit() 的結果
    • 回傳含測試資料集效能指標的 tibble
  • 迴歸模型的預設指標
    • RMSE
    • R squared
lm_last_fit %>% 
  collect_metrics()
# A tibble: 2 x 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard       1.93 
2 rsq     standard       0.904
在 R 中使用 tidymodels 建立模型

彙整預測

collect_predictions() 函式

  • 接收 last_fit() 的結果
    • 回傳含測試資料集預測的 tibble
    • 預測欄名為 .pred
    • 會包含應變數與其他列識別欄
lm_last_fit %>% 
  collect_predictions()
# A tibble: 57 x 4
   id               .pred  .row   hwy
   <chr>            <dbl> <int> <int>
 1 train/test split  25.0     1    29
 2 train/test split  27.7     3    31
 3 train/test split  25.0     7    27
 4 train/test split  25.0     8    26
 5 train/test split  22.3     9    25
# ... with 47 more rows
在 R 中使用 tidymodels 建立模型

來評估一些模型吧!

在 R 中使用 tidymodels 建立模型

Preparing Video For Download...