如何获取每行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
对于该模型,有4个分割,产生5个"终端节点",或者用rpart中使用的术语:<leaf>
s。我不明白为什么任何东西都应该有5个预测。预测是针对特定情况的,叶子是用于进行这些预测的可变数量的分割的结果。原始数据集中最终出现在叶子中的行数可能是您想要的,在这种情况下,以下是获取这些数字的方法:
# Row-wise predicted class
fit$where
# counts of cases in leaves of prediction rules
table(fit$where)
3 5 7 8 9
29 12 14 7 19
为了组装应用于特定叶的labels(fit)
,您需要遍历规则树,并累积用于生成特定叶的所有拆分的所有标签。你可能想看看:
?print.rpart
?rpart.object
?text.rpart
?labels.rpart
上面使用$where的方法只弹出树框架中的行号。因此,当使用kyphosis$ID = fit$where
时,可能会为某些观测指定节点ID,而不是叶节点ID要获得实际的叶节点ID,请使用以下内容:
MyID <- row.names(fit$frame)
kyphosis$ID <- MyID[fit$where]
为了预测新数据上的叶,可以使用包rpart.plot
中的rpart.predict(fit, newdata, nn = TRUE)
将节点名称添加到输出中。
这是一个孤立的rpart叶预失真器:
rpart_leaves <- function(fit, newdata, type = c("where", "leaf"), na.action = na.pass) {
if (is.null(attr(newdata, "terms"))) {
Terms <- delete.response(fit$terms)
newdata <- model.frame(Terms, newdata, na.action = na.action,
xlev = attr(fit, "xlevels"))
if (!is.null(cl <- attr(Terms, "dataClasses")))
.checkMFClasses(cl, newdata, TRUE)
}
newdata <- rpart:::rpart.matrix(newdata)
where <- unname(rpart:::pred.rpart(fit, newdata))
if (match.arg(type) == "where")
return(where)
rownames(fit$frame)[where]
}