在randomForest R中使用VarImpPlot时出现问题

时间:2017-01-09 13:07:52

标签: r random-forest

我使用以下代码构建了一个RandomForest模型:

library(randomForest)

set.seed(101)
RFs1 = ERC[sample(nrow(ERC),100000),]
RFs2  <-  RFs1[,-c(1,2,3,228,229,230,232,233,234,235,240)] 
RFs2 <- RFs2[complete.cases(RFs2),] # handling missing values

RFfit <- randomForest(as.factor(RFs2$earlyR)~., data=RFs2[,-231])

VI_F <- importance(RFfit)
varImpPlot(VI_F, type = 2) 

现在,当我试图策划Feature Importance时,我收到以下错误:

  

varImpPlot中的错误(VI_F,type = 2):     此函数仅适用于“randomForest&#39;

”类的对象

我在这里寻找问题的解决方案(Stack Overflow)并通过网络购买我无法找到问题。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

代码有两个问题,我将尝试解释。我将使用mtcars执行此操作,因为您未提供示例数据。首先,您需要将importance = TRUE传递给randomForest

mtrf <- randomForest(mpg ~ . , data = mtcars, importance = TRUE)

您可以将importance作为带有

的表格

importance(mtrf)

> importance(mtrf)
       %IncMSE IncNodePurity
cyl  11.584480    194.396219
disp 12.560117    230.427777
hp   12.908195    201.095073
drat  5.238172     69.766801
wt   12.449930    233.921376
qsec  3.705991     27.621441
vs    4.221830     27.044382
am    1.982329      9.416001
gear  3.472656     18.282543
carb  6.116177     28.398651

但是,要绘制该图,您需要使用varImpPlot参数在您创建的实际randomForest对象上调用importance = TRUE

varImpPlot(mtrf)

enter image description here

我建议Introduction to Statistical Learning with Applications in R作为在randomForest中使用R包的好介绍。