说明
1.参考文章:R语言实现决策树ID3算法
2.补充了分类预测的函数部分
3.采用数据框模拟xml文件的方式存储决策树
代码
训练集(train_data)
outlook | temperature | humidity | windy | play |
---|---|---|---|---|
sunny | hot | high | FALSE | no |
sunny | hot | high | TRUE | no |
overcast | hot | high | FALSE | yes |
rainy | mild | high | FALSE | yes |
rainy | cool | normal | FALSE | yes |
rainy | cool | normal | TRUE | no |
overcast | cool | normal | TRUE | yes |
sunny | mild | high | FALSE | no |
sunny | cool | normal | FALSE | yes |
rainy | mild | normal | FALSE | yes |
sunny | mild | normal | TRUE | yes |
overcast | mild | high | TRUE | yes |
overcast | hot | normal | FALSE | yes |
rainy | mild | high | TRUE | no |
测试集也是这个数据集,只是将类标移除了
模型训练函数
train<-function(formula,train_data){
#工具函数
#计算一列数据的信息熵
calculateEntropy <- function(train_data){
t <- table(train_data) #统计每种结果出现多少次
sum <- sum(t) #总次数
t <- t[t!=0] #去掉非0
entropy <- -sum(log2(t/s