1、决策树-ID3算法
在原基础上进行熵对比计算过程的一个提示输出,便于对比程序计算与手动计算上的算式。
import math
import operator
import pandas as pd
def createDataSet():
dataSet = [
[456, 498, 795, 586, 3512, 2104, 384, 'Vegetation'],
[934, 498, 795, 602, 657, 2104, 1129, 'Vegetation'],
[934, 2098, 795, 586, 657, 1637, 1129, 'Vegetation'],
[365, 498, 795, 586, 3512, 1637, 112, 'Vegetation'],
[456, 2098, 827, 586, 3512, 2104, 1129, 'Vegetation'],
[456, 498, 827, 602, 3512, 2104, 1129, 'Vegetation'],
[934, 498, 1404, 1184, 657, 451, 112, 'Non - Vegetation'],
[934, 1085, 1404, 1184, 657, 1637, 384, 'Non - Vegetation'],
[365, 2098, 1404, 1184, 657, 451, 384, 'Non - Vegetation'],
[456, 498, 795, 602, 3512, 2104, 1129, 'Non - Vegetation']
]
labels = ['v1','v2','v3','v4','v5','v6','v7']
#change to discrete values
return dataSet, labels
# 计算香农熵
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVec in dataSet: # the the number of unique elements and their occurance
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
for key in labelCounts:
prob = float(labelCounts[key]) / numEntries
shannonEnt -= prob * math.log(prob, 2) # log base 2
print(str(prob) + '*' + 'log'+str(prob) + '+', end='')
print("="+str(shannonEnt))
return shannonEnt
# 按特征和特征值划分数据集
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis] # chop out axis used for splitting
reducedFeatVec.extend(featVec[axis + 1:])
retDataSet.append(reducedFeatVec) # 这里注意extend和append的区别
return retDataSet
# ID3决策树分类算法
def chooseBestFeatureToSplitID3(dataSet):
numFeatures = len(dataSet[0]) - 1 # myDat[0]表示第一行数据, the last column is used for the labels
baseEntropy = calcShannonEnt(dataSet)
bestInfoGain = 0.0
bestFeature = -1
#print(numFeatures)
for i in range(numFeatures): # iterate over all the features
featList = [example[i] for example in dataSet] # featList是每一列的所有值,是一个列表
uniqueVals = set(featList) # 集合中每个值互不相同
newEntropy = 0.0
print('\nE'+str(i)+'=')
for value in uniqueVals:
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet) / float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
print(')*'+str(prob)+'+(',end='')
print('')
infoGain = baseEntropy - newEntropy # calculate the info gain; ie reduction in entropy
print(str(i) + '------')
print('infoGain:' + str(infoGain))
print('newEntropy:' + str(newEntropy) + ' baseEntropy:' + str(baseEntropy))
if (infoGain > bestInfoGain): # compare this to the best gain so far
bestInfoGain = infoGain # if better than current best, set to best
bestFeature = i
print(str(bestFeature) + '------bestHere')
print('bestInfoGain:' + str(bestInfoGain) )
return bestFeature # returns an integer
# 当所有特征都用完的时候投票决定分类
def majorityCnt(classList):
classCount = {}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
# ID3构建树
def createTreeID3(dataSet, labels):
classList = [example[-1] for example in dataSet] # 创建类标签
if classList.count(classList[0]) == len(classList):
return classList[0] # 如果所有类标签完全相同则停止,直接返回该类标签
if len(dataSet[0]) == 1: # 遍历完了所有的标签仍然不能将数据集划分为仅包含唯一类别的分组
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplitID3(dataSet) # 最佳分类特征的下标
bestFeatLabel = labels[bestFeat] # 最佳分类特征的名字
print(bestFeatLabel+'-----best'+ '\n')
myTree = {bestFeatLabel: {}} # 创建
del (labels[bestFeat]) # 从label里删掉这个最佳特征,创建迭代的label列表
featValues = [example[bestFeat] for example in dataSet] # 这个最佳特征对应的所有值
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:] # copy all of labels, so trees don't mess up existing labels
myTree[bestFeatLabel][value] = createTreeID3(splitDataSet(dataSet, bestFeat, value), subLabels)
return myTree
def storeTree(inputTree, filename):
import pickle
fw = open(filename, 'wb')
pickle.dump(inputTree, fw)
fw.close()
def grabTree(filename):
import pickle
fr = open(filename, 'rb')
return pickle.load(fr)
myDat,labels=createDataSet()
myTree=createTreeID3(myDat,labels)
print(myTree)
storeTree(myTree, 'ID3TreeStructure.txt')
grabTree('ID3TreeStructure.txt')
2、读取决策树,画图显示
import matplotlib.pyplot as plt
plt.switch_backend('TkAgg')
# 定义文本框和箭头格式
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
# 获取叶节点数目
def getNumLeafs(myTree):
numLeafs = 0
firstStr = list(myTree.keys())[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict': # 是字典继续递归,不是字典就是叶节点
numLeafs += getNumLeafs(secondDict[key])
else:
numLeafs += 1
return numLeafs
def getTreeDepth(myTree):
maxDepth = 0
firstStr = list(myTree.keys())[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[
key]).__name__ == 'dict':
thisDepth = 1 + getTreeDepth(secondDict[key])
else:
thisDepth = 1
if thisDepth > maxDepth: maxDepth = thisDepth
return maxDepth
def retrieveTree(i):
# listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
# {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
# ]
listOfTrees =[{'v4': {1184: 'Non - Vegetation', 586: 'Vegetation', 602: {'v1': {456: {'v3': {795: 'Non - Vegetation', 827: 'Vegetation'}}, 934: 'Vegetation'}}}},
]
return listOfTrees[i]
getNumLeafs(retrieveTree(0))
getTreeDepth(retrieveTree(0))
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
createPlot.axl.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction',
va="center", ha="center", bbox=nodeType, arrowprops=arrow_args)
def plotMidText(cntrPt, parentPt, txtString):
xMid = (parentPt[0] - cntrPt[0])/2.0 + cntrPt[0]
yMid = (parentPt[1] - cntrPt[1])/2.0 + cntrPt[1]
createPlot.axl.text(xMid, yMid, txtString)
def plotTree(myTree, parentPt, nodeTxt):
numLeafs = getNumLeafs(myTree)
depth = getTreeDepth(myTree)
firstStr = list(myTree.keys())[0]
cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
plotMidText(cntrPt, parentPt, nodeTxt)
plotNode(firstStr, cntrPt, parentPt, decisionNode)
secondDict = myTree[firstStr]
plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict':
plotTree(secondDict[key], cntrPt, str(key))
else:
plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff),cntrPt, leafNode)
plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
def createPlot(inTree):
fig = plt.figure(1, facecolor='white')
fig.clf()
axprops = dict(xticks=[], yticks=[])
createPlot.axl = plt.subplot(111, frameon=False, **axprops)
plotTree.totalW = float(getNumLeafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree))
plotTree.xOff = -0.5/plotTree.totalW
plotTree.yOff = 1.0
plotTree(inTree, (0.5, 1.0), '')
plt.show()
myTree = retrieveTree(0)
createPlot(myTree)