簡體   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