本文为自己学习机器学习所记笔记,主要参考《统计学习方法》和《机器学习实战》两本书。本文讨论决策树算法应用于分类问题。
1.决策树模型
分类决策树模型是一种描述对实例进行分类的树形结构,由节点(node)和有向边(directed edge)构成。节点分为内部节点(internal node)和叶节点(leaf node)。内部节点表示一个一个特征或属性,叶节点 表示一个类。决策树可以看作一个if-then规则的集合。
2.决策树学习算法
决策树学习的算法通常是递归地选择最有特征,并根据该特征值对训练数据集进行分割,使得对于各个子数据集有一个最好的分类的过程。开始,构建根节点,将所有训练数据集都放在跟节点,选择一个最优特征按照这一特征将训练数据集分割为子集,使得各个子集在当前条件下有一个最好的分类。如果这些子集基本能够被正确分类,那么构建叶节点,并将这些子集分到对应的叶节点;如果不能,对这些子集继续选择新的最优特征,如此递归,直到所有子集都被基本正确分类或者没有合适的特征为止。
以上生成的决策树可能发生过拟合现象,因此我们需要对已生成的树进行剪枝。
3.特征选择
如何让选择一个最有特征来对数据集进行分类?通常选择的准则为信息增益或者信息增益比。
熵:表示随机变量不确定性的度量
设X为一离散随机变量,其概率分布为:P(X=xi)=pi,i=1,2...n
随机变量X的熵的定义为
熵越大,随机变量的不确定性越大。
条件熵:随机变量Y在给定条件X下的条件熵:
信息增益:集合D的熵与特征A给定条件下D的经验条件熵H(D|A)之差:
g(D|A)=H(D)-H(D|A)
信息增益表示经过特征A的分类后,数据不确定度的减少。因此我们选择信息增益最大的特征进行数据划分。
4.python实现
(1)决策树的构建
本文采用IDE3算法构建决策树,即以信息增益为特征选择的准则。
from math import log
import operator
#计算信息熵
def calEntropy(dataset):
num=len(dataset)
labelsCount={} #定义一个字典,保存所有的类,及各个类中的样本数
for featureVec in dataset:
currentLabel=featureVec[-1] #最后一列为标签,作为键值
if currentLabel not in labelsCount.keys():#当前键值不存在,则加入
labelsCount[currentLabel]=0
labelsCount[currentLabel]+=1
entropy=0
for key in labelsCount:
prob=labelsCount[key]/num
entropy-=prob*log(prob,2) #底数为2
return entropy
#按某一特征值划分数据集。输入三个参数,数据集列表,划分数据集的特征索引,特征返回值。返回按某一特征值提取的样本
#dataset为一个列表元素的列表,列表中每一个实例的最后一个元素为标签值
def splitDataset(dataset,axis,value):
reDataset=[]
for featureVec in dataset:
if featureVec[axis]==value:
reducedFeat=featureVec[:axis]
reducedFeat.extend(featureVec[axis+1:]) #extend将后一个列表的元素添加进前一个列表
reDataset.append(reducedFeat) #append将后一个列表作为元素添加进前一个列表
return reDataset
#选择最佳的特征进行数据集划分,依据最大信息增益
def chooseBestFeature(dataset):
numFeature=len(dataset[0])-1 #特征数
baseEntropy=calEntropy(dataset) #原始熵
bestInfoGain=0.0
bestFeature=-1
#对每一个特征计算信息增益
for i in range(numFeature):
featureList=[example[i] for example in dataset] #获得每一个特征对应的值
uniqueVals=set(featureList) #使用set除去原list的重复元素
newEntropy=0
#遍历当前特征中的所有唯一属性值,根据属性值划分数据集,并计算划分后的熵
for value in uniqueVals:
subDataset=splitDataset(dataset,i,value)
prob=len(subDataset)/len(dataset)
newEntropy+=prob*calEntropy(subDataset)
newInfogain=baseEntropy-newEntropy #信息增益
if newInfogain>bestInfoGain:
bestInfoGain=newInfogain
bestFeature=i
return bestFeature #返回最佳特征索引
#多数表决法决定类别,输入为类标签列表
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)
#排序,三个参数分别为:将classCount转化为元组列表,利用第二个元素排序,降序排列
#count={'A':1,'B':3,'C':2},count.items()=dict_items([('A', 1), ('B', 3), ('C', 2)])
return sortedClassCount[0][0]
#构建决策树。输入数据集和特征名称列表。
def creatTree(dataset,featureName):
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=chooseBestFeature(dataset)#当前最好分类特征
bestFeatName=featureName[bestFeat]
mytree={bestFeatName:{}} #用嵌套字典存储决策树
del(featureName[bestFeat]) #删掉已用过的特征
featValues=[example[bestFeat] for example in dataset] #当前分类特征下的所有特征值
uniqFeatValues=set(featValues)
for value in uniqFeatValues:
subFeatName=featureName[:] #避免每次调用creatTree都改变featureName的值,复制次列表
mytree[bestFeatName][value]=creatTree(splitDataset(dataset,bestFeat,value),subFeatName) #递归调用
return mytree
#用决策树对一样本进行分类。输入参数:决策树,特征名称,测试向量
def classify(inputTree,featLabels,testVec):
firstStr=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
(2)测试
使用一个不同情况应该适配什么眼镜的数据集来构建决策树,并通过可视化手段画出决策树。原数据集如下 :
第一至四列为特征,特征名分别记为:'age','prescript','astigmatic','tearRate',最后一列为适配的眼镜种类
fr=open('D:\python\code\machinelearninginaction\Ch03\lenses.txt')
dataset=[line.strip().split('\t') for line in fr.readlines()]
fr.close()
print('\n')
featureName=['age','prescript','astigmatic','tearRate']
lensesTree=creatTree(dataset,featureName)
print(lensesTree)
featureName=['age','prescript','astigmatic','tearRate']
testFeatVec=['young','myope','no','reduced']
glass=classify(lensesTree,featureName,testFeatVec)
print('the suitable glass to choose:',glass)
输出:
{'tearRate': {'normal': {'astigmatic': {'yes': {'prescript': {'hyper': {'age': {'presbyopic': 'no lenses', 'young': 'hard', 'pre': 'no lenses'}}, 'myope': 'hard'}}, 'no': {'age': {'presbyopic': {'prescript': {'hyper': 'soft', 'myope': 'no lenses'}}, 'young': 'soft', 'pre': 'soft'}}}}, 'reduced': 'no lenses'}}
the suitable glass to choose: no lenses
图形化决策树:
绘制决策树程序:
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':#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 createPlot():
# fig = plt.figure(1, facecolor='white')
# fig.clf()
# createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses
# 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()
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]
#createPlot(thisTree)
mytree={'tearRate': {'normal': {'astigmatic': {'no': {'age': {'young': 'soft', 'presbyopic': {'prescript': {'hyper': 'soft', 'myope': 'no lenses'}}, 'pre': 'soft'}}, 'yes': {'prescript': {'hyper': {'age': {'young': 'hard', 'presbyopic': 'no lenses', 'pre': 'no lenses'}}, 'myope': 'hard'}}}}, 'reduced': 'no lenses'}}
决策树的剪枝以及在回归问题的应用在之后的文章讨论。