I need to use a batch of models of RandomForest package. I decided to use a list list.of.models to store them. Now I don't know how to apply them. I append a list using
list.of.models <- append(list.of.models, randomForest(data, as.factor(label))
and then tried to use
sapply(list.of.models[length(list.of.models)], predict, data, type = "prob")
to call the last one but the problem is that randomForest returns a list of many values, not a learner.
What to do to add to list RF-model and then call it? For example lets take a source code
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,])
With append your're extending your model.list with the elements inside the RF.model, thus not recognized by predict.randomForest etc. because the outer container list and its attribute class="randomForest" are lost. Also data input is named newdata in predict.randomForest.
This should work:
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,])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.