《机器学习实战》读书笔记第三章

来源:互联网 发布:杨幂用什么软件直播 编辑:程序博客网 时间:2024/06/05 17:57

《机器学习实战》(Machine Learning in Action)读书笔记 
anaconda平台 python3.6

第三章 决策树

决策树的主要优势在于数据内容易于理解,通过推断分解逐步缩小范围
头文件
from math import logimport operatorimport TreePlotterimport pickle
为了建立决策树,首先要了解信息熵的概念
通过以下代码计算给定数据集的信息熵,混合的数据越多,熵就越高
def calcShannonEnt(dataSet):    '''    计算给定数据集的信息熵    :param dataSet:    :return:    '''    numEntries = len(dataSet)#实例总数    labelCounts = {}#用于计数的字典    for featVec in dataSet:        currentLabel = featVec[-1]#数据集最后一列的数值,即标签        if currentLabel not in labelCounts.keys():#字典中已有则+1,没有则创建并+1            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 splitDataSet(dataSet, axis, value):    '''    按照给定特征划分数据集    :param dataset: 待划分的数据集    :param axis: 划分数据集的特征    :param value: 特征的值    :return: 划分过的数据集,即原数据集中特征满足条件且不包含该特征的部分    '''    retDataSet = []#创建一个新的列表对象防止原始数据集被修改    for featVec in dataSet:        if featVec[axis] == value:#该数据符合划分条件            reducedFeatVec = featVec[ :axis]#取特征前面部分的数据            reducedFeatVec.extend(featVec[axis + 1: ])#取特征后面部分的数据            retDataSet.append(reducedFeatVec)#将去掉特征的数据存入新数据集    return retDataSet
利用上面两个函数选择最好的数据划分方式,要注意列表取值都是从0开始的,因此返回的i表示取第i+1个特征进行划分是最好的
def chooseBestFeatureToSplit(dataSet):    '''    选择最好的数据集划分方式    :param dataSet:    :return:    '''    numFeatures = len(dataSet[0]) - 1    baseEntropy = calcShannonEnt(dataSet)#计算原始数据集的信息熵    bestInfoGain = 0.0;#初始信息增益为0    bestFeature = -1#最好的划分数据集的特征,初始为-1,即第0个条件,也就是不划分    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)#对每个特征划分一次数据集            prob = len(subDataSet) / float(len(dataSet))#计算选择该分类的概率            newEntropy += prob * calcShannonEnt(subDataSet)#计算信息熵并对所有唯一特征值得到的熵求和        infoGain = baseEntropy - newEntropy#如果信息增益变大,则当前特征值为最好划分特征        if (infoGain > bestInfoGain):            bestInfoGain = infoGain            bestFeature = i    return bestFeature
最后,我们通过调用以上所有函数创建一棵简单的决策树
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:{}}#开始构造树的第一个结点    tempLabels = labels[:]    del(tempLabels[bestFeat])#删除已用过的特征    featValues = [example[bestFeat] for example in dataSet]    uniqueVals = set(featValues)#得到所有唯一特征值    for value in uniqueVals:#循环当前选择特征的所有属性值        subLabels = tempLabels        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)#递归构造整棵树    return myTree
原文采用的del(labels[bestFeat])会导致输入的labels被修改,在这里用一个tempLabels代替

接下来要绘制决策树,我们新建一个TreePlotter.py文件
首先尝试通过以下代码分别画出判断节点和叶子节点
import matplotlib.pyplot as pltdecisionNode = dict(boxstyle="sawtooth", fc="0.8")leafNode = dict(boxstyle="round4", fc="0.8")arrow_args = dict(arrowstyle="<-")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 createPlot():    fig = plt.figure(1, facecolor='white')#创建一个白色背景的画布    fig.clf()#清除原有图形    createPlot.axl = plt.subplot(111, frameon=False)#将画布分为1行1列,画在第1块且没有边框    plotNode('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode)#调用plotNode创造一个判断节点    plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)#调用plotNode创造一个叶子节点    plt.show()#展示图案
接下来通过两个函数分别求出叶子结点和判断节点的数量,注意python2和python3的dict.keys()的不同
def getNumLeafs(myTree):#遍历整棵树,统计叶子节点的个数    numLeafs = 0    firstSides = list(myTree.keys())#python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[0]    secondDict = myTree[firstStr]    for key in secondDict.keys():        if type(secondDict[key]).__name__ == 'dict':#如果子节点是字典类型,则该节点也是一个判断节点,需要递归调用            numLeafs += getNumLeafs(secondDict[key])        else:            numLeafs += 1    return numLeafsdef getTreeDepth(myTree):#遍历整棵树,统计判断节点的个数    maxDepth = 0    firstSides = list(myTree.keys())#python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[0]    secondDict = myTree[firstStr]    for key in secondDict.keys():        if type(secondDict[key]).__name__ == 'dict':            thisDepth = 1 + getTreeDepth(secondDict[key])        else:#一旦遇到叶子节点就从递归调用中返回,并将深度+1            thisDepth = 1        if thisDepth > maxDepth:            maxDepth = thisDepth    return maxDepth
最后利用修改过的createPlot函数和新增的函数实现决策树的绘制,完整代码如下
import matplotlib.pyplot as pltdecisionNode = dict(boxstyle="sawtooth", fc="0.8")leafNode = dict(boxstyle="round4", fc="0.8")arrow_args = dict(arrowstyle="<-")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 createPlot(inTree):    fig = plt.figure(1, facecolor='white')#创建一个白色背景的画布    fig.clf()#清除原有图形    axprops = dict(xticks=[], yticks=[])    createPlot.axl = plt.subplot(111, frameon=False, **axprops)#将画布分为1行1列,画在第1块且没有边框    plotTree.totalW = float(getNumLeafs(inTree))#存储树的宽度    plotTree.totalD = float(getTreeDepth(inTree))#存储树的高度    plotTree.xOff = -0.5 / plotTree.totalW#按照叶子结点的数量将x轴划分为若干部分,并用此变量放置下一个节点的恰当x坐标位置    plotTree.yOff = 1.0#此变量放置下一个节点的恰当y坐标位置    plotTree(inTree,(0.5, 1.0),'')    plt.show()#展示图案def getNumLeafs(myTree):#遍历整棵树,统计叶子节点的个数    numLeafs = 0    firstSides = list(myTree.keys())#python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[0]    secondDict = myTree[firstStr]    for key in secondDict.keys():        if type(secondDict[key]).__name__ == 'dict':#如果子节点是字典类型,则该节点也是一个判断节点,需要递归调用            numLeafs += getNumLeafs(secondDict[key])        else:            numLeafs += 1    return numLeafsdef getTreeDepth(myTree):#遍历整棵树,统计判断节点的个数    maxDepth = 0    firstSides = list(myTree.keys())#python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[0]    secondDict = myTree[firstStr]    for key in secondDict.keys():        if type(secondDict[key]).__name__ == 'dict':            thisDepth = 1 + getTreeDepth(secondDict[key])        else:#一旦遇到叶子节点就从递归调用中返回,并将深度+1            thisDepth = 1        if thisDepth > maxDepth:            maxDepth = thisDepth    return maxDepthdef retriveTree(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]#计算中间位置的x坐标    yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1]#计算中间位置的y坐标    createPlot.axl.text(xMid, yMid, txtString)#添加文本信息def plotTree(myTree, parentPt, nodeTxt):    numLeafs = getNumLeafs(myTree)#计算树的宽度    depth = getTreeDepth(myTree)#计算树的高度    firstSides = list(myTree.keys())  # python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[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 -= 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#绘制完毕后增加全局变量Y的偏移myTree = retriveTree(0)createPlot(myTree)
效果如图:

为了利用决策树,首先用决策树构建一个分类器,这里我们用到了之前写的TreePlotter.py中的函数
def classify(inputTree, featLabels, testVec):    firstSides = list(inputTree.keys())  # python3的dict.keys返回的是dict_keys对象,不支持index,因此需要先将其转换为list    firstStr = firstSides[0]#当前第一个判断节点    secondDict = inputTree[firstStr]#除去第一个判断节点后的树    featIndex = featLabels.index(firstStr)#判断节点的index    for key in secondDict.keys():#遍历剩下的树        if testVec[featIndex] == key:#按输入的testVec向下遍历            if type(secondDict[key]).__name__ == 'dict':#如果是判断节点,就递归                classLabel = classify(secondDict[key], featLabels, testVec)            else:#如果是叶子节点,就返回当前节点的分类标签                classLabel = secondDict[key]    return classLabel
为了节省计算时间,最好能在每次执行分类时调用已经构造好的决策树,通过下面的代码我们可以预先提炼并存储数据集中包含的知识信息,在需要的时候再使用
def storeTree(inputTree, filename):#存储树    fw = open(filename, 'wb+')#python3需要用wb+写入    pickle.dump(inputTree, fw)    fw.close()def grabTree(filename):#读取树    fr = open(filename, 'rb+')#python3需要用rb+读取    return pickle.load(fr)

接下来,我们通过一个预测隐形眼镜镜片类型的例子来学习如何使用决策树
fr = open('lenses.txt')lenses = [inst.strip().split('\t') for inst in fr.readlines()]#根据tab分隔的数据行读入数据集lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']#定义标签lensesTree = createTree(lenses, lensesLabels)#构造决策树TreePlotter.createPlot(lensesTree)#绘制决策树的图像
结果如图:

小结:
决策树
  • 优点:计算复杂度不高,输出结果 
  • 缺点:可能会产生过多的数据集划分
  • 适用数据:数值型和标称型
阅读全文
0 0
原创粉丝点击