三种属性选择度量:信息增益(ID3)、增益率(C4.5)、基尼指数(CART)
ID3:Iterative Dichotomiser(迭代的二分器),利用增益比不纯性,树采用二叉树,停止准则为当所有的记录属于同一类时,停止分裂;或当所有的记录都有相同的属性时,停止分裂
C4.5:ID3的改进版,也是最流行的决策树算法,采用多重分枝和剪枝技术。
CART:Classification and Regression Trees(分类回归树)
使用R自带的数据
iris
,最后一列是类别信息
ID3—C4.5:使用
RWeka
包中的J48
函数(该包可能依赖于R3.4版本)
CART:使用tree
包中的tree
函数
一、构建训练集与检验集
data(iris)
ind <- sample(2,nrow(iris),replace=T,prob=c(0.7,0.3))
trainSet <- iris[ind==1,]
testSet <- iris[ind==2,]
二、J48构建决策树
treeC4.5 <- J48(Species~.,data=trainSet)
#给出因变量即类别和训练数据的特征信息
table(trainSet$Species,predict(treeC4.5))
testPre <- predict(treeC4.5,newdata=testSet)
table(testPre,testSet$Species)
plot(treeC4.5)
text(treeC4.5)
三、tree构建决策树
library(tree)
search() ##该函数可查看当前加载了哪些包
myFormula <-Species~Petal.Width+Petal.Length+Sepal.Width+Sepal.Length
treeCART <- tree(myFormula,data=trainSet)
树的结构:
预测信息:对每个样本都给出属于每个类的概率:
比较预测类与真实类:
table(apply(predict(treeCART),1,function(x){names(x)[which.max(x)]}),trainSet$Species)
table(apply(predict(trainCART,newdata=testSet),1,function(x){names(x)[which.max(x)]}),testSet$Species)
作图:
plot(treeCART)
text(treeCART)
四、随机森林
提高分类准确率的技术——组合分类方法:
①bagging
②boosting
③随机森林
randomForest
包中的randomForest
函数
library(randomForest)
rf <- randomForest(Species~.,data=trainSet,ntree=100)
table(trainSet$Species,predict(rf))
testPre <- predict(rf,newdata=testSet)
table(testPre,testSet$Species)
plot(rf) #绘制误差率
importance(rf) #变量的重要性
varImpPlot(rf) #变量的重要性可视化,展示每个变量的最小减少的gini指数