如何计算落在树的每个节点中的观察结果

Ric*_*Kim 2 tree r classification decision-tree

我目前正在处理MMST包中的葡萄酒数据.我已将整个数据集拆分为训练和测试,并构建如下代码的树:

library("rpart")
library("gbm")
library("randomForest")
library("MMST")

data(wine)
aux <- c(1:178)
train_indis <- sample(aux, 142, replace = FALSE)
test_indis <- setdiff(aux, train_indis)

train <- wine[train_indis,]
test <- wine[test_indis,]    #### divide the dataset into trainning and testing

model.control <- rpart.control(minsplit = 5, xval = 10, cp = 0)
fit_wine <- rpart(class ~ MalicAcid + Ash + AlcAsh + Mg + Phenols + Proa + Color + Hue + OD + Proline, data = train, method = "class", control = model.control)

windows()
plot(fit_wine,branch = 0.5, uniform = T, compress = T,  main = "Full Tree: without pruning")
text(fit_wine, use.n = T, all = T, cex = .6)
Run Code Online (Sandbox Code Playgroud)

我可以得到这样的图像: 树没有修剪

每个节点下的数字(例如Grignolino下的0/1/48)是什么意思?如果我想知道每个节点有多少培训和测试样本,我应该在代码中写什么?

Mat*_*agg 7

数字表示该节点中每个类的成员数.因此,标签"0/1/48"告诉我们0类(类型1)(Barabera,我推断),类别2(Barolo)和48类(Grignolino)中只有一例.

您可以使用获取有关树和每个节点的详细信息summary(fit_wine).
有关?summary.rpart详细信息, 请参阅

您还可以使用predict()(将调用predict.rpart())来查看树如何对数据集进行分类.例如,predict(fit_wine, train, type="class").或者将其包装在桌子上以便于查看table(predict(fit_wine, train, type = "class"),train[,"class"])

如果您特别想知道观察到哪个叶节点,则存储此信息fit_wine$where.对于数据集中的每个案例,fit_wine$where包含行号fit_wine$frame,表示案例所在的叶节点.因此,我们可以通过以下方式获取每个案例的叶信息:

trainingnodes <- rownames(fit_wine$frame)[fit_wine$where]
Run Code Online (Sandbox Code Playgroud)

为了获得测试数据的叶子信息,我用来运行predict()type="matrix"和推断它.这令人困惑地返回了一个矩阵,该矩阵是通过连接预测的类,在计算树中该节点处的类计数和类概率而产生的.所以对于这个例子:

testresults <- predict(fit_wine, test, type = "matrix")
testresults <- data.frame(testresults)
names(testresults) <- c("ClassGuess","NofClass1onNode", "NofClass2onNode",
     "NofClass3onNode", "PClass1", "PClass2", "PClass2")
Run Code Online (Sandbox Code Playgroud)

由此,我们可以推断出不同的节点,例如,来自unique(testresults[,2:4]),但它是不优雅的.

然而,Yuji在之前的一个问题上有一个聪明的黑客.他复制rpart对象并将节点替换为类,因此运行predict会返回节点而不是类:

nodes_wine <- fit_wine
nodes_wine$frame$yval = as.numeric(rownames(nodes_wine$frame))
testnodes <- predict(nodes_wine, test, type="vector")
Run Code Online (Sandbox Code Playgroud)

我在这里已经包含了解决方案,但人们应该支持他.