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

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

UCI Machine Learning Repository の Obesity データの分析9 - 決定木モデルで予測。正解率は 94.2%

www.crosshyou.info

今回は決定木モデルで予測します。decision_tree() 関数で、エンジンは rpart を使います。モデルを作成します。

ワークフローを作ります。

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

チューニングを実行します。

最適なパラメータを取り出します。

最適なパラメータを使って最終ワークフローを作ります。

トレーニング用のデータで学習します。

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

おお!1行目から10行目まで全部正解です。すごいですね。

混合行列を作成します。

Obesity Type III はパーフェクトに予測しています。

正解率はどのくらいでしょうか?

94.2% の正解率は、いままでで一番ですね。

今回は以上です。

次回は

www.crosshyou.info

です。

 

はじめから読むには、

www.crosshyou.info

です。

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

#
# モデルの作成
tree_mod <- decision_tree(
  cost_complexity = tune(),
  tree_depth = tune(),
  min_n = tune()
) |> 
  set_engine("rpart") |> 
  set_mode("classification")
#
# ワークフローの作成
tree_wf <- workflow() |> 
  add_recipe(rec) |> 
  add_model(tree_mod)
#
# チューニンググリッドの作成
tree_grid <- grid_regular(
  cost_complexity(range = c(-5, -1)),
  tree_depth(range = c(1, 10)),
  min_n(range = c(2, 20)),
  levels = 5
)
#
# チューニングの実行
set.seed(123)
tree_tuned <- tune_grid(
  tree_wf,
  resamples = folds,
  grid = tree_grid,
  metrics = metric_set(accuracy)
)
#
# 最適なパラメータ
tree_params <- select_best(tree_tuned, metric = "accuracy")
tree_params
#
# 最適なパラメータで最終ワークフロー
tree_wf_final <- finalize_workflow(tree_wf, tree_params)
#
# トレーニング用のデータで学習
tree_fit <- fit(tree_wf_final, data = df_train)
#
# テスト用のデータで予測
tree_pred <- predict(tree_fit, new_data = df_test) |> 
  bind_cols(df_test |> select(obesity))
tree_pred
#
# 混合行列を作成
conf_mat(tree_pred, truth = obesity, estimate = .pred_class)
#
# 正解率
accuracy(tree_pred, truth = obesity, estimate = .pred_class)
#

(冒頭の画像は Bing Image Creator で生成しました。プロンプトは Landscape of photograph, showing vast desert land, a few coconut trees, small oasis, bule sky and one white cloud, closing up of blue morning glory flowers. です。)