2017-05-29 116 views
1

如何在R的同名包中输出randomForest的树图功能?例如,我使用iris数据,并且想要绘制500个输出束中的第一棵树。我的代码是随机绘制500棵树中的一棵林林包

model <-randomForest(Species~.,data=iris,ntree=500) 
+0

以下答案有帮助吗? https://stats.stackexchange.com/questions/41443/how-to-actually-plot-a-sample-tree-from-randomforestgettree – Avitus

+0

@Avitus谢谢你的回答,但我不能保持原状。你能给我一个简单的代码,用于绘制randomForest函数输出中的第一棵树吗? –

+0

我为'randomForest'包添加了一个答案;其他软件包 - 像“聚会” - 允许类似的功能 – Avitus

回答

2

您可以使用getTree()功能randomForest包(官方指导价:https://cran.r-project.org/web/packages/randomForest/randomForest.pdf)在

iris数据集:

require(randomForest) 
data(iris) 

## we have a look at the k-th tree in the forest 
k <- 10 
getTree(randomForest(iris[, -5], iris[, 5], ntree = 10), k, labelVar = TRUE) 
+0

如何绘制这棵树?请在上面的代码中添加绘图代码。谢谢 –

+0

@Amin上面的代码给你选择的树('k < - 10')。如果你想看到它,你需要更多的努力(我不知道'randomForest'中有任何直接绘图功能)。请看看这个https://shiring.github.io/machine_learning/2017/03/16/rf_plot_ggraph – Avitus

0

您可以使用cforest绘制如下图所示,我已经将值硬编码为5,您可以根据您的要求进行更改。

ntree <- 5 
library("party") 
cf <- cforest(Species~., data=iris,controls=cforest_control(ntree=ntree)) 

for(i in 1:ntree){ 
pt <- prettytree([email protected][[i]], names([email protected]@get("input"))) 
nt <- new("Random Forest BinaryTree") 
[email protected] <- pt 
[email protected] <- [email protected] 
[email protected] <- [email protected] 

pdf(file=paste0("filex",i,".pdf")) 
plot(nt, type="simple") 
dev.off() 

} 

cforest是随机森林的另一种实现方式,它不能说哪个更好,但总体上是可以看出一些区别。区别在于cforest使用有条件的推论,我们对终端节点赋予更多的权重,与randomForest包相比,其中实现为终端节点提供相等的权重。

一般而言cofrest使用加权平均值,而randomForest使用正常平均值。你可能想检查this

+0

谢谢你的回答。我想使用'randomForest',我可以使用'cforest'而不是'randomForest'吗? –

+0

@aminroshani,请参阅编辑 – PKumar