'''
需要文件联系我
决策树
优点: 计算复杂度不高,输出结果易于理解,对中间值缺失不敏感,可以处理不相关特征数据
缺点:可能会产生过度匹配问题
适用数据类型:数值型,标称型
一般流程:
收集数据
准备数据:数构造算法只适合用于标称型数据,因此数值型数据必须离散化
分析数据
训练算法
测试算法
使用算法
划分数据集:
检测数据集中的每个子项是否属于同一分类
If so return 类标签
Else
寻找划分数据集的最好特征
划分数据集
创建分支节点
For 每个划分的子集
调用函数createBranch并增加返回结果到分支点中
Return 分支节点
信息增益——————
原则:将无序数据变为有序数据
集合信息的度量方式成为香浓熵或者简称熵(ShannonEnt)
熵定义为信息的期望
l(xi) = -log2p(xi) p(xi)表示选择该分类的概率
计算所有类别所有可能值包含的信息期望
H = -Σp(xi)log2p(xi) 1->n
熵越高混合的数据越高
得到熵之后可以按照获取最大信息增益的方法划分数据集
另一个方法基尼不纯度
'''
import matplotlib.pyplot as plt
from math import log
import operator
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def createDataSet():
dataSet = [[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']]
labels = ['no surfacing','flippers']
return dataSet, labels
def calcShannonEnt(dataSet):
#计算香农熵
numEntries = len(dataSet) # 计算dataset 大小
labelCounts = {} #存放标签
for featVec in dataSet: #对于每一个元素
currentLabel = featVec[-1] # 获取标签
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0 #如果当前标签没有记录过
labelCounts[currentLabel] += 1 # 出现次数+1
shannonEnt = 0.0 #香农熵
for key in labelCounts: #对于每一个标签
prob = float(labelCounts[key])/numEntries #计算标签
shannonEnt -= prob * log(prob,2) # 计算香农熵
return shannonEnt #返回香农熵
def splitDataSet(dataSet, axis, value): #分割数据
retDataSet = []
for featVec in dataSet: # 对于每个集合
if featVec[axis] == value: #如果是待划分的值
reducedFeatVec = featVec[:axis] #选择当前的进行划分
reducedFeatVec.extend(featVec[axis+1:]) #extend 在list 后 一次性追加多个值
retDataSet.append(reducedFeatVec) #加入
return retDataSet
def chooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) - 1 #最后一列是标签 比进行计算
baseEntropy = calcShannonEnt(dataSet) #计算一下香农熵
bestInfoGain = 0.0 #信息增益
bestFeature = -1 #特征值
for i in range(numFeatures): #对于每一个数据
featList = [example[i] for example in dataSet] #每一列的值作为一个list
uniqueVals = set(featList) #创建唯一的分类标签
newEntropy = 0.0 #新的香农熵
for value in uniqueVals: #对于每一个唯一标签
subDataSet = splitDataSet(dataSet, i, value) #划分数据
prob = len(subDataSet)/float(len(dataSet)) #计算概率
newEntropy += prob * calcShannonEnt(subDataSet) #计算香浓熵
infoGain = baseEntropy - newEntropy #计算信息增益 info gain
if (infoGain > bestInfoGain): #比较一下 , 获得最好的增益
bestInfoGain = infoGain
bestFeature = i
return bestFeature #返回了一个intger 最好的特征值
def majorityCnt(classList):
#创建一个唯一的数据字典,返回次数最多的分类名称
classCount={}
for vote in classList: #对于list中的每一个元素
if vote not in classCount.keys(): #如果是新统计的元素
classCount[vote] = 0 #开个新空间
classCount[vote] += 1 # +1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) #排序 从大到小 根据次数拍戏
return sortedClassCount[0][0]#返回第一个 也就是出现次数最多的标签
def createTree(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 = chooseBestFeatureToSplit(dataSet) #最好的每类特征
bestFeatLabel = labels[bestFeat] #最好分类特征的标签
myTree = {bestFeatLabel:{}} #标签树
del(labels[bestFeat]) #删除这个标签
featValues = [example[bestFeat] for example in dataSet] #把最好特征的数据变成list
uniqueVals = set(featValues) #唯一的集合
for value in uniqueVals: #对于唯一的集合
subLabels = labels[:] #复制一下
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels) #向树中添加节点
return myTree
def classify(inputTree, featLabels, testVec):
firstStr = list(inputTree.keys())[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)
key = testVec[featIndex]
valueOfFeat = secondDict[key]
if isinstance(valueOfFeat, dict):
classLabel = classify(valueOfFeat, featLabels, testVec)
else:
classLabel = valueOfFeat
return classLabel
def storeTree(inputTree,filename):
import pickle
fw = open(filename,'w')
pickle.dump(inputTree,fw)
fw.close()
def grabTree(filename):
import pickle
fr = open(filename)
return pickle.load(fr)
def getNumLeafs(myTree):
numLeafs = 0
firstStr = list(myTree.keys())[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
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':#test to see if the nodes are dictonaires, if not they are leaf nodes
thisDepth = 1 + getTreeDepth(secondDict[key])
else: thisDepth = 1
if thisDepth > maxDepth: maxDepth = thisDepth
return maxDepth
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.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.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on
numLeafs = getNumLeafs(myTree) #this determines the x width of this tree
depth = getTreeDepth(myTree)
firstStr = list(myTree.keys())[0] #the text label for this node should be this
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':#test to see if the nodes are dictonaires, if not they are leaf nodes
plotTree(secondDict[key],cntrPt,str(key)) #recursion
else: #it's a leaf node print the leaf node
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
#if you do get a dictonary you know it's a tree, and the first element will be another dict
def createPlot(inTree):
fig = plt.figure(1, facecolor='white')
fig.clf()
axprops = dict(xticks=[], yticks=[])
createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #no ticks
#createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses
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()
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'}}}}
]
return listOfTrees[i]
'''
myDat , labels = createDataSet()
print(labels)
mytree = retrieveTree(0)
print(mytree)
classLabel = classify(mytree, labels, [1, 0])
print(classLabel)
'''
fr = open('C:\\Users\\lvcun\\Desktop\\lenses.txt')
lenses = [inst.strip().split('\t') for inst in fr.readlines()]
lensesLabels = ['age', 'prescrip', 'astigmatic', 'astigmatic', 'tearRate']
lensesTree = createTree(lenses, lensesLabels)
print(lensesTree)
createPlot(lensesTree)