【问题标题】:How to create Random Forest from scratch in R (without the randomforest package)如何在 R 中从头开始创建随机森林(没有 randomforest 包)
【发布时间】:2017-12-25 14:16:57
【问题描述】:

这是我想通过使用RandomForest 包来使用随机森林的方式:

library (randomForest)
rf1 <- randomForest(CLA ~ ., dat, ntree=100, norm.votes=FALSE)
p1 <- predict(rf1, testing, type='response')
confMat_rf1 <- table(p1,testing_CLA$CLA)
accuracy_rf1 <- sum(diag(confMat_rf1))/sum(confMat_rf1)

我根本不想使用RandomForest 包。给定一个数据集(dat)并使用rpartrandomforest 包的默认值,我怎样才能得到相同的结果?例如,对于 100 棵决策树,我需要运行以下命令:

for(i in 1:100){
cart.models[[i]]<-rpart(CLA~ ., data = random_dataset[[i]],cp=-1)
} 

每个random_dataset[[i]] 将随机选择默认数量的属性和行。另外,rpart 是否用于randomforest

【问题讨论】:

  • 您是在问如何在仅给定决策树包的情况下进行随机森林?你为什么想做这个?这些软件包已经针对使用进行了优化。
  • 沙洛姆@TimBiegeleisen,谢谢!我有几个原因。其中之一是向我的学生演示该过程,此外我想控制一些参数并更改一些算法。
  • 如果你觉得很学术,你可以看看randomForest的源代码。它不会像你想象的那么糟糕。在进入之前,请确保您了解通用算法。
  • 我想在 R 环境中做,因为我需要使用 R 和其他包的更多功能。
  • @Avi,您可能会发现 this 对演示内容很有用

标签: r random-forest rpart


【解决方案1】:

可以通过在训练集上使用 rpart 和 bootstrap 样本训练多棵树以及训练集的特征来模拟训练随机森林。 以下代码 sn-p 训练 10 棵树以对鸢尾花物种进行分类,并返回每棵树的袋外准确率的树列表。

library(rpart)
library(Metrics)
library(doParallel)
library(foreach)
library(ggplot2)


random_forest <- function(train_data, train_formula, method="class", feature_per=0.7, cp=0.01, min_split=20, min_bucket=round(min_split/3), max_depth=30, ntrees = 10) {

  target_variable <- as.character(train_formula)[[2]]
  features <- setdiff(colnames(train_data), target_variable)
  n_features <- length(features)

  ncores <- detectCores(logical=FALSE)
  cl <- makeCluster(ncores)
  registerDoParallel(cl)

  rf_model <- foreach(
    icount(ntrees),
    .packages = c("rpart", "Metrics")
  ) %dopar% {
    bagged_features <- sample(features, n_features * feature_per, replace = FALSE)
    index_bag <- sample(nrow(train_data), replace=TRUE)
    in_train_bag <- train_data[index_bag,]
    out_train_bag <- train_data[-index_bag,]
    trControl <- rpart.control(minsplit = min_split, minbucket = min_bucket, cp = cp, maxdepth = max_depth)
    tree <- rpart(formula = train_formula, 
                  data = in_train_bag, 
                  control = trControl)

    oob_pred <- predict(tree, newdata = out_train_bag, type = "class")
    oob_acc <- accuracy(actual = out_train_bag[, target_variable], predicted = oob_pred)

    list(tree=tree, oob_perf=oob_acc)
  }

  stopCluster(cl)

  rf_model

}

train_formula <- as.formula("Species ~ .")
forest <- random_forest(train_data = iris, train_formula = train_formula)

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2016-11-11
    • 2014-06-14
    • 1970-01-01
    • 2019-04-15
    • 2020-04-08
    • 2017-11-13
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多