如何绘制经过训练的 rpart 决策树模型的变量重要性?

pos*_*ion 2 plot r ggplot2 rpart

我使用 rpart 训练了一个模型,我想生成一个图,显示用于决策树的变量的变量重要性,但我不知道如何做。

我能够提取变量重要性。我尝试过 ggplot 但没有显示任何信息。我尝试在其上使用plot()函数,但它只给我一个平面图。我还尝试了plot.default,它好一点,但仍然是我想要的。

这是 rpart 模型训练:

argIDCART = rpart(Argument ~ ., 
                  data = trainSparse, 
                  method = "class")
Run Code Online (Sandbox Code Playgroud)

将变量重要性放入数据框中。

argPlot <- as.data.frame(argIDCART$variable.importance)
Run Code Online (Sandbox Code Playgroud)

这是打印内容的一部分:

       argIDCART$variable.importance
noth                             23.339346
humanitarian                     16.584430
council                          13.140252
law                              11.347241
presid                           11.231916
treati                            9.945111
support                           8.670958
Run Code Online (Sandbox Code Playgroud)

我想绘制一个图表来显示变量/特征名称及其数字重要性。我就是无法让它做到这一点。它似乎只有一列。我尝试使用单独的函数将它们分开,但也无法做到这一点。

ggplot(argPlot, aes(x = "variable importance", y = "feature"))
Run Code Online (Sandbox Code Playgroud)

只是打印空白。

其他情节看起来真的很糟糕。

plot.default(argPlot)
Run Code Online (Sandbox Code Playgroud)

看起来它绘制了点,但没有放置变量名称。

bbi*_*asi 7

由于没有可重现的示例,我使用 ggplot2 包和其他数据操作包基于自己的 R 数据集安装了我的响应。

library(rpart)
library(tidyverse)
fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
df <- data.frame(imp = fit$variable.importance)
df2 <- df %>% 
  tibble::rownames_to_column() %>% 
  dplyr::rename("variable" = rowname) %>% 
  dplyr::arrange(imp) %>%
  dplyr::mutate(variable = forcats::fct_inorder(variable))
ggplot2::ggplot(df2) +
  geom_col(aes(x = variable, y = imp),
           col = "black", show.legend = F) +
  coord_flip() +
  scale_fill_grey() +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot2::ggplot(df2) +
  geom_segment(aes(x = variable, y = 0, xend = variable, yend = imp), 
               size = 1.5, alpha = 0.7) +
  geom_point(aes(x = variable, y = imp, col = variable), 
             size = 4, show.legend = F) +
  coord_flip() +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述