假设您使用的是randomForest 包,您只需将keep.inbag 参数设置为TRUE。
library(randomForest)
set.seed(1)
rf <- randomForest(Species ~ ., iris, keep.inbag = TRUE)
输出列表将包含一个 n×ntree 矩阵,可以通过名称 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
矩阵中的值告诉您样品在袋子中的次数。例如,上面第 5 行第 3 列中的值 2 表示对于第 3 棵树,第 5 次观察被包含在包中两次。
作为这里的背景知识,一个样本可以多次出现在袋子中(因此是 2 次),因为默认情况下,抽样是通过替换完成的。
您也可以通过replace 参数进行采样而不用替换。
set.seed(1)
rf2 <- randomForest(Species ~ ., iris, keep.inbag = TRUE, replace = FALSE)
现在我们可以验证,在不替换的情况下,任何样本被包含的最大次数是一次。
# 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