99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python機器學(xué)習(xí)之決策樹算法實例詳解
Python機器學(xué)習(xí)之決策樹算法實例詳解
2018-02-10
收藏

Python機器學(xué)習(xí)決策樹算法實例詳解

本文實例講述了Python機器學(xué)習(xí)決策樹算法。分享給大家供大家參考,具體如下:

決策樹學(xué)習(xí)是應(yīng)用最廣泛的歸納推理算法之一,是一種逼近離散值目標函數(shù)的方法,在這種方法中學(xué)習(xí)到的函數(shù)被表示為一棵決策樹決策樹可以使用不熟悉的數(shù)據(jù)集合,并從中提取出一系列規(guī)則,機器學(xué)習(xí)算法最終將使用這些從數(shù)據(jù)集中創(chuàng)造的規(guī)則。決策樹的優(yōu)點為:計算復(fù)雜度不高,輸出結(jié)果易于理解,對中間值的缺失不敏感,可以處理不相關(guān)特征數(shù)據(jù)。缺點為:可能產(chǎn)生過度匹配的問題。決策樹適于處理離散型和連續(xù)型的數(shù)據(jù)。

決策樹中最重要的就是如何選取用于劃分的特征

在算法中一般選用ID3,D3算法的核心問題是選取在樹的每個節(jié)點要測試的特征或者屬性,希望選擇的是最有助于分類實例的屬性。如何定量地衡量一個屬性的價值呢?這里需要引入熵和信息增益的概念。熵是信息論中廣泛使用的一個度量標準,刻畫了任意樣本集的純度。

假設(shè)有10個訓(xùn)練樣本,其中6個的分類標簽為yes,4個的分類標簽為no,那熵是多少呢?在該例子中,分類的數(shù)目為2(yes,no),yes的概率為0.6,no的概率為0.4,則熵為 :

其中value(A)是屬性A所有可能值的集合,是S中屬性A的值為v的子集,即。上述公式的第一項為原集合S的熵,第二項是用A分類S后熵的期望值,該項描述的期望熵就是每個子集的熵的加權(quán)和,權(quán)值為屬于的樣本占原始樣本S的比例。所以Gain(S, A)是由于知道屬性A的值而導(dǎo)致的期望熵減少。

完整的代碼:

# -*- coding: cp936 -*-
from numpy import *
import operator
from math import log
import operator
def createDataSet():
  dataSet = [[1,1,'yes'],
    [1,1,'yes'],
    [1,0,'no'],
    [0,1,'no'],
    [0,1,'no']]
  labels = ['no surfacing','flippers']
  return dataSet, labels
def calcShannonEnt(dataSet):
  numEntries = len(dataSet)
  labelCounts = {} # a dictionary for feature
  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:
    #print(key)
    #print(labelCounts[key])
    prob = float(labelCounts[key])/numEntries
    #print(prob)
    shannonEnt -= prob * log(prob,2)
  return shannonEnt
#按照給定的特征劃分數(shù)據(jù)集
#根據(jù)axis等于value的特征將數(shù)據(jù)提出
def 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 retDataSet
#選取特征,劃分數(shù)據(jù)集,計算得出最好的劃分數(shù)據(jù)集的特征
def chooseBestFeatureToSplit(dataSet):
  numFeatures = len(dataSet[0]) - 1 #剩下的是特征的個數(shù)
  baseEntropy = calcShannonEnt(dataSet)#計算數(shù)據(jù)集的熵,放到baseEntropy中
  bestInfoGain = 0.0;bestFeature = -1 #初始化熵增益
  for i in range(numFeatures):
    featList = [example[i] for example in dataSet] #featList存儲對應(yīng)特征所有可能得取值
    uniqueVals = set(featList)
    newEntropy = 0.0
    for value in uniqueVals:#下面是計算每種劃分方式的信息熵,特征i個,每個特征value個值
      subDataSet = splitDataSet(dataSet, i ,value)
      prob = len(subDataSet)/float(len(dataSet)) #特征樣本在總樣本中的權(quán)重
      newEntropy = prob * calcShannonEnt(subDataSet)
    infoGain = baseEntropy - newEntropy #計算i個特征的信息熵
    #print(i)
    #print(infoGain)
    if(infoGain > bestInfoGain):
      bestInfoGain = infoGain
      bestFeature = i
  return bestFeature
#如上面是決策樹所有的功能模塊
#得到原始數(shù)據(jù)集之后基于最好的屬性值進行劃分,每一次劃分之后傳遞到樹分支的下一個節(jié)點
#遞歸結(jié)束的條件是程序遍歷完成所有的數(shù)據(jù)集屬性,或者是每一個分支下的所有實例都具有相同的分類
#如果所有實例具有相同的分類,則得到一個葉子節(jié)點或者終止快
#如果所有屬性都已經(jīng)被處理,但是類標簽依然不是確定的,那么采用多數(shù)投票的方式
#返回出現(xiàn)次數(shù)最多的分類名稱
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]
#創(chuàng)建決策樹
def createTree(dataSet,labels):
  classList = [example[-1] for example in dataSet]#將最后一行的數(shù)據(jù)放到classList中,所有的類別的值
  if classList.count(classList[0]) == len(classList): #類別完全相同不需要再劃分
    return classList[0]
  if len(dataSet[0]) == 1:#這里為什么是1呢?就是說特征數(shù)為1的時候
    return majorityCnt(classList)#就返回這個特征就行了,因為就這一個特征
  bestFeat = chooseBestFeatureToSplit(dataSet)
  print('the bestFeatue in creating is :')
  print(bestFeat)
  bestFeatLabel = labels[bestFeat]#運行結(jié)果'no surfacing'
  myTree = {bestFeatLabel:{}}#嵌套字典,目前value是一個空字典
  del(labels[bestFeat])
  featValues = [example[bestFeat] for example in dataSet]#第0個特征對應(yīng)的取值
  uniqueVals = set(featValues)
  for value in uniqueVals: #根據(jù)當(dāng)前特征值的取值進行下一級的劃分
    subLabels = labels[:]
    myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet,bestFeat,value),subLabels)
  return myTree
#對上面簡單的數(shù)據(jù)進行小測試
def testTree1():
  myDat,labels=createDataSet()
  val = calcShannonEnt(myDat)
  print 'The classify accuracy is: %.2f%%' % val
  retDataSet1 = splitDataSet(myDat,0,1)
  print (myDat)
  print(retDataSet1)
  retDataSet0 = splitDataSet(myDat,0,0)
  print (myDat)
  print(retDataSet0)
  bestfeature = chooseBestFeatureToSplit(myDat)
  print('the bestFeatue is :')
  print(bestfeature)
  tree = createTree(myDat,labels)
  print(tree)

對應(yīng)的結(jié)果是:    
>>> import TREE
>>> TREE.testTree1()
The classify accuracy is: 0.97%
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
[[1, 'yes'], [1, 'yes'], [0, 'no']]
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
[[1, 'no'], [1, 'no']]
the bestFeatue is :
0
the bestFeatue in creating is :
0
the bestFeatue in creating is :
0
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

最好再增加使用決策樹的分類函數(shù)

同時因為構(gòu)建決策樹是非常耗時間的,因為最好是將構(gòu)建好的樹通過 python 的 pickle 序列化對象,將對象保存在磁盤上,等到需要用的時候再讀出    
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)

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }