要在 R 中获取随机森林模型的 OOB,您可以:
library(randomForest)
set.seed(1)
model <- randomForest(Species ~ ., data = iris)
OOB 错误在:
model$err.rate[,1]
其中第 i 个元素是直到第 i 个树的 (OOB) 错误率。
可以绘制它并检查它是否与为 rf 模型定义的绘图方法中的 OOB 相同:
par(mfrow = c(2,1))
plot(model$err.rate[,1], type = "l")
plot(model)
OOB 对于选择超参数 mtry 和 ntree 很有用,并且应该与 k-fold CV 相关,但不应使用它来将 rf 与 k-fold CV 测试的不同类型的模型进行比较。
OOB 很棒,因为它几乎是免费的,而 k-fold CV 则需要运行 k 次。
在 R 中运行 k-fold CV 的一种简单方法是:
定义折叠(将 5 替换为 k(正整数 >1)以运行 k -fold CV:
folds <- sample(1:5, size = nrow(iris), replace = T) #5 fold CV
这种方法不会给出同样大小的折叠(尤其是对于较小的数据集),这通常没什么大不了的。
table(folds)
#output
1 2 3 4 5
30 28 28 33 31
解决这个问题:
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
在 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]))
})
您可以使用相同的代码来获得岭模型的性能。
将数据框列表转换为数据框:
CV_rf <- do.call(rbind, CV_rf)
检查准确性
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
所以这里的准确度是 0.9533
而第 500 个(500 个默认适合 rf)树的 OOB 是:
model$err.rate[500,1]
#OOB
0.04666667
它们完全一样,完全击败了我的观点,但是例如尝试运行 10 倍 CV 或 3 倍,你会发现它们不一样。
另一种方法是使用caret 或mlr 库。我不使用mlr,但caret 非常适合这样的任务。这是something,让您开始使用插入符号和射频。此外插入符号具有出色的documentation。即使您不打算使用该软件包,我也可以推荐它。