1

我已经使用 rpart 创建了一个决策树,我想知道如何准确找到哪些训练数据案例落入每个终端节点。

我按照此链接中的答案进行操作: 如何计算落在树的每个节点中的观察值, 但由于某种原因,$where 函数仅生成终端节点的向量,而没有行号指示哪种情况对应于哪个终端节点。但是,如果我对使用 tree 包制作的树执行完全相同的操作,我将获得带有相应终端节点的行号列表(标识每个案例)。我注意到唯一的区别是对于 rpart 包,$where 产生一个“int”向量,而对于 tree 包,$where 产生一个“Named int”向量。我想知道如何为由 rpart 制成的树生成相同的“命名 int”向量?

我还尝试了以下建议的答案: Find the data elements in a data frame that pass the rule for a node in a tree model? 但它对我不起作用,因为 rpart 在创建模型时删除了 16 个观察值,因此结果模型中的观察数与用于创建模型的原始数据框不匹配。

对不起,如果答案似乎很明显,新手 R 用户在这里!

这是我用来创建树的代码,它是用于根据行为特征预测自闭症诊断的树:

Set.seed(565808016)
inTrain21<- createDataPartition(clinicaldiagnosis, p=0.75, list=FALSE)
training_data21<- Decisiontree4[ inTrain21,]
testing_data21<- Decisiontree4[-inTrain21,]
test_clinicaldiagnosis21<-clinicaldiagnosis[-inTrain21]
lossmatrix=matrix(c(0,1,1,1,0,1,2,1,0), ncol=3, nrow=3)

set.seed(591251974)
tree_model22= rpart(clinicaldiagnosis~ Visualtracking + etc etc, training_data21, na.action=na.rpart, method="class", control=rpart.control(cp=0.00001), parms=list(loss=lossmatrix))
plot(tree_model22, uniform=TRUE, margin=0.05)
text(tree_model22, use.n=TRUE, pretty=0)
plotcp(tree_model22)
printcp(tree_model22)

pruned_model22=prune(tree_model22, cp=0.0146341)
plot(pruned_model22, uniform=TRUE, margin=0.1)
text(pruned_model22, use.n=TRUE, cex=0.85, splits=TRUE, pretty=0)

tree_pred22=predict(pruned_model22, testing_data21, type="class")
table(tree_pred22, test_clinicaldiagnosis21)
trainingnodes22<-rownames(pruned_model22$frame)[pruned_model22$where] #this only gives a list of terminal nodes without the corresponding row names
4

0 回答 0