[英]How do I generate a Decision Tree plot and a Variable Importance plot in Random Forest using R?
[英]How do I plot the Variable Importance of my trained rpart decision tree model?
我使用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)
看起來它繪制了點,但沒有放置變量名稱。
如果要查看變量名稱,最好將它們用作x軸上的標簽。
plot(argIDCART$variable.importance, xlab="variable",
ylab="Importance", xaxt = "n", pch=20)
axis(1, at=1:7, labels=row.names(argIDCART))
(您可能需要調整窗口大小以正確查看標簽。)
如果您有很多變量,則可能需要旋轉變量名稱以使其不重疊。
par(mar=c(7,4,3,2))
plot(argIDCART$variable.importance, xlab="variable",
ylab="Importance", xaxt = "n", pch=20)
axis(1, at=1:7, labels=row.names(argIDCART), las=2)
argIDCART = read.table(text="variable.importance
noth 23.339346
humanitarian 16.584430
council 13.140252
law 11.347241
presid 11.231916
treati 9.945111
support 8.670958",
header=TRUE)
由於沒有可重現的示例,我使用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()
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.