繁体   English   中英

R.如何将sapply()应用于随机森林

[英]R. How to apply sapply() to random forest

我需要使用一批模型的RandomForest包。 我决定使用list.of.models列表来存储它们。 现在我不知道如何应用它们。 我附上清单

list.of.models <- append(list.of.models, randomForest(data, as.factor(label))

然后尝试使用

sapply(list.of.models[length(list.of.models)], predict, data, type = "prob") 

调用最后一个,但问题是randomForest返回许多值的列表,而不是学习者。

如何添加到列表RF模型然后调用它? 例如让我们获取源代码

data(iris)
set.seed(111)
ind <- sample(2, nrow(iris), replace = TRUE, prob=c(0.8, 0.2))
iris.rf <- randomForest(Species ~ ., data=iris[ind == 1,])
iris.pred <- predict(iris.rf, iris[ind == 2,])

追加后,您将用RF.model内的元素扩展您的model.list,由于外部容器列表及其属性class =“ randomForest”丢失了,因此无法被predict.randomForest等识别。 另外,数据输入在predict.randomForest中也称为newdata。

这应该工作:

set.seed(1234)
library(randomForest)
data(iris)

test = sample(150,25)

#create 3 models
RF.models = lapply(1:3,function(mtry) {
    randomForest(formula=Species~.,data=iris[-test,],mtry=mtry)
})
#append extra model
RF.models[[length(RF.models)+1]] = randomForest(formula=Species~.,data=iris[-test,],mtry=4)
summary(RF.models)

#predict all models
sapply(RF.models,predict,newdata=iris[test,])

#predict one model
predict(RF.models[[length(RF.models)]],newdata=iris[test,])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM