《机器学习实战》Python3实现代码(第三章节)

本文是针对《机器学习实战》(第三章)内所需要的程序代码进行修改(书中使用的是py2),现已py3呈现。

 

程序清单3-1:

from math import log

def createDataSet():
    dataSet = [[1,1,'maybe'],
               [1,1,'yes'],
               [1,0,'no'],
               [0,1,'no'],
               [0,1,'no']
                ]
    labels = ['no surfacing','flippers']
    return dataSet,labels

def clacShannonEnt(dataSet):
    numEntries = len(dataSet)
    labelCounts = {}
    for featVec in dataSet:
        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)
    return shannonEnt

if __name__== '__main__':
    dataSet,label = createDataSet()

    print(clacShannonEnt(dataSet))


运行结果:1.3709505944546687

 

程序清单3-2:

def splitDataSet(dataSet,axis,value):
    #create a new list,ban from change the data of testData
    retDataSet = []
    for featVec in dataSet:
    #function:
    #find the data in the dataSet and accord with the value which need to return
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]
            reducedFeatVec.extend(featVec[axis+1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet

运行结果:[[1, 'maybe'], [1, 'yes'], [0, 'no']]

 

程序清单3-3:

def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0])-1
    baseEntropy = clacShannonEnt(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 * clacShannonEnt(subDataSet)
        infoGain = baseEntropy - newEntropy
        if(infoGain > bestFeature):
            bestInfoGain = infoGain
            bestFeature = i
    return bestFeature

 

程序清单3-4:

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(label[bestFeat])
    featValues = [example[bestFeat] for example in dataSet]
    uniquevVals = set(featValues)
    for value in uniquevVals:
        subLabels = labels[:]
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet,bestFeat,value),subLabels)
    return myTree

def majorityCnt(classList):
    #存储classList中每个标签出现的频率
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount [vote] += 1
    sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse = True)
    return sortedClassCount[0][0]

运行结果:{'flippers': {0: 'no', 1: {'no surfacing': {0: 'no', 1: 'yes'}}}}

 

程序清单3-5:

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 createPlot():
    fig = plt.figure(1,facecolor='white')
    fig.clf()
    createPlot.ax1 = plt.subplot(111,frameon = False)
    plotNode('决策节点',(0.5,0.1),(0.1,0.5),decisionNode)
    plotNode('叶节点',(0.8,0.1),(0.3,0.8),leafNode)
    plt.show()

createPlot()

运行结果:

后面的代码不做描述,原因为不是核心机器学习代码。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值