决策树
决策树概述
决策树是一种树结构,包含终止模块,判断模块和分支。
优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据
缺点:可能会产生过度匹配问题
适用数据类型:数值型和标称型
本章使用的是ID3算法划分数据集,而不是通常采用的二分法。
ID3算法可以归纳为以下几点:
- 使用所有没有使用的属性并计算与之相关的样本熵值
- 选取其中熵值最小的属性
- 生成包含该属性的节点
引自维基百科
划分数据集的大原则是:将无序的数据变得有序。将无序数据变得有序的一种方法是使用信息论度量信息,信息论是量化处理信息的分支科学。
这些东西都不知道什么来的,网上查了一下,写个大概。度量信息的前提是信息可以度量。那么,信息可以度量吗?显然是可以的。
既然信息可以度量,那么信息量肯定是有大有小的。而信息量的大小跟什么有关呢?答案是不确定性。你讲一个大家都知道的事情,这件事情肯定就没什么信息量,因为大家都确定就是这样啊。相反,你讲一个大家都不确定的事情,那信息量肯定非常大啊!好了,那不确定性又和什么有关系呢?当然是事件可能结果的数量和事件发生的概率。
假如我想在13亿中国人中找一个人,这个人(包括首富)的财富和我的加起来比首富还多。显然,我有13亿个选择,也就是有13亿个结果,显然,该事件可能结果的数量是相当可观的,仅从这一点考虑,不确定性是非常大的。但是,假如我们知道可能结果的概率分布,不确定性就会发生变化。也许我的财富和第二富的人的加起来可能比首富多(白日做梦!),但是我的财富和首富的加起来一定比首富多,那么后者的概率(100%)肯定比前者的要高。这时,这个问题的答案就非常确定了。所以,不确定性的变化事件和可能结果的数量和事件发生的概率相关。
到这里,我们已经讲了这么多了,可是信息量到底该怎么衡量呢?先给出定义,信息量的定义为。从这里我们可以看出,信息量和结果的数量以及概率相关,由于概率在0到1之间,概率的对数为负,需要在前面负号,以保证信息量为正。这里会有两个疑问,一个是为什么信息量为正,另一个为什么是对数。关于信息量为什么是正,感觉网上的解释很多,一种解释是信息只能被赋予不能被夺走,另一个是当值为负时,不能称为信息量,而是干扰。而关于为什么是对数关系,给出的解释是多个事件同时发生的概率是多个事件概率相乘,总的信息量是信息量相加,因而确定了对数关系。
既然已经已经知道了信息量的定义,我还想知道所有可能发生事件所带来的信息量的期望,这时就引出了信息熵。信息熵的公式为。知道了信息熵,条件熵就很好理解。条件熵就是在已知第二个随机变量X 的值的前提下,随机变量 Y 的信息熵。我们知道,信息熵实际上就是随机变量的不确定度,条件熵则是在某一个条件下,随机变量的不确定度。两者相减,便是在某一条件下,信息不确定度减少的程度。这个就是信息增益。
我们根据一个特征划分数据,划分数据集之前和之后信息发生的变化实际上就是信息增益,信息增益越高,说明不确定性减少的程度越高,也就是说分类数据的确定性比之前更高。显然,获得信息增益越高的特征的重要性也高。
计算香农熵
from math import log
#香农熵
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVec in dataSet:
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 * log(prob,2)
return shannonEnt
#数据集
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
myDat,labels = createDataSet()
print(calcShanninEnt(myDat)) #0.9709505944546686
#增加分类,熵发生了变化
myDat[0][-1]='maybe'
print(myDat)
print(calcShannonEnt(myDat)) #1.3709505944546687
划分数据集
def splitDataSet(dataSet, axis, value): #待划分的数据集、划分数据集的特征、需要返回的特征的值
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
retDataSet.append(reducedFeatVec)
return retDataSet
print(splitDataSet(myDat,0,1)) #[[1, 'yes'], [1, 'yes'], [0, 'no']]
print(splitDataSet(myDat,0,0)) #[[1, 'no'], [1, 'no']]
选择最好的划分方式
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] #所有第i个特征的值
uniqueVals = set(featList) #去除重复元素
newEntropy = 0.0
for value in uniqueVals:
subDataSet = splitDataSet(dataSet, i, value) #按第i个特征划分数据集
prob = len(subDataSet)/float(len(dataSet)) #概率
newEntropy += prob * calcShannonEnt(subDataSet) #计算条件熵
infoGain = baseEntropy - newEntropy #计算信息增益
if (infoGain > bestInfoGain): #比较信息增益
bestInfoGain = infoGain
bestFeature = i
return bestFeature #返回信息增益
print(chooseBestFeatureToSplit(myDat)) #0,也就是说第0个特征是最好的
递归构建决策树
def majorityCnt(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 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]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:] #剩下的标签
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
return myTree
myTree = createTree(myDat,labels)
print(myTree) #{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
绘制树形图
使用文本注解绘制树节点
import matplotlib.pyplot as plt
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-") #箭头
def plotNode(nodeTxt, centerPt, parentPt, nodeType): #添加注释
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', #xy是数据坐标
xytext=centerPt, textcoords='axes fraction', #xytext是注释坐标
va="center", ha="center", bbox=nodeType, arrowprops=arrow_args )
def createPlot():
fig = plt.figure(1, facecolor='white') #新建图形,背景颜色设为白色
fig.clf() #清空绘图区
createPlot.ax1 = plt.subplot(111, frameon=False)
plotNode('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode) #决策节点
plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode) #叶节点
plt.show()
createPlot()

获取叶节点的数目和树的层数
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'}}}}
]
return listOfTrees[i]
myTree = retrieveTree(0)
print(getNumLeafs(myTree)) #3
print(getTreeDepth(myTree)) #2
构造整个树
import matplotlib.pyplot as plt
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 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 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]
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):
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 #下一节点的y坐标值
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 #x坐标值
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.ax1 = 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)

测试算法:使用决策树执行分类
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
import treePlotter
myTree = treePlotter.retrieveTree(0)
print(classify(myTree,labels,[1,0])) #no
print(classify(myTree,labels,[1,1])) #yes
使用算法 :决策树的储存
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)
storeTree(myTree,'classifierStorage.txt')
grabTree('classifierStorage.txt')
使用决策树预测隐形眼镜类型
fr = open('lenses.txt')
lenses = [inst.strip().split('\t') for inst in fr.readlines()]
lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']
lensesTree = createTree(lenses,lensesLabels)
print(lensesTree)
'''
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
{'tearRate': {'normal': {'astigmatic': {'yes': {'prescript': {'myope': 'hard', 'hyper': {'age': {'pre': 'no lenses', 'young': 'hard', 'presbyopic': 'no lenses'}}}}, 'no': {'age': {'pre': 'soft', 'young': 'soft', 'presbyopic': {'prescript': {'myope': 'no lenses', 'hyper': 'soft'}}}}}}, 'reduced': 'no lenses'}}
'''
treePlotter.createPlot(lensesTree)

总结
本章采用的是ID3算法,该算法无法直接处理数值型数据。尽管可以通过量化的方法将数值型数据转化为标称型数据,但如果存在太多的特征划分,该算法仍会面临其他问题。