r - 如何在bagging中创建模型对象?

标签 r machine-learning

我尝试为 Ensemble of Ensemble 建模创建一个函数:

library(foreach)
library(randomForest)
set.seed(10)
Y<-round(runif(1000))
x1<-c(1:1000)*runif(1000,min=0,max=2)
x2<-c(1:1000)*runif(1000,min=0,max=2)
x3<-c(1:1000)*runif(1000,min=0,max=2)
all_data<-data.frame(Y,x1,x2,x3)
bagging = function(dataFile, length_divisor = 4, iterations = 100)
{
    fit = list()
    predictions = foreach(m = 1 : iterations, .combine = cbind) %do% 
    {
        dataFile$Y = as.factor(dataFile$Y)
        rf_fit = randomForest(Y ~ ., data = dataFile, ntree = 100)
        fit[[m]] = rf_fit
        rf_fit$votes[,2]
    }
    rowMeans(predictions)
    return(list(formula = as.formula("Y ~ ."), trees = fit, ntree = 100, class = dataFile$Y, votes = predictions))
}
final_model = bagging(all_data)
predict(final_model, TestData) # It says predict doesn't support final_model object
# Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "list"

它说 -

Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "list".

我需要上述函数bagging来返回聚合模型对象,以便我可以预测新数据集。

最佳答案

您的bagging函数仅返回一个任意列表。 Predict 通过查看第一个参数的类来了解要执行的“正确操作”。我假设您想从列表中存储的 randomForest 对象进行预测?您可以使用 Map() 循环遍历您的列表。例如

Map(function(x) predict(x, TestData), final_model$trees)

(未经测试,因为您似乎没有提供TestData)

关于r - 如何在bagging中创建模型对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33514130/

相关文章:

r - 在 Rstudio 中使用 if 和 else 语句定义分段函数

c - 如何从 R 调用 C 函数?

r - 在 R 的插入符包中使用 adaboost

r - 如何协调 facet_wrap 中的轴并缩放 ="free_y"?

R 管道 (%>%) 不适用于复制功能

r - 识别在 x 天内发生给定事件序列的记录

machine-learning - 机器学习/NLP文本分类: training a model from corpus of text files - scikit learn

machine-learning - 基于深度学习的图像分类器是否应该包含负类

machine-learning - 是否可以从类概率中学习分类器(在sklearn中)

c# Encog 框架,神经网络,为什么在训练网络时会出现内部错误?