我使用以下代码构建了一个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)并通过网络购买我无法找到问题。
任何帮助将不胜感激!
答案 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)
我建议Introduction to Statistical Learning with Applications in R作为在randomForest
中使用R
包的好介绍。