[机器学习实战]决策树

本文详细介绍了决策树的学习过程,包括定义、构造方法,以及如何使用信息增益选择最优特征。通过Python代码展示了从数据集读取、决策树构建到绘制决策树的完整流程。最后,对决策树的优点和缺点进行了总结,如易于理解、无需数据预处理,但也存在过拟合和不稳定性的问题。实验结果显示,使用信息增益构建的决策树在测试数据上的正确率为90%。
摘要由CSDN通过智能技术生成

目录

一、决策树

1、定义

 2、构造

二、代码实现

1.信息增益

2.数据集

3.决策树

4.使用Matplotlib绘制决策树

5.实验结果

三、总结

1、优点

2、缺点


一、决策树

1、定义

决策树(decision tree):是一种基本的分类与回归方法,是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率,评价项目风险,判断其可行性的决策分析方法,是直观运用概率分析的一种图解法。由于这种决策分支画成图形很像一棵树的枝干,故称决策树。

 2、构造

决策树学习的算法通常是一个递归地选择最优特征,并根据该特征对训练数据进行分割,使得各个子数据集有一个最好的分类的过程。这一过程对应着对特征空间的划分,也对应着决策树的构建。

1) 开始:构建根节点,将所有训练数据都放在根节点,选择一个最优特征,按着这一特征将训练数据集分割成子集,使得各个子集有一个在当前条件下最好的分类。

2) 如果这些子集已经能够被基本正确分类,那么构建叶节点,并将这些子集分到所对应的叶节点去。

3)如果还有子集不能够被正确的分类,那么就对这些子集选择新的最优特征,继续对其进行分割,构建相应的节点,如果递归进行,直至所有训练数据子集被基本正确的分类,或者没有合适的特征为止。

4)每个子集都被分到叶节点上,即都有了明确的类,这样就生成了一颗决策树。
 

二、代码实现

1.信息增益

 一般而言,信息增益越大,则意味着使用属性a来进行划分所获得的“纯度提升”越大

代码实现 

#计算信息增益
def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1
    baseEntropy = calcShannonEnt1(dataSet)
    bestInfoGain = 0.0                       
    bestFeature = -1                         
    for i in range(numFeatures):
        featList = [example[i] for example in dataSet]
        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                  

2.数据集

 以100条征兵入伍的数据,用'身高', '体重', '视力', '有无纹身', '足型','有无传染病',判断是否满足入伍要求。

 读入数据集

 
#读入数据集
import pandas as pd
    myData = pd.read_excel('C:\Users\Rouger\PycharmProjects\pythonProject\shujuji.xlsx',header = None)
    print(myData.head())
    myData = np.array(myData).tolist()
    for d in myData:
        for i in range(len(d)):
            d[i] = d[i].strip()
    Labels = ['身高', '体重', '视力', '有无纹身', '足型','有无传染病']

3.决策树

代码如下

 
#创建决策树
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:{}}                       
    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
 
#使用pickle存储决策树
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)  
 

4.使用Matplotlib绘制决策树

代码如下

#绘制决策树
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',
        xytext=centerPt, textcoords='axes fraction',
        va="center", ha="center", bbox=nodeType, arrowprops=arrow_args) #绘制箭头的注解
 
 
#获取叶结点的数目
def getNumLeafs(myTree):
    numLeafs = 0                                     
    #firstStr = myTree.keys()[0]
    firstStr = next(iter(myTree))                   
    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 = next(iter(myTree))
    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
 
 
#plotTree函数
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 = next(iter(myTree))
    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
            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()
 
#使用决策树的分类函数
def classify(inputTree,featLabels,testVec):          
    firstStr = list(inputTree.keys())[0]
    secondDict = inputTree[firstStr]            
    featIndex = featLabels.index(firstStr)      #将标签字符串转换为索引
    for key in secondDict.keys():
        if testVec[featIndex] == key:
            if type(secondDict[key]).__name__=='dict':
                classLabel = classify(secondDict[key],featLabels,testVec)
            else:
                classLabel = secondDict[key]
        return classLabel

5.实验结果

使用信息增益方法生成决策树

 使用以下数据进行验证

结果

 

 正确率为90%

三、总结

1、优点

1)易于理解和解释,决策树可以可视化。
2)几乎不需要数据预处理。其他方法经常需要数据标准化,创建虚拟变量和删除缺失值。决策树还不支持缺失值。
3)使用树的花费(例如预测数据)是训练数据点(data points)数量的对数。
4)可以同时处理数值变量和分类变量。其他方法大都适用于分析一种变量的集合。
5)可以处理多值输出变量问题。

2、缺点

1)决策树学习可能创建一个过于复杂的树,并不能很好的预测数据。也就是过拟合。修剪机制(现在不支持),设置一个叶子节点需要的最小样本数量,或者数的最大深度,可以避免过拟合。
2)决策树可能是不稳定的,因为即使非常小的变异,可能会产生一颗完全不同的树。这个问题通过decision trees with an ensemble来缓解。
3)概念难以学习,因为决策树没有很好的解释他们。
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值