在 R 中使用 tidymodels 建模
David Svancer
Data Scientist
使用 cty 预测 hwy
$$hwy = \beta_{0} + \beta_{1} cty$$
模型参数
使用 cty 预测 hwy
$$hwy = \beta_{0} + \beta_{1} cty$$
模型参数
基于训练数据的估计参数
$$\small hwy = 0.77 + 1.35(cty)$$
parsnip 中的模型公式
通用形式
outcome ~ predictor_1 + predictor_2 + ...
速记法
outcome ~ .
将 cty 作为预测变量来预测 hwy
hwy ~ cty
R 中统一的模型规范语法
指定模型类型
指定引擎
指定模式
使用 parsnip 定义模型规范
linear_reg()
将 lm_model 传给 fit() 函数
data
lm_model <- linear_reg() %>%set_engine('lm') %>%set_mode('regression')
lm_fit <- lm_model %>%
fit(hwy ~ cty, data = mpg_training)
tidy() 函数
parsnip 模型对象term 与 estimate 列给出参数估计
tidy(lm_fit)
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.769 0.528 1.46 1.47e- 1
2 cty 1.35 0.0305 44.2 6.32e-97
将训练好的 parsnip 模型传给 predict()
new_data 指定要预测的数据集
predict() 的标准化输出
new_data 保持一致.predhwy_predictions <- lm_fit %>% predict(new_data = mpg_test)hwy_predictions
# A tibble: 57 x 1
.pred
<dbl>
1 25.0
2 27.7
3 25.0
4 25.0
5 22.3
# ... with 47 more rows
bind_cols() 函数
步骤
mpg_test 选取 hwy 和 ctybind_cols() 并添加预测列mpg_test_results <- mpg_test %>% select(hwy, cty) %>%bind_cols(hwy_predictions) 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 建模