如何计算随机森林的OOB?

gra*_*ace 1 r random-forest

我正在比较一些模型以获得最佳模型.现在,我想获得随机森林模型的OOB错误,以将其与其他模型的交叉验证错误进行比较.我可以做比较吗?如果可以,我如何通过R代码获得OOB错误?

mis*_*use 8

要在R中获取随机森林模型的OOB,您可以:

library(randomForest)

set.seed(1)
model <- randomForest(Species ~ ., data = iris)
Run Code Online (Sandbox Code Playgroud)

OOB错误在于:

model$err.rate[,1]
Run Code Online (Sandbox Code Playgroud)

其中第i个元素是直到第i个所有树的(OOB)错误率.

可以绘制它并检查它是否与为rf模型定义的绘图方法中的OOB相同:

par(mfrow = c(2,1))
plot(model$err.rate[,1], type = "l")
plot(model)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

OOB对于选择超参数是有用的mtry,ntree并且应该与k-fold CV相关联,但是不应该使用它来将rf与通过k-fold CV测试的不同类型的模型进行比较.OOB很棒,因为它几乎是免费的,而k-fold CV则需要k次才能运行.

在R中运行k-fold CV的简单方法是:

定义折叠(用k替换5(正整数> 1)以运行k -fold CV:

folds <- sample(1:5, size = nrow(iris), replace = T) #5 fold CV
Run Code Online (Sandbox Code Playgroud)

这种方法不会给出相同大小的折叠(特别是对于较小的数据集),这通常不是什么大问题.

table(folds)
#output
 1  2  3  4  5 
30 28 28 33 31 
Run Code Online (Sandbox Code Playgroud)

解决这个问题:

folds <- sample(rep(1:5, length.out = nrow(iris)), size = nrow(iris), replace = F)

table(folds)
#output
 1  2  3  4  5 
30 30 30 30 30 
Run Code Online (Sandbox Code Playgroud)

穿过折叠,在4个折叠中的每一个上训练模型并在5日进行预测.在这里,我只返回包含预测和实际值的数据框列表,可以自定义调用以返回他想要的任何统计数据.

CV_rf <- lapply(1:5, function(x){ #5 corresponds to the number of folds defined earlier
  model <- randomForest(Species ~ ., data = iris[folds != x,])
  preds <- predict(model,  iris[folds == x,], type="response")
  return(data.frame(preds, real = iris$Species[folds == x]))
  })
Run Code Online (Sandbox Code Playgroud)

您可以使用相同的代码来获得脊模型的性能.

将数据帧列表转换为数据帧:

CV_rf <- do.call(rbind, CV_rf)
Run Code Online (Sandbox Code Playgroud)

检查准确性

caret::confusionMatrix(CV_rf$preds, CV_rf$real) 
#part of output:
Overall Statistics

               Accuracy : 0.9533         
                 95% CI : (0.9062, 0.981)
    No Information Rate : 0.3333         
    P-Value [Acc > NIR] : < 2.2e-16 
Run Code Online (Sandbox Code Playgroud)

所以这里的准确度是0.9533

而500的OOB(默认情况下500在rf中是合适的)树是:

model$err.rate[500,1]
#OOB 
0.04666667 
Run Code Online (Sandbox Code Playgroud)

它们完全相同地击败了我的观点,但是例如尝试运行10倍CV或3倍,你会发现它们不一样.

另一种方法是使用caretmlr库.我不使用,mlrcaret对这样的任务真的很好.下面是一些让你开始使用插入符号和射频.Caret拥有出色的文档.即使您不打算使用该包,我也可以推荐它.