Rで何かをしたり、読書をするブログ

政府統計の総合窓口のデータや、OECDやUCIやのデータを使って、Rの練習をしています。ときどき、読書記録も載せています。

2010年から2024年のプロ野球の成績のデータの分析 8 - ランダムフォレストがロジスティクス回帰に負けることもある。

www.crosshyou.info

の続きです。今回はランダムフォレストで予測してみます。

まず、モデルを作成します。エンジンは randomForest を使いました。

mtryなどのハイパーパラメータはあとでチューニングします。

レシピの作成をします。

文字列型データのダミー変数への変換と数値型のデータの標準化をします。

ワークフローの作成をします。

クロスバリデーションを作成します。

チューングリッドを作成します。

チューニングします。

最適なパラメータを決定します。

最適なパラメータで最終モデルを作成をします。

最終ワークフローの作成をします。

最終ワークフローでfitします。

テスト用のデータで予測します。

正解率を計算します。

正解率は72.2%でした。前回のロジスティクス回帰での正解率も72.2%で同じでしたね。

AUCを計算します。

AUCは0.813でした。前回のロジスティクス回帰では0.824でしたから、ランダムフォレストのほうが悪いですね。

ROC曲線を描きます。

前回のロジスティクス回帰でのROC曲線は下のようです。こちらのほうが滑らかでいい感じですね。

今回は以上です。ランダムフォレストがロジスティクス回帰よりも悪いときがあるのですね。

はじめから読むには、

www.crosshyou.info

です。

今回のコードは以下になります。

#
# ランダムフォレストで予測
# モデルの作成
rf_model <- rand_forest(
  mtry = tune(),
  trees = tune(),
  min_n = tune()
) |> 
  set_engine("randomForest") |> 
  set_mode("classification")
rf_model
#
# ランダムフォレストで予測
# レシピの作成
rf_recipe <- recipe(league ~ ., data = train_data) |> 
  step_dummy(all_nominal_predictors()) |> 
  step_normalize(all_numeric_predictors())
rf_recipe
#
# ランダムフォレストで予測
# ワークフローの作成
rf_workflow <- workflow() |> 
  add_model(rf_model) |> 
  add_recipe(rf_recipe)
rf_workflow
#
# ランダムフォレストで予測
# クロスバリデーションの作成
set.seed(809)
rf_cv_folds <- vfold_cv(train_data, v = 10)
rf_cv_folds
#
# ランダムフォレストで予測
# チューニンググリッドの作成
rf_grid <- grid_regular(
  mtry(range = c(2, 5)),
  trees(range = c(200, 1000)),
  min_n(range(3, 7)),
  levels = 5
)
rf_grid
#
# ランダムフォレストで予測
# ハイパーパラメータのチューニング
rf_tune <- tune_grid(
  rf_workflow,
  resamples = rf_cv_folds,
  grid = rf_grid,
  metrics = metric_set(roc_auc)
)
rf_tune
#
# ランダムフォレストで予測
# 最適なパラメータを作成
rf_select_best <- select_best(rf_tune, "roc_auc")
rf_select_best
#
# ランダムフォレストで予測
# 最終モデルを作成
rf_final_model <- finalize_model(rf_model, rf_select_best)
rf_final_model
#
# ランダムフォレストで予測
# 最終ワークフローの作成
rf_final_workflow <-
  workflow() |> 
  add_recipe(rf_recipe) |> 
  add_model(rf_final_model)
rf_final_workflow
#
# ランダムフォレストで予測
# 最終モデルでfit
rf_fit <- fit(rf_final_workflow, train_data)
rf_fit
#
# ランダムフォレストで予測
# テスト用のデータで予測
rf_pred <- predict(rf_fit, new_data = test_data) |> 
  bind_cols(predict(rf_fit, new_data = test_data, type = "prob")) |> 
  bind_cols(test_data)
rf_pred
#
# ランダムフォレストで予測
# 正解率
accuracy(rf_pred, truth = league, estimate = .pred_class)
#
# ランダムフォレストで予測
# AUC
roc_auc(rf_pred, truth = league, .pred_C)
#
# ランダムフォレストで予測
# ROC曲線
roc_curve(rf_pred, truth = league, .pred_C) |> 
  autoplot()
#

 

 

(冒頭の画像は Bing Image Creator で生成しました。プロンプトは close up of orange Marigold flowers, on the vast green grass fields, under the blue sky, photograph)