首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Caret对R中的单个类的变量重要性

使用Caret对R中的单个类的变量重要性
EN

Stack Overflow用户
提问于 2021-09-27 12:42:47
回答 1查看 131关注 0票数 0

我使用随机森林来预测班级。现在,我正在尝试绘制每个类的变量重要性图。我已经使用了下面的代码,但它没有为我提供varImp类智慧,它为我提供了整个模型。谁能帮帮我。

谢谢。

代码语言:javascript
复制
odFit = train(x = df_5[,-22], 
              y = df_5$`kpres$cluster`,
              ntree=20,method="rf",metric = "Accuracy",trControl = control,tuneGrid = tunegrid
              )
odFit

varImp(odFit)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-27 13:04:50

只需在train函数中添加importance=TRUE,这与在randomForest包中添加importance(odFit)相同。

下面是一个可重复使用的示例:

代码语言:javascript
复制
library(caret)
data(iris)

control <- trainControl(method = "cv",10)
tunegrid <- expand.grid(mtry=2:ncol(iris)-1)
odFit = train(x = iris[,-5], 
              y = iris$Species,
              ntree=20,
              trControl = control,
              tuneGrid = tunegrid,
              importance=T
)
odFit

varImp(odFit)

这是输出

代码语言:javascript
复制
rf variable importance

  variables are sorted by maximum importance across the classes
             setosa versicolor virginica
Petal.Width   57.21     73.747    100.00
Petal.Length  61.90     79.981     77.49
Sepal.Length  20.01      2.867     40.47
Sepal.Width   20.01      0.000     15.73

您可以使用ggplot绘制变量重要性图

代码语言:javascript
复制
library(ggplot2)
vi <- varImp(odFit,scale=T)[[1]]
vi$var <-row.names(vi) 
vi <- reshape2::melt(vi)

ggplot(vi,aes(value,var,col=variable))+
  geom_point()+
  facet_wrap(~variable)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69346832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档