gpt4 book ai didi

r - 如何在R中的randomForest中找到从getTree函数从根到叶子的路径?

转载 作者:行者123 更新时间:2023-11-30 08:47:05 25 4
gpt4 key购买 nike

R 中 randomForest 包中的 getTree 函数显示随机森林中使用的特定树的结构。

这是 iris 数据集的示例

library(randomForest)
data(iris)
rf <- randomForest(Species ~ ., iris)
getTree(rf, 1)

这显示了 500 棵树#1 的输出:

   left daughter right daughter split var split point status prediction
1 2 3 3 2.50 1 0
2 0 0 0 0.00 -1 1
3 4 5 4 1.65 1 0
4 6 7 4 1.35 1 0
5 8 9 3 4.85 1 0
6 0 0 0 0.00 -1 2
7 10 11 2 3.10 1 0
8 12 13 4 1.55 1 0
9 0 0 0 0.00 -1 3
10 0 0 0 0.00 -1 3
11 0 0 0 0.00 -1 2
12 14 15 2 2.55 1 0
13 0 0 0 0.00 -1 2
14 16 17 2 2.35 1 0
15 0 0 0 0.00 -1 3
16 0 0 0 0.00 -1 3
17 0 0 0 0.00 -1 2

现在我的主要目标是找到从节点 1 到终端节点的路径(在这些情况下为 2、6、9、10 等)

有我可以使用的通用算法或代码吗?

9 的路径是 1 -> 3 -> 5 -> 910 的路径将为 1 -> 3 -> 6 -> 10

任何帮助将不胜感激。

最佳答案

您可以通过递归来完成此操作 - 例如:

library(randomForest)
data(iris)
set.seed(123) # for reproducibility
rf <- randomForest(Species ~ ., iris)

some_tree <- getTree(rf, 1)

some_tree

get_path_to_node <- function(tree, child){
parent <- which(tree[,'left daughter']==child | tree[,'right daughter']==child)
if( parent==1 ) return(paste(parent, child, sep='->'))
return( paste(get_path_to_node(tree, child=parent), child, sep='->' ) )
}

get_path_to_node(some_tree, 5)

给你1->3->5

说明:我们从节点 j 开始。我们可以通过找出哪一行有 left daughter 来找出它的“父级”是什么。等于 jright daughter等于 j 。然后我们对其父级重复该过程,依此类推,直到我们发现父级为 1,根据定义,它是根。我们使用pastesep='->'边走边构建链条。

关于r - 如何在R中的randomForest中找到从getTree函数从根到叶子的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com