在caret中绘制ctree方法的决策树,去除不需要的条形图底部。

4
我正在caret中运行ctree方法模型,并尝试绘制决策树。 以下是我的主要代码部分。
fitControl <- trainControl(method = "cv", number = 10)
dtree <- train(
  Outcome ~ ., data = training_set, 
  method = "ctree", trControl = fitControl
)

我正在尝试绘制决策树,我使用

plot(dtree$finalModel)

这给了我这个 -

decision tree

这里的图片不太好,但我得到了一个类似于使用rpart.plot功能绘制ctree图表答案中第一个图表的图像。
而as.simpleparty函数无法工作,因为它不是rpart对象。
我想要移除下面的条形图,并在那些节点上简单地得到一个1或0,告诉我它是如何分类的。由于dtree$finalModel是一个二叉树对象,
prp(dtree$finalModel)

不起作用。


如果不熟悉ctree,则可以始终捕获输出的绘图对象并手动操作以删除不需要的部分。如果您找到了一种优雅的方法,请在此处发布并提交给软件包维护者。 - smci
嗨AVT,欢迎来到stackoverflow。我该如何改进我的答案以获得赞或被标记为已接受的答案? - makeyourownmaker
1
@makeyourownmaker 抱歉,完全忘记了。现在完成了。 - AVT
没问题。谢谢您接受我的答案。 - makeyourownmaker
1个回答

2

可以在不使用caret的情况下获得一个没有底部图形但带有结果标签的ctree图。尽管如此,为了完整起见,我还是包含了caret代码。

首先设置一些数据以进行可重复的示例:

library(caret)    
library(partykit)
data("PimaIndiansDiabetes", package = "mlbench")
head(PimaIndiansDiabetes)
      pregnant glucose pressure triceps insulin mass pedigree age diabetes
1        6     148       72      35       0 33.6    0.627  50      pos
2        1      85       66      29       0 26.6    0.351  31      neg
3        8     183       64       0       0 23.3    0.672  32      pos
4        1      89       66      23      94 28.1    0.167  21      neg
5        0     137       40      35     168 43.1    2.288  33      pos
6        5     116       74       0       0 25.6    0.201  30      neg

现在使用caret找到最佳的ctree参数:

fitControl <- trainControl(method = "cv", number = 10)
dtree <- train(
  diabetes ~ ., data = PimaIndiansDiabetes, 
  method = "ctree", trControl = fitControl
)

dtree
Conditional Inference Tree

768 samples
  8 predictor
  2 classes: 'neg', 'pos'

No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 691, 691, 691, 692, 691, 691, ...
Resampling results across tuning parameters:

  mincriterion  Accuracy   Kappa
  0.01          0.7239747  0.3783882
  0.50          0.7447027  0.4230003
  0.99          0.7525632  0.4198104

Accuracy was used to select the optimal model using the largest value.
The final value used for the model was mincriterion = 0.99.

这不是一个理想的模型,但是嘿呵,我们继续前进。

现在使用caret中的最佳参数构建并绘制ctree模型:

ct <- ctree(diabetes ~ ., data = PimaIndiansDiabetes, mincriterion = 0.99)

png("diabetes.ctree.01.png", res=300, height=8, width=14, units="in")
plot(as.simpleparty(ct))
dev.off()

这将给出以下图形,底部没有图表,但终端节点上具有结果变量(“pos”和“neg”)。为避免重叠的终端节点,需要使用非默认高度和宽度值。

Diabetes ctree diagram

请注意,在使用caret的ctree时,0、1结果变量需要小心处理。 使用ctree方法的caret包默认使用整数或数值0、1数据构建回归模型。如果需要进行分类,请将结果变量转换为因子。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接