r - 获取 rpart 模型节点的 id/name

标签 r rpart

如何获取 rpart 终端节点的 ID(或名称)每行的模型? predict.rpart可以仅返回分类树的预测类(数字或因子)或类概率或某些组合(使用 type="matrix" )。

我想做类似的事情:

fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
plot(fit) # there are 5 terminal nodes
predict(fit, type = "node_id")   # should return IDs of terminal nodes (e.g. 1-5) (does not work)

最佳答案

partykit包支持 predict(..., type = "node") ,样本内和样本外。您可以简单地转换 rpart对象使用这个:

library("partykit")
predict(as.party(fit), type = "node")  
## 9 7 9 9 3 3 3 3 3 8 8 3 9 5 3 3 3 7 3 5 3 9 8 9 9 5 9 8 3 3 3 7 7 3 7 3 5 ## 9 5 8 
## 9 7 9 9 3 3 3 3 3 8 8 3 9 5 3 3 3 7 3 5 3 9 8 9 9 5 9 8 3 3 3 7 7 3 7 3 5 ## 9 5 8 
## 9 5 9 9 3 7 3 7 9 7 8 3 9 3 3 3 5 9 5 8 9 9 9 3 3 5 3 7 5 3 7 7 3 7 3 3 7 ## 5 7 9 
## 9 5 9 9 3 7 3 7 9 7 8 3 9 3 3 3 5 9 5 8 9 9 9 3 3 5 3 7 5 3 7 7 3 7 3 3 7 ## 5 7 9 
## 5 
## 5 
table(predict(as.party(fit), type = "node")) 
##  3  5  7  8  9 
## 29 12 14  7 19 

关于r - 获取 rpart 模型节点的 id/name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17597739/

相关文章:

r - 使用 rpart 决策树进行数据预测

r - 使用 rpart 选择决策树修剪的 CP 值

r - PCA空间和 'feature-space'发散中的质心距离计算

image - r- 如何在 image.plot 中编辑 x 轴上的元素

r - 在 R 中拆分的快速替代方案

r - 将ggplot2网格导出为PDF错误: 'Error in grid.Call.graphics... invalid font type'

r - 有人可以解释一下 ID3 和 CART 算法之间的区别吗?

R - 两个 data.tables 的匹配值的索引

R 插入符包 (rpart) : constructing a classification tree

r - 决策树代理 split 的澄清