侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python机器学习理论与实战(二)决策树

Python  /  管理员 发布于 7年前   139

        决策树也是有监督机器学习方法。 电影《无耻混蛋》里有一幕游戏,在德军小酒馆里有几个人在玩20问题游戏,游戏规则是一个设迷者在纸牌中抽出一个目标(可以是人,也可以是物),而猜谜者可以提问题,设迷者只能回答是或者不是,在几个问题(最多二十个问题)之后,猜谜者通过逐步缩小范围就准确的找到了答案。这就类似于决策树的工作原理。(图一)是一个判断邮件类别的工作方式,可以看出判别方法很简单,基本都是阈值判断,关键是如何构建决策树,也就是如何训练一个决策树。

(图一)

构建决策树的伪代码如下:

Check if every item in the dataset is in the same class:    If so return the class label    Else       find the best feature to split the data       split the dataset        create a branch node       for each split          call create Branch and add the result to the branch node      return branch node

         原则只有一个,尽量使得每个节点的样本标签尽可能少,注意上面伪代码中一句说:find the best feature to split the data,那么如何find thebest feature?一般有个准则就是尽量使得分支之后节点的类别纯一些,也就是分的准确一些。如(图二)中所示,从海洋中捞取的5个动物,我们要判断他们是否是鱼,先用哪个特征?

(图二)

         为了提高识别精度,我们是先用“离开陆地能否存活”还是“是否有蹼”来判断?我们必须要有一个衡量准则,常用的有信息论、基尼纯度等,这里使用前者。我们的目标就是选择使得分割后数据集的标签信息增益最大的那个特征,信息增益就是原始数据集标签基熵减去分割后的数据集标签熵,换句话说,信息增益大就是熵变小,使得数据集更有序。熵的计算如(公式一)所示:

有了指导原则,那就进入代码实战阶段,先来看看熵的计算代码:

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 

有了熵的计算代码,接下来看依照信息增益变大的原则选择特征的代码:

def splitDataSet(dataSet, axis, value):   retDataSet = []   for featVec in dataSet:     if featVec[axis] == value:       reducedFeatVec = featVec[:axis]   #chop out axis used for splitting       reducedFeatVec.extend(featVec[axis+1:])       retDataSet.append(reducedFeatVec)   return retDataSet    def chooseBestFeatureToSplit(dataSet):   numFeatures = len(dataSet[0]) - 1   #the last column is used for the labels   baseEntropy = calcShannonEnt(dataSet)   bestInfoGain = 0.0; bestFeature = -1   for i in range(numFeatures):    #iterate over all the features     featList = [example[i] for example in dataSet]#create a list of all the examples of this feature     uniqueVals = set(featList)    #get a set of unique values     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 

        从最后一个if可以看出,选择使得信息增益最大的特征作为分割特征,现在有了特征分割准则,继续进入一下个环节,如何构建决策树,其实就是依照最上面的伪代码写下去,采用递归的思想依次分割下去,直到执行完成就构建了决策树。代码如下:

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   

用图二的样本构建的决策树如(图三)所示:


(图三)

有了决策树,就可以用它做分类咯,分类代码如下:

def classify(inputTree,featLabels,testVec):   firstStr = inputTree.keys()[0]   secondDict = inputTree[firstStr]   featIndex = featLabels.index(firstStr)   key = testVec[featIndex]   valueOfFeat = secondDict[key]   if isinstance(valueOfFeat, dict):      classLabel = classify(valueOfFeat, featLabels, testVec)   else: classLabel = valueOfFeat   return classLabel 

最后给出序列化决策树(把决策树模型保存在硬盘上)的代码:

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) 

优点:检测速度快

缺点:容易过拟合,可以采用修剪的方式来尽量避免

参考文献:machine learning in action

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python机器学习理论与实战(四)逻辑回归
    下一条:
    Python爬虫天气预报实例详解(小白入门)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客