中的combine函数randomForest可以组合多个randomForest对象。
准备数据:
set.seed(1234)
X1 <- rnorm(100, 120, 16)
X2 <- X1 + rnorm(100, 200, 10)
X3 <- 0.8*X2 + rnorm(100, 140, 12)
Y <- factor(as.numeric(X1 > 125))
dat.test <- data.frame(Y, X1, X2, X3)
# Impose missingness
Y[runif(100) < 0.5] <- NA
X1[runif(100) < 0.5] <- NA
X2[runif(100) < 0.5] <- NA
X3[runif(100) < 0.5] <- NA
dat <- data.frame(Y, X1, X2, X3)
估算缺失数据:
library(mice)
mice <- mice(dat, m = 10, method = "rf")
impdat <- NULL # allocate empty list of imputations
for (m in 1:10){impdat[[m]] <- complete(mice, m)} # export imputations
现在在m个完整的数据集上训练m个模型:
library(randomForest)
rf <- NULL
for (m in 1:10){rf[[m]] <- randomForest(Y ~ ., data = impdat[[m]])}
选项1
中的combine函数randomForest可以聚合相同大小的树:
body(combine)[[4]] <- substitute(rflist <- (...))
rf.all <- combine(rf)
rf.all您的“合并”模型在哪里。如果我们测试它:
predictions <- predict(rf.all, within(dat.test, rm("Y")))
table(dat.test$Y, predictions)
0 1
0 70 1
1 2 27
我们发现预测非常准确。
选项 2
第二种选择是将每个模型的投票集中在一起:
votes <- list()
for (m in 1:10){votes[[m]] <- predict(rf[[m]],
within(dat.test, rm("Y")),
type = "vote")}
votes <- Reduce('+', votes)
predictions <- NULL
for (i in 1:nrow(votes))
{if (votes[i,1] < votes[i,2])
{predictions[i] = 1} else {predictions[i] = 0}}
注意type = "vote"在 的参数中的选择predict。其他功能可能需要type = "prob".
> table(dat.test$Y, predictions) # mostly accurate
predictions
0 1
0 70 1
1 2 27
混淆矩阵是一样的。
投票池是基于树的模型的一种通用方法,它应该满足ranger对象和gbm对象。
如果目标是回归而不是分类,则汇集投票非常相似,但设置type = "response"为predict(默认)。
rf <- NULL
for (m in 1:10){rf[[m]] <- randomForest(X1 ~ ., data = impdat[[m]])}
predictions <- list()
for (m in 1:10){predictions[[m]] <- predict(rf[[m]],
within(dat.test, rm("X1")),
type = "response")}
predictions <- Reduce('+', predictions)/10 # divide by m
计算均方误差:
> mean((predictions - dat.test$X1)^2)
[1] 64.78884