决策树R语言代码

讲解链接

R语言分类树,决策树
library(readxl)
data <- read_excel(path = 'D:\\sj1.xlsx')
library(rpart)
dtree<-rpart(事故责任~.,data=data,method="class", parms=list(split="information"))
printcp(dtree)
print(dtree)
tree<-prune(dtree,cp=0.0125)
tree<-prune(dtree,cp=dtree$cptable[which.min(dtree$cptable[,"xerror"]),"CP"])
opar<-par(no.readonly = T)
par(mfrow=c(1,1))
library(rpart.plot)
# #png(file = "D:\\tree1.png")
rpart.plot(dtree,
          type = 2, extra = "auto",
         under = FALSE, fallen.leaves = TRUE,       
         digits = 2, varlen = 0, faclen = 1, roundint = TRUE,
           cex = 0.6, tweak = 1,
           clip.facs = FALSE, clip.right.labs = TRUE,
           snip = FALSE,box.palette = 'red' ,shadow.col = 0,)
# #rpart.plot(dtree,branch=1,type=2, fallen.leaves=T,cex=0.8, sub="剪枝前")
# #png(file = "D:\\tree2.png")
# #rpart.plot(tree,branch=1, type=4,fallen.leaves=T,cex=0.8, sub="剪枝后")
# #par(opar)
# #dev.off()代码片
#R语言分类树,决策树
library(readxl)
data <- read_excel(path = 'D:\\个人文件\\研究生论文\\长三角\\数据整合\\data2019\\数据回归一张表201920210526.xlsx')
library(rpart)
dtree<-rpart(耦合协调度~Variable2+Variable8+Variable14+Variable16+Variable20+Variable22+Variable32+Variable34+Variable40+Variable52+Variable54+Variable64+Variable106+Variable115+Variable116+Variable82+Variable86,data=data,method="class", parms=list(split="information"))
printcp(dtree)

print(dtree)
tree<-prune(dtree,cp=0.0125)
tree<-prune(dtree,cp=dtree$cptable[which.min(dtree$cptable[,"xerror"]),"CP"])
opar<-par(no.readonly = T)
par(mfrow=c(1,1))
#library(rpart.plot)
# #png(file = "D:\\tree1.png")
rpart.plot(dtree,type = 2, extra = "auto",under = FALSE, fallen.leaves = TRUE,digits = 2, varlen = 0, faclen = 1, roundint = TRUE,cex = 0.6, tweak = 1,clip.facs = FALSE, clip.right.labs = TRUE,snip = FALSE,box.palette = 'red' ,shadow.col = 0,)
# #rpart.plot(dtree,branch=1,type=2, fallen.leaves=T,cex=0.8, sub="剪枝前")
# #png(file = "D:\\tree2.png")
# #rpart.plot(tree,branch=1, type=4,fallen.leaves=T,cex=0.8, sub="剪枝后")
# #par(opar)
# #dev.off()代码片

你可能感兴趣的:(数据挖掘)