python實(shí)現(xiàn)C4.5決策樹算法
C4.5算法使用信息增益率來代替ID3的信息增益進(jìn)行特征的選擇,克服了信息增益選擇特征時(shí)偏向于特征值個(gè)數(shù)較多的不足。信息增益率的定義如下:
# -*- coding: utf-8 -*- from numpy import * import math import copy import cPickle as pickle class C45DTree(object): def __init__(self): # 構(gòu)造方法 self.tree = {} # 生成樹 self.dataSet = [] # 數(shù)據(jù)集 self.labels = [] # 標(biāo)簽集 # 數(shù)據(jù)導(dǎo)入函數(shù) def loadDataSet(self, path, labels): recordList = [] fp = open(path, "rb") # 讀取文件內(nèi)容 content = fp.read() fp.close() rowList = content.splitlines() # 按行轉(zhuǎn)換為一維表 recordList = [row.split("\t") for row in rowList if row.strip()] # strip()函數(shù)刪除空格、Tab等 self.dataSet = recordList self.labels = labels # 執(zhí)行決策樹函數(shù) def train(self): labels = copy.deepcopy(self.labels) self.tree = self.buildTree(self.dataSet, labels) # 構(gòu)件決策樹:穿件決策樹主程序 def buildTree(self, dataSet, lables): cateList = [data[-1] for data in dataSet] # 抽取源數(shù)據(jù)集中的決策標(biāo)簽列 # 程序終止條件1:如果classList只有一種決策標(biāo)簽,停止劃分,返回這個(gè)決策標(biāo)簽 if cateList.count(cateList[0]) == len(cateList): return cateList[0] # 程序終止條件2:如果數(shù)據(jù)集的第一個(gè)決策標(biāo)簽只有一個(gè),返回這個(gè)標(biāo)簽 if len(dataSet[0]) == 1: return self.maxCate(cateList) # 核心部分 bestFeat, featValueList= self.getBestFeat(dataSet) # 返回?cái)?shù)據(jù)集的最優(yōu)特征軸 bestFeatLabel = lables[bestFeat] tree = {bestFeatLabel: {}} del (lables[bestFeat]) for value in featValueList: # 決策樹遞歸生長(zhǎng) subLables = lables[:] # 將刪除后的特征類別集建立子類別集 # 按最優(yōu)特征列和值分隔數(shù)據(jù)集 splitDataset = self.splitDataSet(dataSet, bestFeat, value) subTree = self.buildTree(splitDataset, subLables) # 構(gòu)建子樹 tree[bestFeatLabel][value] = subTree return tree # 計(jì)算出現(xiàn)次數(shù)最多的類別標(biāo)簽 def maxCate(self, cateList): items = dict([(cateList.count(i), i) for i in cateList]) return items[max(items.keys())] # 計(jì)算最優(yōu)特征 def getBestFeat(self, dataSet): Num_Feats = len(dataSet[0][:-1]) totality = len(dataSet) BaseEntropy = self.computeEntropy(dataSet) ConditionEntropy = [] # 初始化條件熵 slpitInfo = [] # for C4.5,caculate gain ratio allFeatVList = [] for f in xrange(Num_Feats): featList = [example[f] for example in dataSet] [splitI, featureValueList] = self.computeSplitInfo(featList) allFeatVList.append(featureValueList) slpitInfo.append(splitI) resultGain = 0.0 for value in featureValueList: subSet = self.splitDataSet(dataSet, f, value) appearNum = float(len(subSet)) subEntropy = self.computeEntropy(subSet) resultGain += (appearNum/totality)*subEntropy ConditionEntropy.append(resultGain) # 總條件熵 infoGainArray = BaseEntropy*ones(Num_Feats)-array(ConditionEntropy) infoGainRatio = infoGainArray/array(slpitInfo) # C4.5信息增益的計(jì)算 bestFeatureIndex = argsort(-infoGainRatio)[0] return bestFeatureIndex, allFeatVList[bestFeatureIndex] # 計(jì)算劃分信息 def computeSplitInfo(self, featureVList): numEntries = len(featureVList) featureVauleSetList = list(set(featureVList)) valueCounts = [featureVList.count(featVec) for featVec in featureVauleSetList] pList = [float(item)/numEntries for item in valueCounts] lList = [item*math.log(item, 2) for item in pList] splitInfo = -sum(lList) return splitInfo, featureVauleSetList # 計(jì)算信息熵 # @staticmethod def computeEntropy(self, dataSet): dataLen = float(len(dataSet)) cateList = [data[-1] for data in dataSet] # 從數(shù)據(jù)集中得到類別標(biāo)簽 # 得到類別為key、 出現(xiàn)次數(shù)value的字典 items = dict([(i, cateList.count(i)) for i in cateList]) infoEntropy = 0.0 for key in items: # 香農(nóng)熵: = -p*log2(p) --infoEntropy = -prob * log(prob, 2) prob = float(items[key]) / dataLen infoEntropy -= prob * math.log(prob, 2) return infoEntropy # 劃分?jǐn)?shù)據(jù)集: 分割數(shù)據(jù)集; 刪除特征軸所在的數(shù)據(jù)列,返回剩余的數(shù)據(jù)集 # dataSet : 數(shù)據(jù)集; axis: 特征軸; value: 特征軸的取值 def splitDataSet(self, dataSet, axis, value): rtnList = [] for featVec in dataSet: if featVec[axis] == value: rFeatVec = featVec[:axis] # list操作:提取0~(axis-1)的元素 rFeatVec.extend(featVec[axis + 1:]) # 將特征軸之后的元素加回 rtnList.append(rFeatVec) return rtnList # 存取樹到文件 def storetree(self, inputTree, filename): fw = open(filename,'w') pickle.dump(inputTree, fw) fw.close() # 從文件抓取樹 def grabTree(self, filename): fr = open(filename) return pickle.load(fr)
調(diào)用代碼
# -*- coding: utf-8 -*- from numpy import * from C45DTree import * dtree = C45DTree() dtree.loadDataSet("dataset.dat",["age", "revenue", "student", "credit"]) dtree.train() dtree.storetree(dtree.tree, "data.tree") mytree = dtree.grabTree("data.tree") print mytree
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于python實(shí)現(xiàn)Pycharm斷點(diǎn)調(diào)試
這篇文章主要介紹了基于python實(shí)現(xiàn)Pycharm斷點(diǎn)調(diào)試,在我們寫程序的時(shí)候,很容易遇到各種各樣的bug,然后編譯器提示程序出錯(cuò)的地方。很多時(shí)候可以通過提示的信息修改程序,但是有時(shí)我們想得到更多的信息,這個(gè)時(shí)候就需要進(jìn)行斷點(diǎn)調(diào)試,下面我們就一起來學(xué)習(xí)ycharm斷點(diǎn)調(diào)試2022-02-02python基礎(chǔ)教程之python消息摘要算法使用示例
這篇文章主要介紹了python中的消息摘要算法使用示例,需要的朋友可以參考下2014-02-02在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度
今天小編就為大家分享一篇在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02python文字轉(zhuǎn)語音的實(shí)例代碼分析
在本篇文章里小編給大家整理的是關(guān)于python文字轉(zhuǎn)語音的實(shí)例代碼分析,有需要的朋友們可以參考下。2019-11-11Python利用request庫實(shí)現(xiàn)翻譯接口
這篇文章主要為大家詳細(xì)介紹了Python如何利用request庫打造自己的翻譯接口,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-04-04基于python實(shí)現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議)
這篇文章主要介紹了基于python實(shí)現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04詳解如何在cmd命令窗口中搭建簡(jiǎn)單的python開發(fā)環(huán)境
這篇文章主要介紹了詳解如何在cmd命令窗口中搭建簡(jiǎn)單的python開發(fā)環(huán)境,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08解決使用pycharm提交代碼時(shí)沖突之后文件丟失找回的方法
這篇文章主要介紹了解決使用pycharm提交代碼時(shí)沖突之后文件丟失找回的方法 ,需要的朋友可以參考下2018-08-08