有没有办法在R中获取随机森林中每棵树的分裂记录和属性?

Is there a way to get the splitting records and attributes for each tree in random forest in R?

为了生成随机森林,该算法随机拆分记录和属性并构建决策树。 例如,如果我使用以下代码:

set.seed(71) 
rf <-randomForest(income~.,data=mydata, ntree=200) 

我要种 200 棵树。 我可以使用参数 mtry = 每次拆分时选择的变量数和 sampsize = 从数据中抽取的样本大小以生长每个决策树. 我想为 200 棵树中的每棵树选择 mydata 数据集的行数(记录)以及选择的变量(属性)的名称。我怎样才能找到它?

根据您在 mtry/sampsize 中的设置,您可以使用以下代码:

rf = randomForest(Species~.,data=iris,ntree=200,mtry=2,sampsize=30,keep.forest=TRUE,replace=FALSE,keep.inbag=TRUE)

out_vars = varUsed(rf,by.tree=TRUE) # gives the variables used in each tree
apply(out_vars,2,function(x) which(x!=0))

out_case = rf$inbag # gives the cases used in each tree
apply(out_case,2,function(x) which(x!=0))

确保 select keep.inbag=TRUEreplace=FALSE,请参阅 ?randomForest 文档