Настройка графика важности - R - PullRequest
0 голосов
/ 28 апреля 2020

Я работаю над записью анализа результатов и хотел изменить свой график MeanDecreaseAccuracy с графика важности переменной после выполнения Случайных Лесов. Я хочу взять только график MeanDecreaseAccuracy и превратить его в график, чтобы сделать визуализацию лучше, чем то, что отображается в данный момент.

Каков наилучший способ сделать это?

Мой текущий код (Перед этим много чего происходит, но для целей этого примера этого должно быть достаточно):

wine=read.csv("wine_dataset.csv")
wine$quality01[wine$quality >= 7] <- 1
wine$quality01[wine$quality < 7] <- 0
wine$quality01=as.factor(wine$quality01)
summary(wine)
num_data <- wine[,sapply(wine,is.numeric)]
hist.data.frame(num_data)

set.seed(8, sample.kind = "Rounding") #Set Seed to make sure results are repeatable
wine.bag=randomForest(quality01 ~ alcohol + volatile_acidity + sulphates + residual_sugar + 
    chlorides + free_sulfur_dioxide + fixed_acidity + pH + density + 
    citric_acid,data=wine,mtry=3,importance=T)    #Use Random Forest with a mtry value of 3 to fit the model

wine.bag #Review the Random Forest Results
plot(wine.bag) #Plot the Random Forest Results
imp=as.data.frame(importance(wine.bag)) #Analyze the importance of each variable in the model
imp=cbind(vars=rownames(imp),imp)
barplot(imp$MeanDecreaseAccuracy, names.arg=imp$vars)

Мой вывод в настоящее время:

enter image description here

Текущий код, который я использую, можно найти здесь :

Ответы [ 2 ]

2 голосов
/ 28 апреля 2020

Вот несколько вариантов:

library(randomForest)
library(tidyverse)

# Random forest model
iris.rf <- randomForest(Species ~ ., data=iris, importance=TRUE)

# Get importance values as a data frame
imp = as.data.frame(importance(iris.rf))
imp = cbind(vars=rownames(imp), imp)
imp = imp[order(imp$MeanDecreaseAccuracy),]
imp$vars = factor(imp$vars, levels=unique(imp$vars))

barplot(imp$MeanDecreaseAccuracy, names.arg=imp$vars)

enter image description here

imp %>% 
  pivot_longer(cols=matches("Mean")) %>% 
  ggplot(aes(value, vars)) +
  geom_col() +
  geom_text(aes(label=round(value), x=0.5*value), size=3, colour="white") +
  facet_grid(. ~ name, scales="free_x") +
  scale_x_continuous(expand=expansion(c(0,0.04))) +
  theme_bw() +
  theme(panel.grid.minor=element_blank(),
        panel.grid.major=element_blank(),
        axis.title=element_blank())

enter image description here

Я также не отказался бы от точечной диаграммы, которая (IMHO) является более чистой визуализацией. Вот параметры, которые более настроены, чем встроенный вывод в вашем вопросе:

dotchart(imp$MeanDecreaseAccuracy, imp$vars, 
         xlim=c(0,max(imp$MeanDecreaseAccuracy)), pch=16)

enter image description here

imp %>% 
  pivot_longer(cols=matches("Mean")) %>% 
  ggplot(aes(value, vars)) +
  geom_point() +
  facet_grid(. ~ name) +
  scale_x_continuous(limits=c(0,NA), expand=expansion(c(0,0.04))) +
  theme_bw() +
  theme(panel.grid.minor=element_blank(),
        panel.grid.major.x=element_blank(),
        panel.grid.major.y=element_line(),
        axis.title=element_blank())

enter image description here

Вы также можете построить сами значения вместо маркеров точек. Например:

imp %>% 
  pivot_longer(cols=matches("Mean")) %>% 
  ggplot(aes(value, vars)) +
  geom_text(aes(label=round(value,1)), size=3) +
  facet_grid(. ~ name, scales="free_x") +
  scale_x_continuous(limits=c(0,NA), expand=expansion(c(0,0.06))) +
  theme_bw() +
  theme(panel.grid.minor=element_blank(),
        panel.grid.major.x=element_blank(),
        panel.grid.major.y=element_line(),
        axis.title=element_blank())

enter image description here

1 голос
/ 28 апреля 2020

Вы также можете рассмотреть леденцы на палочках (например, из ggalt), или сделать как здесь: https://uc-r.github.io/lollipop Пример:

suppressPackageStartupMessages({
    library(ggalt)
    library(randomForest)
    library(data.table)
})

# Random forest model (from @eipi10)
iris.rf <- randomForest(Species ~ ., data=iris, importance=TRUE)
imp <- data.table(importance(iris.rf), keep.rownames = TRUE, 
                  key = "MeanDecreaseAccuracy")
imp[, rn := factor(rn, unique(rn))]
ggplot(melt(imp, id.vars="rn")[grep("Mean", variable)], 
       aes(x=rn, y=value, label = round(value, 1))) + 
    geom_lollipop(point.size = 3, point.colour = "cadetblue") +
    geom_text(nudge_y = 5) +
    coord_flip() +
    facet_wrap(~variable) +
    theme_minimal() +
    labs(y="Percent", x=NULL)

Создано в 2020-04-28 пакетом Представ (v0.3.0)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...