R での tidymodels によるモデリング
David Svancer
Data Scientist
すべての yardstick 関数はモデル結果のtibbleを必要とする
hwy.predmpg_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
RMSEは平均予測誤差を推定する
yardstick の rmse() で計算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
実測値と予測値の相関の二乗を測る指標
yardstick の rsq() で計算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二乗)の可視化
ggplot2でR二乗プロットを作成
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')
last_fit() 関数
lm_last_fit <- lm_model %>%
last_fit(hwy ~ cty,
split = mpg_split)
collect_metrics() 関数
last_fit() の結果を受け取り、テストデータで得た性能指標のtibbleを返す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
collect_predictions() 関数
last_fit() の結果を受け取り、テストデータの予測を含むtibbleを返す.predlm_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 によるモデリング