评估模型性能

在 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² 指标

度量真实值与预测值的平方相关性

  • 也称为"判定系数"
  • 取值范围 0 到 1
    • 当所有预测等于真实值时,R² = 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² 图

R² 指标可视化

  • 模型预测 vs. 真实值
  • 直线 y = x
    • 表示 R² = 1
  • 用于发现模型性能问题
    • 非线性模式
    • 预测较差的区域

Mpg 模型 R² 图

在 R 中使用 tidymodels 建模

绘制 R² 图

ggplot2 绘制 R² 图

  • 含模型结果的 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² 图

在 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
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...