path.rpart给出了一个很好的概述,但MrFlick已经写了一些代码来显示其观察落在特定的节点。看看here。
这只看rpart树。为了查看预测值落在哪个节点上,请看this post。
查看我包含的示例代码。该功能来自第一个答案。第二个答案的最后一部分。
library(rpart)
# split kyphosis into 2 for example
train <- kyphosis[1:60, ]
test <- kyphosis[-(1:60), ]
fit <- rpart(Kyphosis ~ Age + Number + Start, data = train)
# Show nodes
print(fit)
# function to show observations that fall in a node
# https://stackoverflow.com/questions/23924051/find-the-data-elements-in-a-data-frame-that-pass-the-rule-for-a-node-in-a-tree-m
subset_rpart <- function (tree, df, nodes) {
if (!inherits(tree, "rpart"))
stop("Not a legitimate \"rpart\" object")
stopifnot(nrow(df)==length(tree$where))
frame <- tree$frame
n <- row.names(frame)
node <- as.numeric(n)
if (missing(nodes)) {
xy <- rpart:::rpartco(tree)
i <- identify(xy, n = 1L, plot = FALSE)
if(i> 0L) {
return(df[tree$where==i, ])
} else {
return(df[0,])
}
}
else {
if (length(nodes <- rpart:::node.match(nodes, node)) == 0L)
return(df[0,])
return (df[tree$where %in% as.numeric(nodes), ])
}
}
subset_rpart(fit, train, 7)
# Find the nodes in which the test observations fall
# https://stackoverflow.com/questions/13690201/how-to-count-the-observations-falling-in-each-node-of-a-tree?lq=1
nodes_fit <- fit
nodes_fit$frame$yval <- as.numeric(rownames(nodes_fit$frame))
testnodes <- predict(nodes_fit, test, type="vector")
print(testnodes)
是的,它有帮助。谢谢! – Sankalp