该ctree()
函数期望 (a) 为每个变量使用适当的类别(数值、因子等),并且 (b) 在模型公式中仅使用有用的预测变量。
至于 (b),您提供的变量实际上只是字符(如Name
)而不是因子。这要么需要进行适当的预处理,要么从分析中省略。
即使你不这样做,你也不会得到最好的结果,因为一些变量(如Survived
和Pclass
)是用数字编码的,但实际上是分类变量,应该是因子。如果您查看https://www.kaggle.com/c/titanic/forums/t/13390/introducing-kaggle-scripts中的脚本,您还将了解如何进行数据准备。在这里,我使用
titanic <- read.csv("train.csv")
titanic$Survived <- factor(titanic$Survived,
levels = 0:1, labels = c("no", "yes"))
titanic$Pclass <- factor(titanic$Pclass)
titanic$Name <- as.character(titanic$Name)
至于 (b),然后我继续调用ctree()
已充分预处理以进行有意义分析的变量。(而且我使用 package 中推荐的较新的实现partykit
。)
library("partykit")
ct <- ctree(Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked,
data = titanic)
plot(ct)
print(ct)
这会产生以下图形输出:
以及以下打印输出:
Model formula:
Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked
Fitted party:
[1] root
| [2] Sex in female
| | [3] Pclass in 1, 2: yes (n = 170, err = 5.3%)
| | [4] Pclass in 3
| | | [5] Fare <= 23.25: yes (n = 117, err = 41.0%)
| | | [6] Fare > 23.25: no (n = 27, err = 11.1%)
| [7] Sex in male
| | [8] Pclass in 1
| | | [9] Age <= 52: no (n = 88, err = 43.2%)
| | | [10] Age > 52: no (n = 34, err = 20.6%)
| | [11] Pclass in 2, 3
| | | [12] Age <= 9
| | | | [13] Pclass in 3: no (n = 71, err = 18.3%)
| | | | [14] Pclass in 2: yes (n = 13, err = 30.8%)
| | | [15] Age > 9: no (n = 371, err = 11.3%)
Number of inner nodes: 7
Number of terminal nodes: 8