gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:49:56 25 4
gpt4 key购买 nike

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

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

这里是rpart模型训练:

argIDCART = rpart(Argument ~ ., 
data = trainSparse,
method = "class")

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

argPlot <- as.data.frame(argIDCART$variable.importance)

这是打印内容的一部分:

       argIDCART$variable.importance
noth 23.339346
humanitarian 16.584430
council 13.140252
law 11.347241
presid 11.231916
treati 9.945111
support 8.670958

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

ggplot(argPlot, aes(x = "variable importance", y = "feature"))

只打印空白。

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

plot.default(argPlot)

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

最佳答案

由于没有可用的可重现示例,我使用 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()

enter image description here

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()

enter image description here

关于r - 如何绘制经过训练的 rpart 决策树模型的变量重要性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com