简单实现决策树

实验数据集

隐形眼镜数据集

实验代码

DecisionTree.py

import operator
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 #存在该字典元素则标签出现次数+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
"""
输入参数:
    dataSet : 总数据集 
    axis : 数据集的第几列特征 
    value: 以及该特征值划分
"""
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
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) #划分子数据集
            prob = len(subDataSet)/float(len(dataSet))
            newEntropy += prob * calcShannonEnt(subDataSet) #计算划分子集后的香农熵
        infoGain = baseEntropy - newEntropy #计算信息增益
        if(infoGain > bestInfoGain):
            bestInfoGain = infoGain
            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.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



PlotDecisionTree.py

import matplotlib.pyplot as plt
import DecisionTree as trees
decisionNode = dict(boxstyle='sawtooth', fc='0.8') #sawtooth样式
leafNode = dict(boxstyle='round4', fc='0.8') #round4样式
arrow_args = dict(arrowstyle='<-') #箭头样式
"""
annotate 参数说明 
    xy 箭头起始点
    xytext 箭头终点
    text 节点上注释的文本
    xycoords/textcoords 定义了xy、xytext的坐标系统 默认值 figure fraction 
    va\ha 定义文本的对齐方式 va垂直高度 ha水平高度
    arrowprops 定义箭头的样式
    bbox 字典 用于定义注释框的样式
"""
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 = 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]

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)
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
            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
#二进制序列化写入
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')
    tree = pickle.load(fr)
    fr.close()
    return tree
def plotLensesTree():
    fr = open('lenses.txt')
    lenses = [inst.strip().split('\t') for inst in fr.readlines()]
    lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']

    trees.createTree(lenses, lensesLabels)

plotLensesTree()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值