如何获取随机森林模型 R 中每棵树使用的 OOB 样本?

use*_*767 2 r random-forest

是否有可能获得随机森林算法为每棵树使用的 OOB 样本?我用的是R语言。我知道随机森林算法使用几乎 66% 的数据(随机选择)来生长每棵树,并使用 34% 的数据作为 OOB 样本来测量 OOB 误差,但我不知道如何获取这些 OOB 样本每棵树?

任何想法 ?

jmu*_*amp 5

假设您正在使用该randomForest包,您只需将keep.inbag参数设置为TRUE

library(randomForest)
set.seed(1)
rf <- randomForest(Species ~ ., iris, keep.inbag = TRUE)
Run Code Online (Sandbox Code Playgroud)

输出列表将包含一个 n × ntree 矩阵,可以通过 name 访问inbag

dim(rf$inbag)
# [1] 150 500

rf$inbag[1:5, 1:3]
#   [,1] [,2] [,3]
# 1    0    1    0
# 2    1    1    0
# 3    1    0    1
# 4    1    0    1
# 5    0    0    2
Run Code Online (Sandbox Code Playgroud)

矩阵中的值告诉您样品在袋中的次数。例如,上面第 5 行第 3 列中的值 2 表示第 5 个观测值被包含在第 3 棵树的袋中两次。

作为这里的一点背景知识,样本可以多次出现在袋子中(因此是 2),因为默认情况下采样是通过替换完成的。

您还可以通过参数进行无替换采样replace

set.seed(1)
rf2 <- randomForest(Species ~ ., iris, keep.inbag = TRUE, replace = FALSE)
Run Code Online (Sandbox Code Playgroud)

现在我们可以验证,在不进行替换的情况下,任何样本最多包含一次。

# with replacement, the maximum number of times a sample is included in a tree is 7
max(rf$inbag)
# [1] 7

# without replacemnet, the maximum number of times a sample is included in a tree is 1
max(rf2$inbag)
# [1] 1
Run Code Online (Sandbox Code Playgroud)