2019独角兽企业重金招聘Python工程师标准>>>

每周一搏,提升自我。

这段时间对python的应用,对python的理解越来越深。摸索中修改网上实例代码,有了自己的理解。

c45是ID3算法的升级版,比ID3高级。个人建议,用CART算法,感觉比C45好。

下面是c45代码,其中显示决策树结构的代码,下篇博文发布。

#!/usr/bin/python
#coding:utf-8import operator
from math import log
import time
import os,sys
import string#已文件为数据源
def createDataSet(trainDataFile):print trainDataFiledataSet=[]try:fin=open(trainDataFile)for line in fin:line=line.strip('\n')  #清除行皆为换行符cols=line.split(',')  #逗号分割行信息row =[cols[1],cols[2],cols[3],cols[4],cols[5],cols[6],cols[7],cols[8],cols[9],cols[10],cols[0]]dataSet.append(row)#print rowexcept:print 'Usage xxx.py trainDataFilePath'sys.exit()labels=['cip1', 'cip2', 'cip3', 'cip4', 'sip1', 'sip2', 'sip3', 'sip4', 'sport', 'domain']print 'dataSetlen',len(dataSet)return dataSet,labels#c4.5 信息熵算法
def calcShannonEntOfFeature(dataSet,feat):numEntries=len(dataSet)labelCounts={}for feaVec in dataSet:currentLabel=feaVec[feat]if currentLabel not in labelCounts:labelCounts[currentLabel]=0labelCounts[currentLabel]+=1shannonEnt=0.0for key in labelCounts:prob=float(labelCounts[key])/numEntriesshannonEnt-=prob * log(prob,2)return shannonEntdef 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 retDataSetdef chooseBestFeatureToSplit(dataSet):numFeatures=len(dataSet[0])-1baseEntropy=calcShannonEntOfFeature(dataSet,-1)bestInfoGainRate=0.0bestFeature=-1for i in range(numFeatures):featList=[example[i] for example in dataSet]uniqueVals=set(featList)newEntropy=0.0for value in uniqueVals:subDataSet=splitDataSet(dataSet,i,value)prob=len(subDataSet) / float(len(dataSet))newEntropy+=prob * calcShannonEntOfFeature(subDataSet,-1)infoGain=baseEntropy- newEntropyiv = calcShannonEntOfFeature(dataSet,i)if(iv == 0):continueinfoGainRate= infoGain /ivif infoGainRate > bestInfoGainRate:bestInfoGainRate = infoGainRatebestFeature = ireturn bestFeaturedef majorityCnt(classList):classCount={}for vote in classList:if vote not in classCount.keys():classCount[vote]=0classCount[vote] +=1return max(classCount)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]if(bestFeat == -1): #特征一样,但类别不一样,即类别与特征不相关,随机选第一个类别分类结果return classList[0]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#创建简单的数据集   武器类型(0 步枪 1机枪),子弹(0 少 1多),血量(0 少,1多)  fight战斗 1逃跑
def createDataSet():dataSet =[[1,1,0,'fight'],[1,0,1,'fight'],[1,0,1,'fight'],[1,0,1,'fight'],[0,0,1,'run'],[0,1,0,'fight'],[0,1,1,'run']]lables=['weapon','bullet','blood']return dataSet,lables#按行打印数据集
def printData(myData):for item in myData:print '%s' %(item)#使用决策树分类
def classify(inputTree,featLabels,testVec):firstStr=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 picklefw=open(filename,'w')pickle.dump(inputTree,fw)fw.close()#获取决策树
def grabTree(filename):import picklefr=open(filename)return pickle.load(fr)def main():data,label =createDataSet()myTree=createTree(data,label)print(myTree)#打印决策树import showTree as showshow.createPlot(myTree)if __name__ == '__main__':main()

调用的showTree.py,内容如下:

#!/usr/bin/python
#coding:utf-8import matplotlib.pyplot as plt#决策树属性设置
decisionNode=dict(boxstyle="sawtooth",fc="0.8")
leafNode=dict(boxstyle="round4",fc="0.8")
arrow_args=dict(arrowstyle="<-")#createPlot 主函数,调用即可画出决策树,其中调用登了剩下的所有的函数,inTree的形式必须为嵌套的决策树
def createPlot(inThree):fig=plt.figure(1,facecolor='white')fig.clf()axprops=dict(xticks=[],yticks=[])createPlot.ax1=plt.subplot(111,frameon=False,**axprops)  #no ticks# createPlot.ax1=plt.subplot(111,frameon=False)  #ticks for demo puropsesplotTree.totalW=float(getNumLeafs(inThree))plotTree.totalD=float(getTreeDepth(inThree))plotTree.xOff=-0.5/plotTree.totalW;plotTree.yOff=1.0plotTree(inThree,(0.5,1.0),'')plt.show()#决策树上节点之间的箭头设置
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 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 getNumLeafs(myTree):numLeafs=0firstStr=myTree.keys()[0]secondDict=myTree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodesnumLeafs += getNumLeafs(secondDict[key])else: numLeafs+=1return numLeafs#得到决策树的深度
def getTreeDepth(myTree):maxDepthh=0firstStr=myTree.keys()[0]secondDict=myTree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':thisDepth=1+getTreeDepth(secondDict[key])else: thisDepth=1if thisDepth>maxDepthh:maxDepthh=thisDepthreturn maxDepthh#父子节点之间画决策树
def plotTree(myTree,parentPt,nodeTxt):numLeafs=getNumLeafs(myTree)depth=getTreeDepth(myTree)firstStr=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.totalDfor key in secondDict.keys():if type(secondDict[key]).__name__=='dict':plotTree(secondDict[key],cntrPt,str(key))else:plotTree.xOff=plotTree.xOff+1.0/plotTree.totalWplotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),cntrPt,leafNode)plotMidText((plotTree.xOff,plotTree.yOff),cntrPt,str(key))plotTree.yOff=plotTree.yOff+1.0/plotTree.totalD

转载于:https://my.oschina.net/wangzonghui/blog/1617580

python 决策树 math库 c45算法相关推荐

  1. python中math库_Python的math库、random库实际应用

    昨天在说那个列表的时候,我挖了一个坑,不知道你们看出来没有?就是用循环语句写迭代的时候,总是运行不了结果,其实是因为我没有缩进的问题,因为有一个for循环,下面print如果没有对应的缩进,那么就说明 ...

  2. python中math库_Python库详解之math库

    1 首先我们看下定义的Number-theoretic and representation functions. 1:ceil(x):功能:返回一个浮点数据,该数据向上取整. 2:copysign( ...

  3. python中math库最大值_python-math库解析

    math库的数学常数(共4个) math.pi 表示Π,圆周率,值为3.141592653589-- math.e 表示e,自然对数,值为2.718-- math.inf 表示正无穷大,负无穷大为-m ...

  4. [再学Python] - 2 - math库和random库

    math库 math库包含了一些常用的数学函数 random库 random库包含了一批随机函数

  5. python读取math_怎么使用python安装math库?怎么用?

    看到这个库的名称,有没有感觉到似曾相识呢?数学里就有这么个公式,有时候说编程和数学融会贯通使用,一点也没有错,那至于这个函数和数学表达式是不是一样的用法呢?请小伙伴们现在脑海中回忆下自己现在所了解的库 ...

  6. Python之math库

    Python math模块中定义了一些数学函数.由于这个模块属于编译系统自带,因此它可以被无条件调用.该模块还提供了与用标准C定义的数学函数的接口. 函数 方法处理问题 Python math.aco ...

  7. anaconda python下载math库_Anaconda下载及安装及查看安装的Python库用法

    Anaconda下载及安装及查看安装的Python库用法 Anaconda 是一个用于科学计算的 Python 发行版,提供了包管理与环境管理的功能.Anaconda 利用 conda 来进行 pac ...

  8. python中求和公式是什么函数_Python的math库中,用于求和的函数是( )。

    [单选题]确定兴利库容 V 兴 ,已知某水库为一回运用水库,其一次蓄水量为 V 1 =300 万 m 3 ,一次供水量为 V 2 =150 万 m 3 . [ ]. [单选题]hAB大于0说明B点的高 ...

  9. python实例练习(8)math库数学实例

    文章目录 简介 实例分析 代码实例 简介 本文将借用"每天努力一点"这个主题,利用python的math库来模拟每天努力一点后,自己的力量有多么强大,以及模拟自己随波逐流无所事事一 ...

最新文章

  1. 基于TI TMS320C6678 + Xilinx Kintex-7 的高性能信号处理方案
  2. visual studio 代码提示插件_程序员请收好:10个非常实用的 VS Code 插件
  3. 生产场景 bond 0实战
  4. 冲刺 (sprint) 评审会议
  5. JVM加载class文件的原理简述
  6. TextSwitcher--文本切换器
  7. pytorch: where、gather函数
  8. LeetCode 119. Pascal’s Triangle II
  9. Open3d之RGBD测程法
  10. GIT入门笔记(2)- 典型的工作模式
  11. 【Linux】VirtualBox设置静态ip
  12. 你未必知的拼音打字快打十招
  13. 从零开始配置腾讯云 CDN
  14. dlopen与dlsym用法
  15. python代码实现时间从12小时制到24小时制的转换
  16. es6 迭代器(遍历器)Iterator 自定义遍历器 lterator/简单模拟values方法 for of运行机制 Array/Set/Map默认迭代器接口 对象设置迭代器
  17. ARP request或reply包丢失导致速率下降优化
  18. 用Python设计第一个游戏,小插曲之变量和字符串(课堂笔记)
  19. python控制qq语音通话_懒人专用的奇淫技巧,用Python实现炫酷的语音操作电脑!...
  20. 猫眼api html,猫眼选座API使用说明

热门文章

  1. 使用vue-happy-scroll 自定义滚动条
  2. vue里ref ($refs)用法
  3. vue中使用watch监听$route 无效问题
  4. git add 失效
  5. svn cvs git的区别
  6. AI:IPPR的数学表示-CNN稀疏结构进化(Mobile、xception、Shuffle、SE、Dilated、Deformable)
  7. 使用PyQT编写界面程序
  8. 几个方便编程的C++特性
  9. 【C++专题】static_cast, dynamic_cast, const_cast探讨
  10. 模拟器显示屏上方的信号和电池图标不显示设置