创建一棵决策树

文章安排:
(1)先从信息论的角度分析如何划分数据
(2)将数学公式运用到实际的数据集
(3)画出一颗决策树
(4)一个实战例程
(5)实验总结

1. 决策树是啥树?

决策树,见字如面。一棵可以做出决策的树。

比如常见的垃圾邮件检测(朴素贝叶斯也可以)(检测邮件发送的域名地址,识别邮件中的中的信息,找到垃圾邮件经常出现的词语如:discount,free,buy),进而做出决策是垃圾邮件,还是正常通信邮件。

为何选择决策树
优点:计算复杂度不高,输出易于理解
缺点:容易产生过拟合
使用场景:数值型和标称型数据

2. 决策树的构造

流程:
(1)收集数据:可以使用任何方法(文末提供数据集,哈哈)
(2)准备数据:树构造算法只适用标称型数据,因此数值型数据需要离散化(类似数字信号处理模数转换的幅值量化)
(3)分析数据:可以使用任何方法,构造树完成后,应及时检查图形是否符合预期
(4)训练算法:构造树的数据结构
(5)测试算法:使用经验树计算错误率
(6)使用算法:写一篇可以跑,不会报错的博客,哈哈哈

采用ID3算法,每次划分数据集采用一个特征,那么该选择那个特征作为我们划分依据呢?

2.1 信息增益

分类的依据:相似的数据分为一类,每次分类后数据,处于同一分支结构的数据有较高的相似性。并且用作分类依据的特征去掉后将使得数据集的无序度降低,数据变得更加整齐。

度量数据有序程度的依据是啥?
引入信息论
在划分数据集的前后信息发生的变化称为信息增益,获得信息增益最高的特征就是我们分类最好的依据。
集合信息的度量方式称为香农熵或者熵
熵越大数据的混乱度越高,数据越无序,相似度更低。

熵就是信息的期望值,如果待分类的事务可能出划分在多个分类之中,则符号x(i)的信息定义为:
在这里插入图片描述
我们需要计算数据集的熵,因此只要累加求和即可:
在这里插入图片描述
至此,我们可以分析划分前后数据集的熵如何变化。

计算数据集的香农熵

from math import log
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 * log(prob, 2) #log base 2
    return shannonEnt

在这里插入图片描述
熵越高,混合的数据越多,我们可以在数据集中添加更多的分类,观察数据集熵的变化
在这里插入图片描述

2.2 划分数据集

按照给定的特征划分数据集,第一个参数为待划分的数据集,第二个参数为划分数据集的特征,第三个参数为需要返回的特征值

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)
    return retDataSet

在这里插入图片描述
例:根据特征0划分数据集,返回特征0为1的数据记录

2.3 选择最好的数据集划分方式

上一小节,我们学习了如何衡量数据集的混乱程度。我们目标:按照数据的内在规律不断划分数据集为小的分支,直到叶子节点,则分类完毕。

我们将对每个特征划分的数据集求计算一次熵,然后判断该特征是否为最好的数据集划分特征(即一个决策过程)

def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1      #the last column is used for the labels
    baseEntropy = calcShannonEnt(dataSet)
    bestInfoGain = 0.0; bestFeature = -1
    for i in range(numFeatures):        #iterate over all the features
        featList = [example[i] for example in dataSet]#create a list of all the examples of this feature
        uniqueVals = set(featList)       #get a set of unique values
        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     #calculate the info gain; ie reduction in entropy
        if (infoGain > bestInfoGain):       #compare this to the best gain so far
            bestInfoGain = infoGain         #if better than current best, set to best
            bestFeature = i
    return bestFeature 

这里将每一个特征作为一次数据集的划分依据,然后求得划分后的数据集的熵newEntropy,当新的数据集的熵最小时,即选取该特征划分数据集前后获得最大的信息增益时,数据的混乱度降低,该特征为最好的数据集划分特征。
在这里插入图片描述

2.4 递归构建决策树

上述数据集划分结束的标志是:每一条记录都分配到一个叶子节点,每次选取一个特征后,都将数据集划分为几个更小的数据集,我们只要对分割后的分支数据集继续使用chooseBestFeatureToSplit函数即可继续划分数据集,递归可以简单的实现这一过程。
我们在实际操作中,还可以指定叶子结点的个数(即分类数,C4.5和CART算法)

def createTree(dataSet, labels):
    classList = [example[-1] for example in dataSet]
    if classList.count(classList[0]) == len(classList):
        return classList[0]#stop splitting when all of the classes are equal
    if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
        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[:]       #copy all of labels, so trees don't mess up existing labels
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
    return myTree

这里通过字典的嵌套模拟树的分支操作。
在这里插入图片描述

3. 画出一棵决策树

如果想要画出一棵好看的树,需要计算树的深度、宽度信息,使用matplotlib函数,过程过于繁琐,这里直接可以调用==treePlotter.createPlot(lensestree)==画出一棵美观的决策树

'''
Created on Oct 14, 2010

@author: Peter Harrington
'''
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)[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)[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)[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)

测试代码

if __name__ == '__main__':
    mydat,labels=createDataSet()
    thistree = createTree(mydat,labels)
    treePlotter.createPlot(thistree)

测试图样:

在这里插入图片描述

4. 一个实战例程

使用决策树预测隐形眼镜类型
数据集源代码都有,有需要评论留言邮箱即可,也可给俺发邮件836808298@qq.com

实验结果图例:

在这里插入图片描述

5.实验总结

决策树的核心是决策过程,我们通过信息论的香农熵,去衡量划分数据的混乱程度,进而得到决策的依据。该算法ID3使用单个特征划分,直至划分到叶子节点。目前流行的是C4.5和CART算法,以后填坑,哈哈。
决策树的过度匹配问题可以通过决策树的裁剪实现,提高算法的泛化能力,以后填坑,哈哈。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值