老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業提供網站建設、域名注冊、服務器等服務

python如何實現決策樹分類-創新互聯

這篇文章主要介紹了python如何實現決策樹分類,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

創新互聯主打移動網站、做網站、成都網站制作、網站改版、網絡推廣、網站維護、域名與空間、等互聯網信息服務,為各行業提供服務。在技術實力的保障下,我們為客戶承諾穩定,放心的服務,根據網站的內容與功能再決定采用什么樣的設計。最后,要實現符合網站需求的內容、功能與設計,我們還會規劃穩定安全的技術方案做保障。

原始數據集:

python如何實現決策樹分類

變化后的數據集在程序代碼中體現,這就不截圖了

構建決策樹的代碼如下:

#coding :utf-8
'''
2017.6.25 author :Erin 
   function: "decesion tree" ID3
   
'''
import numpy as np
import pandas as pd
from math import log
import operator 
def load_data():
 
 #data=np.array(data)
 data=[['teenager' ,'high', 'no' ,'same', 'no'],
   ['teenager', 'high', 'no', 'good', 'no'],
   ['middle_aged' ,'high', 'no', 'same', 'yes'],
   ['old_aged', 'middle', 'no' ,'same', 'yes'],
   ['old_aged', 'low', 'yes', 'same' ,'yes'],
   ['old_aged', 'low', 'yes', 'good', 'no'],
   ['middle_aged', 'low' ,'yes' ,'good', 'yes'],
   ['teenager' ,'middle' ,'no', 'same', 'no'],
   ['teenager', 'low' ,'yes' ,'same', 'yes'],
   ['old_aged' ,'middle', 'yes', 'same', 'yes'],
   ['teenager' ,'middle', 'yes', 'good', 'yes'],
   ['middle_aged' ,'middle', 'no', 'good', 'yes'],
   ['middle_aged', 'high', 'yes', 'same', 'yes'],
   ['old_aged', 'middle', 'no' ,'good' ,'no']]
 features=['age','input','student','level']
 return data,features
 
def cal_entropy(dataSet):
 '''
 輸入data ,表示帶最后標簽列的數據集
 計算給定數據集總的信息熵
 {'是': 9, '否': 5}
 0.9402859586706309
 '''
 
 numEntries = len(dataSet)
 labelCounts = {}
 for featVec in dataSet:
  label = featVec[-1]
  if label not in labelCounts.keys():
   labelCounts[label] = 0
  labelCounts[label] += 1
 entropy = 0.0
 for key in labelCounts.keys():
  p_i = float(labelCounts[key]/numEntries)
  entropy -= p_i * log(p_i,2)#log(x,10)表示以10 為底的對數
 return entropy
 
def split_data(data,feature_index,value):
 '''
 劃分數據集
 feature_index:用于劃分特征的列數,例如“年齡”
 value:劃分后的屬性值:例如“青少年”
 '''
 data_split=[]#劃分后的數據集
 for feature in data:
  if feature[feature_index]==value:
   reFeature=feature[:feature_index]
   reFeature.extend(feature[feature_index+1:])
   data_split.append(reFeature)
 return data_split
def choose_best_to_split(data):
 
 '''
 根據每個特征的信息增益,選擇大的劃分數據集的索引特征
 '''
 
 count_feature=len(data[0])-1#特征個數4
 #print(count_feature)#4
 entropy=cal_entropy(data)#原數據總的信息熵
 #print(entropy)#0.9402859586706309
 
 max_info_gain=0.0#信息增益大
 split_fea_index = -1#信息增益大,對應的索引號
 
 for i in range(count_feature):
  
  feature_list=[fe_index[i] for fe_index in data]#獲取該列所有特征值
  #######################################
  '''
  print('feature_list')
  ['青少年', '青少年', '中年', '老年', '老年', '老年', '中年', '青少年', '青少年', '老年',
  '青少年', '中年', '中年', '老年']
  0.3467680694480959 #對應上篇博客中的公式 =(1)*5/14
  0.3467680694480959
  0.6935361388961918
  '''
  # print(feature_list)
  unqval=set(feature_list)#去除重復
  Pro_entropy=0.0#特征的熵
  for value in unqval:#遍歷改特征下的所有屬性
   sub_data=split_data(data,i,value)
   pro=len(sub_data)/float(len(data))
   Pro_entropy+=pro*cal_entropy(sub_data)
   #print(Pro_entropy)
   
  info_gain=entropy-Pro_entropy
  if(info_gain>max_info_gain):
   max_info_gain=info_gain
   split_fea_index=i
 return split_fea_index
  
  
##################################################
def most_occur_label(labels):
 #sorted_label_count[0][0] 次數最多的類標簽
 label_count={}
 for label in labels:
  if label not in label_count.keys():
   label_count[label]=0
  else:
   label_count[label]+=1
  sorted_label_count = sorted(label_count.items(),key = operator.itemgetter(1),reverse = True)
 return sorted_label_count[0][0]
def build_decesion_tree(dataSet,featnames):
 '''
 字典的鍵存放節點信息,分支及葉子節點存放值
 '''
 featname = featnames[:]    ################
 classlist = [featvec[-1] for featvec in dataSet] #此節點的分類情況
 if classlist.count(classlist[0]) == len(classlist): #全部屬于一類
  return classlist[0]
 if len(dataSet[0]) == 1:   #分完了,沒有屬性了
  return Vote(classlist)  #少數服從多數
 # 選擇一個最優特征進行劃分
 bestFeat = choose_best_to_split(dataSet)
 bestFeatname = featname[bestFeat]
 del(featname[bestFeat])  #防止下標不準
 DecisionTree = {bestFeatname:{}}
 # 創建分支,先找出所有屬性值,即分支數
 allvalue = [vec[bestFeat] for vec in dataSet]
 specvalue = sorted(list(set(allvalue))) #使有一定順序
 for v in specvalue:
  copyfeatname = featname[:]
  DecisionTree[bestFeatname][v] = build_decesion_tree(split_data(dataSet,bestFeat,v),copyfeatname)
 return DecisionTree

繪制可視化圖的代碼如下:

def getNumLeafs(myTree):
 '計算決策樹的葉子數'
 
 # 葉子數
 numLeafs = 0
 # 節點信息
 sides = list(myTree.keys()) 
 firstStr =sides[0]
 # 分支信息
 secondDict = myTree[firstStr]
 
 for key in secondDict.keys(): # 遍歷所有分支
  # 子樹分支則遞歸計算
  if type(secondDict[key]).__name__=='dict':
   numLeafs += getNumLeafs(secondDict[key])
  # 葉子分支則葉子數+1
  else: numLeafs +=1
  
 return numLeafs
 
 
def getTreeDepth(myTree):
 '計算決策樹的深度'
 
 # 大深度
 maxDepth = 0
 # 節點信息
 sides = list(myTree.keys()) 
 firstStr =sides[0]
 # 分支信息
 secondDict = myTree[firstStr]
 
 for key in secondDict.keys(): # 遍歷所有分支
  # 子樹分支則遞歸計算
  if type(secondDict[key]).__name__=='dict':
   thisDepth = 1 + getTreeDepth(secondDict[key])
  # 葉子分支則葉子數+1
  else: thisDepth = 1
  
  # 更新大深度
  if thisDepth > maxDepth: maxDepth = thisDepth
  
 return maxDepth
 
import matplotlib.pyplot as plt
 
decisionNode = dict(box, fc="0.8")
leafNode = dict(box, fc="0.8")
arrow_args = dict(arrow)
 
# ==================================================
# 輸入:
#  nodeTxt:  終端節點顯示內容
#  centerPt: 終端節點坐標
#  parentPt: 起始節點坐標
#  nodeType: 終端節點樣式
# 輸出:
#  在圖形界面中顯示輸入參數指定樣式的線段(終端帶節點)
# ==================================================
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 )
 
# =================================================================
# 輸入:
#  cntrPt:  終端節點坐標
#  parentPt: 起始節點坐標
#  txtString: 待顯示文本內容
# 輸出:
#  在圖形界面指定位置(cntrPt和parentPt中間)顯示文本內容(txtString)
# =================================================================
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)
 
# ===================================
# 輸入:
#  myTree: 決策樹
#  parentPt: 根節點坐標
#  nodeTxt: 根節點坐標信息
# 輸出:
#  在圖形界面繪制決策樹
# ===================================
def plotTree(myTree, parentPt, nodeTxt):
 '繪制決策樹'
 
 # 當前樹的葉子數
 numLeafs = getNumLeafs(myTree)
 # 當前樹的節點信息
 sides = list(myTree.keys()) 
 firstStr =sides[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]
 # 開始繪制子樹,縱坐標-1。  
 plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
  
 for key in secondDict.keys(): # 遍歷所有分支
  # 子樹分支則遞歸
  if type(secondDict[key]).__name__=='dict':
   plotTree(secondDict[key],cntrPt,str(key))
  # 葉子分支則直接繪制
  else:
   plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
   plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
   plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
  
 # 子樹繪制完畢,縱坐標+1。
 plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
 
# ==============================
# 輸入:
#  myTree: 決策樹
# 輸出:
#  在圖形界面顯示決策樹
# ==============================
def createPlot(inTree):
 '顯示決策樹'
 
 # 創建新的圖像并清空 - 無橫縱坐標
 fig = plt.figure(1, facecolor='white')
 fig.clf()
 axprops = dict(xticks=[], yticks=[])
 createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
 
 # 樹的總寬度 高度
 plotTree.totalW = float(getNumLeafs(inTree))
 plotTree.totalD = float(getTreeDepth(inTree))
 
 # 當前繪制節點的坐標
 plotTree.xOff = -0.5/plotTree.totalW; 
 plotTree.yOff = 1.0;
 
 # 繪制決策樹
 plotTree(inTree, (0.5,1.0), '')
 
 plt.show()
 
if __name__ == '__main__':
 data,features=load_data()
 split_fea_index=choose_best_to_split(data)
 newtree=build_decesion_tree(data,features)
 print(newtree)
 createPlot(newtree)
 '''
 {'age': {'old_aged': {'level': {'same': 'yes', 'good': 'no'}}, 'teenager': {'student': {'no': 'no', 'yes': 'yes'}}, 'middle_aged': 'yes'}}
 '''

結果如下:

python如何實現決策樹分類

感謝你能夠認真閱讀完這篇文章,希望小編分享的“python如何實現決策樹分類”這篇文章對大家有幫助,同時也希望大家多多支持創新互聯成都網站設計公司,關注創新互聯成都網站設計公司行業資訊頻道,更多相關知識等著你來學習!

另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、網站設計器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。


網頁名稱:python如何實現決策樹分類-創新互聯
分享路徑:http://www.xueling.net.cn/article/djiodj.html

其他資訊

在線咨詢
服務熱線
服務熱線:028-86922220
TOP
主站蜘蛛池模板: 亚洲欧美成人A∨在线观看 亚洲一区二区福利视频 | 亚洲日韩蜜桃av在线观看 | 中文字幕无码日韩专区免费 | 中文在线一区二区 | 国产一区二区在线免费播放 | 99国产精品永久免费视频 | 国产在线不卡精品网站 | 亚洲三级中文字幕在线看 | 亚洲AV福利天堂一区二区三 | 黄色片免费看视频 | 亚洲综合清纯唯美 | 99久久成人| 成人欧美一区二区三区黑人孕妇 | 五月丁香亚洲综合无码 | 色综合久久综合中文综合网 | 国产乱子伦一区二区三区视频播放 | 粉嫩在线一区二区三区视频 | 男生操女生视频在线观看 | 欧美福利 | 久久国产综合 | 欧美同性gv片在线观看 | 97超碰国产精品无码分类 | 岛国一区 | 91精品午夜窝窝看片 | 99热99精品| www.免费网站在线观看 | 4438ⅹ亚洲全国最大色丁香 | 亚洲第一色| 国产揄拍国产精品人妻蜜 | 韩日在线观看视频 | 免费女人18毛片A级毛片视频 | 凸输偷窥xxxx自由免费视频 | 精品成人久久久 | 亚洲久本草在线中文字幕 | 国产激情999 | 亚洲成人av中文字幕 | 亚洲精品自偷自拍无码忘忧 | 久久欧美精品一区 | 四虎影视在线观看视频 | 激情91 | 99久久免费国产精精品 |