目标变量可以采用一组离散值的树模型称为分类树(常用的分类树算法有ID3、C4.5、CART),而目标变量可以采用连续值(通常是实数)的决策树被称为回归树(如CART算法)
分类树被看作是非线性模型,树形工具利用穷举的方法,进行分析:
- 在一个大组中考虑所有的预测因子;
- 找出第一个预测因子,它能最好的将响应拆分成两个不同的同类组;
- 把数据分割成两组,也就是“叶子”。执行分割的位置称为“节点”;
- 在每一个分支中,我们重新检索所有的预测因子包括刚刚拆分的预测因子,尝试找出该组内另一个预测因子,或者把响应拆分成更多的同类组;
- 重复这一过程,直至分组足够小或者足够纯净,才能停止算法。
rpart包, rpart参数介绍

使用ID3算法时候,split = “information” ,使用CART算法的时候, split = “gini”
- data
data("iris")
n<-nrow(iris)
ntrain<-round(n*0.6)
set.seed(333)
tindex<-sample(n,ntrain)
train_iris<-iris[tindex,]
test_iris<-iris[-tindex,]
str(train_iris)
- 建立决策树
library(rpart)
tree_iris<-rpart(Species~.,data=train_iris)
# summary(tree_iris)
printcp(tree_iris)
tree_iris$variable.importance
plotcp(tree_iris,lwd=2)




- 画决策树
# 1
plot(tree_iris)
text(tree_iris,use.n=T,all=T,cex=0.9)
# 2
rpart.plot(tree_iris,branch=1,shadow.col="gray",box.col="yellow",border.col="blue",split.col="red",split.cex=1.2,main="决策树")
rpart.plot(tree_iris,branch=1,type=4, fallen.leaves=T,cex=0.8, sub="剪枝前") # type有5类

- 剪枝 pruning:使用具有最小交叉验证误差的cp来建立回归树
cp=tree_iris$cptable[which.min(tree_iris$cptable[,"xerror"]),"CP"]
tree.iris.new<-prune(tree_iris,cp=0.01000)
rpart.plot(tree.iris.new,branch=1, type=5,fallen.leaves=T,cex=0.8, sub="剪枝后")
# ......同上的检查
- 输出规则,预测
library(rattle)
asRules(tree.iris.new)

library(pROC)
pred.tree<-predict(tree.iris.new,newdata=test_iris)

pred.tree<-predict(tree_iris,newdata=test_iris,type="class") #利用预测集进行预测
table(test_iris$Species, pred.tree, dnn=c("真实值","预测值")) #输出混淆矩阵
data.frame(test_iris$Species, pred.tree)
最后,可以用ROC可视化结果。
网友评论