tidymodelsからの決定木の結果のプロット

Aug 22 2020

tidymodelsパッケージを使用してデシジョンツリーモデルを構築できましたが、結果を取得してツリーをプロットする方法がわかりません。rpartrpart.plotパッケージを使用して同じことを達成できることはわかっていますがtidymodels、それが私が学んでいることなので、むしろ使用したいと思います。以下はmtcarsデータを使用した例です。

library(tidymodels)
library(rpart)
library(rpart.plot)
library(dplyr) #contains mtcars

#data
df <- mtcars %>%
    mutate(gear = factor(gear))


#train/test
set.seed(1234)

df_split <- initial_split(df)
df_train <- training(df_split)
df_test <- testing(df_split)


df_recipe <- recipe(gear~ ., data = df) %>%
  step_normalize(all_numeric())


#building model
tree <- decision_tree() %>%
   set_engine("rpart") %>%
   set_mode("classification")

#workflow
 tree_wf <- workflow() %>%
   add_recipe(df_recipe) %>%
   add_model(tree) %>%
   fit(df_train) #results are found here 

rpart.plot(tree_wf$fit$fit) #error is here

The error I get says Error in rpart.plot(tree_wf$fit$fit) : Not an rpart object which makes sense but I am unaware if there is a package or step I am missing to convert the results into a format that rpart.plot will allow me to plot. This might not be possible but any help would be much appreciated.

回答

4 HanyNagaty Aug 22 2020 at 13:11

You can also use the workflows::pull_workflow_fit() function. It makes the code a little bit more elegant.

tree_fit <- tree_wf %>% 
  pull_workflow_fit()
rpart.plot(tree_fit$fit)
3 StephenMilborrow Aug 22 2020 at 04:37

The following works (note the extra $fit):

rpart.plot(tree_wf$fit$fit$fit)

Not a very elegant solution, but it does plot the tree.

Tested with parsnip 0.1.3 and rpart.plot 3.0.8.