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