Bagging算法在R语言中可使用随机森林(random forests)函数实现。以下是使用randomForest函数实现Bagging算法的示例代码:
# 导入数据
data(iris)
# 安装randomForest包
install.packages("randomForest")
# 导入包
library(randomForest)
# 将数据集划分为训练集和测试集
trainIndex <- sample(1:nrow(iris), size=0.8*nrow(iris))
train <- iris[trainIndex,]
test <- iris[-trainIndex,]
# 使用randomForest函数实现Bagging算法
set.seed(123)
baggingModel <- randomForest(Species ~ ., data=train, ntree=100)
# 预测结果
predictions <- predict(baggingModel, test)
# 计算准确率
accuracy <- sum(predictions == test$Species)/length(predictions)
print(paste("Bagging算法准确率为:", accuracy))
在此示例中,我们导入了iris数据集并使用randomForest函数实现了Bagging算法。我们将数据集划分为训练集和测试集,并使用randomForest函数在训练集上训练了100个决策树。最终,我们使用预测函数预测测试集的结果,并计算了准确率。
参考资料:
- Breiman, Leo. "Random forests." Machine learning 45.1 (2001): 5-32.
- randomForest Package Documentation in R. https://cran.r-project.org/web/packages/randomForest/randomForest.pdf.