机器学习实战python版第三章决策树代码理解

来源:互联网 发布:sql 修改字段默认值 编辑:程序博客网 时间:2024/05/22 13:28

今天开始学习第三章决策树。

前面对决策树的讲解我就不写了,书上写的都很清楚,就是根据特征的不同逐步的对数据进行分类,形状像一个倒立的树。决策树算法比kNN的算法复杂度要低,理解起来也有一定难度。

信息增益

每一组数据都有自己的熵,数据要整齐,熵越低。也就是说属于同一类的数据熵低,越混合的数据熵越高。计算数据集的熵代码如下:

<span style="font-size:24px;">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</span>

划分数据集

就是根据一个特征把数据进行划分。代码如下:

<span style="font-size:24px;">def splitDataSet(dataSet,axis,value):    retDataSet = []    for featVec in dataSet:        if featVec[axis] == value:            reducedFeatVec = featVec[:axis]#axis = 0时 这个列表是空的            reducedFeatVec.extend(featVec[axis + 1:])            retDataSet.append(reducedFeatVec)    return retDataSet</span>

append,和extend这两个函数很有意思。

结果如下:

<span style="font-size:24px;">>>> import trees>>> myDat,labels = trees.createDataSet()>>> myDat[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]>>> trees.splitDataSet(myDat,0,1)[[1, 'yes'], [1, 'yes'], [0, 'no']]</span>

但是实际操作中我们不能总能人工输入分类依据的特征。我们需要机器根据数据的特征自己判断最佳的分类特征。代码如下:

<span style="font-size:24px;">def chooseBestFeatureToSplit(dataSet):    numFeatures = len(dataSet[0]) - 1      #列减一    baseEntropy = calcShannonEnt(dataSet)    bestInfoGain = 0.0; bestFeature = -1    for i in range(numFeatures):        # 012遍历数据集        featList = [example[i] for example in dataSet]#create a list of all the examples of this feature全部数据组的第i个数据,        uniqueVals = set(featList)       #数据组的集,即{0,1}。{yes,no}        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                      #returns an integer</span>


结果如下:

<span style="font-size:24px;">>>> import trees>>> myDat,labels = trees.createDataSet()>>> trees.chooseBestFeatureToSplit(myDat)0</span>

建立决策树

书中的内容还是比较好理解的,树的建立理论也写得很详细,主要是代码比较难懂,因为python的代码很简洁,所以看起来也就更难一些。

创建树的函数代码:

<span style="font-size:24px;">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]#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                                </span>

首先这是一个递归函数,就是函数自己不停的调用自己,当遇到结束情况时在一步步返回。
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)
只有一个数据的时候
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)递归,每次调用两个creatTree,分两个字典给赋值。

结果如下:

<span style="font-size:24px;">>>> myDat,labels = trees.createDataSet()>>> myTree = trees.createTree(myDat,labels)>>> myTreesTraceback (most recent call last):  File "<pyshell#10>", line 1, in <module>    myTreesNameError: name 'myTrees' is not defined>>> myTree{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}</span>

下面的内容明天再写,希望大家多多指导!


1 0
原创粉丝点击