2017-05-29 126 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