2.2.1 信息增益(information gain)php
2.2.2 信息增益比(information gain ratio)html
2.2.3 基尼指數(Gini index)node
""" 函數說明:建立測試數據集 Parameters: 無 Returns: dataSet - 數據集 labels - 特徵標籤 """ def createDataSet(): dataSet = [[0, 0, 0, 0, 'no'], #數據集 [0, 0, 0, 1, 'no'], [0, 1, 0, 1, 'yes'], [0, 1, 1, 0, 'yes'], [0, 0, 0, 0, 'no'], [1, 0, 0, 0, 'no'], [1, 0, 0, 1, 'no'], [1, 1, 1, 1, 'yes'], [1, 0, 1, 2, 'yes'], [1, 0, 1, 2, 'yes'], [2, 0, 1, 2, 'yes'], [2, 0, 1, 1, 'yes'], [2, 1, 0, 1, 'yes'], [2, 1, 0, 2, 'yes'], [2, 0, 0, 0, 'no']] labels = ['年齡', '有工做', '有本身的房子', '信貸狀況'] #特徵標籤 return dataSet, labels #返回數據集和分類屬性
""" 函數說明:按照給定特徵劃分數據集 Parameters: dataSet - 待劃分的數據集 axis - 劃分數據集的特徵 value - 須要返回的特徵的值 Returns: 無 """ def splitDataSet(dataSet, axis, value): retDataSet = [] #建立返回的數據集列表 for featVec in dataSet: #遍歷數據集 if featVec[axis] == value: reducedFeatVec = featVec[:axis] #去掉axis特徵 reducedFeatVec.extend(featVec[axis+1:]) #將符合條件的添加到返回的數據集 retDataSet.append(reducedFeatVec) return retDataSet #返回劃分後的數據集
3)計算香儂熵python
""" 函數說明:計算給定數據集的經驗熵(香農熵) Parameters: dataSet - 數據集 Returns: shannonEnt - 經驗熵(香農熵) """ def calcShannonEnt(dataSet): numEntires = len(dataSet) #返回數據集的行數 labelCounts = {} #保存每一個標籤(Label)出現次數的字典 for featVec in dataSet: #對每組特徵向量進行統計 currentLabel = featVec[-1] #提取標籤(Label)信息 if currentLabel not in labelCounts.keys(): #若是標籤(Label)沒有放入統計次數的字典,添加進去 labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 #Label計數 shannonEnt = 0.0 #經驗熵(香農熵) for key in labelCounts: #計算香農熵 prob = float(labelCounts[key]) / numEntires #選擇該標籤(Label)的機率 shannonEnt -= prob * log(prob, 2) #利用公式計算 return shannonEnt #返回經驗熵(香農熵)
4)選擇最優特徵git
""" 函數說明:選擇最優特徵 Parameters: dataSet - 數據集 Returns: bestFeature - 信息增益最大的(最優)特徵的索引值 """ def chooseBestFeatureToSplit(dataSet): numFeatures = len(dataSet[0]) - 1 #特徵數量 baseEntropy = calcShannonEnt(dataSet) #計算數據集的香農熵 bestInfoGain = 0.0 #信息增益 bestFeature = -1 #最優特徵的索引值 for i in range(numFeatures): #遍歷全部特徵 #獲取dataSet的第i個全部特徵 featList = [example[i] for example in dataSet] uniqueVals = set(featList) #建立set集合{},元素不可重複 newEntropy = 0.0 #經驗條件熵 for value in uniqueVals: #計算信息增益 subDataSet = splitDataSet(dataSet, i, value) #subDataSet劃分後的子集 prob = len(subDataSet) / float(len(dataSet)) #計算子集的機率 newEntropy += prob * calcShannonEnt(subDataSet) #根據公式計算經驗條件熵 infoGain = baseEntropy - newEntropy #信息增益 # print("第%d個特徵的增益爲%.3f" % (i, infoGain)) #打印每一個特徵的信息增益 if (infoGain > bestInfoGain): #計算信息增益 bestInfoGain = infoGain #更新信息增益,找到最大的信息增益 bestFeature = i #記錄信息增益最大的特徵的索引值 return bestFeature
""" 函數說明:統計classList中出現此處最多的元素(類標籤) Parameters: classList - 類標籤列表 Returns: sortedClassCount[0][0] - 出現此處最多的元素(類標籤) """ def majorityCnt(classList): classCount = {} for vote in classList: #統計classList中每一個元素出現的次數 if vote not in classCount.keys():classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True) #根據字典的值降序排序 return sortedClassCount[0][0] #返回classList中出現次數最多的元素 """
6)建立決策樹github
""" 函數說明:建立決策樹 Parameters: dataSet - 訓練數據集 labels - 分類屬性標籤 featLabels - 存儲選擇的最優特徵標籤 Returns: myTree - 決策樹 """ def createTree(dataSet, labels, featLabels): classList = [example[-1] for example in dataSet] #取分類標籤(是否放貸:yes or no) if classList.count(classList[0]) == len(classList): #若是類別徹底相同則中止繼續劃分 return classList[0] if len(dataSet[0]) == 1: #遍歷完全部特徵時返回出現次數最多的類標籤 return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) #選擇最優特徵 bestFeatLabel = labels[bestFeat] #最優特徵的標籤 featLabels.append(bestFeatLabel) myTree = {bestFeatLabel:{}} #根據最優特徵的標籤生成樹 del(labels[bestFeat]) #刪除已經使用特徵標籤 featValues = [example[bestFeat] for example in dataSet] #獲得訓練集中全部最優特徵的屬性值 uniqueVals = set(featValues) #去掉重複的屬性值 for value in uniqueVals: #遍歷特徵,建立決策樹。 myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), labels, featLabels) return myTree
遞歸建立決策樹時,遞歸有兩個終止條件:第一個中止條件是全部的類標籤徹底相同,則直接返回該類標籤;第二個中止條件是使用完了全部特徵,仍然不能將數據劃分僅包含惟一類別的分組,即決策樹構建失敗,特徵不夠用。此時說明數據緯度不夠,因爲第二個中止條件沒法簡單地返回惟一的類標籤,這裏挑選出現數量最多的類別做爲返回值。算法
""" 函數說明:獲取決策樹葉子結點的數目 Parameters: myTree - 決策樹 Returns: numLeafs - 決策樹的葉子結點的數目 """ def getNumLeafs(myTree): numLeafs = 0 #初始化葉子 firstStr = next(iter(myTree)) #python3中myTree.keys()返回的是dict_keys,不在是list,因此不能使用myTree.keys()[0]的方法獲取結點屬性,可使用list(myTree.keys())[0] secondDict = myTree[firstStr] #獲取下一組字典 for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': #測試該結點是否爲字典,若是不是字典,表明此結點爲葉子結點 numLeafs += getNumLeafs(secondDict[key]) else: numLeafs +=1 return numLeafs """ 函數說明:獲取決策樹的層數 Parameters: myTree - 決策樹 Returns: maxDepth - 決策樹的層數 """ def getTreeDepth(myTree): maxDepth = 0 #初始化決策樹深度 firstStr = next(iter(myTree)) #python3中myTree.keys()返回的是dict_keys,不在是list,因此不能使用myTree.keys()[0]的方法獲取結點屬性,可使用list(myTree.keys())[0] secondDict = myTree[firstStr] #獲取下一個字典 for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': #測試該結點是否爲字典,若是不是字典,表明此結點爲葉子結點 thisDepth = 1 + getTreeDepth(secondDict[key]) else: thisDepth = 1 if thisDepth > maxDepth: maxDepth = thisDepth #更新層數 return maxDepth """ 函數說明:繪製結點 Parameters: nodeTxt - 結點名 centerPt - 文本位置 parentPt - 標註的箭頭位置 nodeType - 結點格式 Returns: 無 """ def plotNode(nodeTxt, centerPt, parentPt, nodeType): arrow_args = dict(arrowstyle="<-") #定義箭頭格式 font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) #設置中文字體 createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', #繪製結點 xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args, FontProperties=font) """ 函數說明:標註有向邊屬性值 Parameters: cntrPt、parentPt - 用於計算標註位置 txtString - 標註的內容 Returns: 無 """ 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) """ 函數說明:繪製決策樹 Parameters: myTree - 決策樹(字典) parentPt - 標註的內容 nodeTxt - 結點名 Returns: 無 """ def plotTree(myTree, parentPt, nodeTxt): decisionNode = dict(boxstyle="sawtooth", fc="0.8") #設置結點格式 leafNode = dict(boxstyle="round4", fc="0.8") #設置葉結點格式 numLeafs = getNumLeafs(myTree) #獲取決策樹葉結點數目,決定了樹的寬度 depth = getTreeDepth(myTree) #獲取決策樹層數 firstStr = next(iter(myTree)) #下個字典 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.totalD #y偏移 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)) plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD """ 函數說明:建立繪製面板 Parameters: inTree - 決策樹(字典) Returns: 無 """ def createPlot(inTree): fig = plt.figure(1, facecolor='white') #建立fig fig.clf() #清空fig axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #去掉x、y軸 plotTree.totalW = float(getNumLeafs(inTree)) #獲取決策樹葉結點數目 plotTree.totalD = float(getTreeDepth(inTree)) #獲取決策樹層數 plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; #x偏移 plotTree(inTree, (0.5,1.0), '') #繪製決策樹 plt.show() #顯示繪製結果
8)執行決策樹windows
依靠訓練數據構造好決策樹以後能夠用於實際數據分類。app
""" 函數說明:使用決策樹分類 Parameters: inputTree - 已經生成的決策樹 featLabels - 存儲選擇的最優特徵標籤 testVec - 測試數據列表,順序對應最優特徵標籤 Returns: classLabel - 分類結果 """ def classify(inputTree, featLabels, testVec): firstStr = next(iter(inputTree)) #獲取決策樹結點 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
9)決策樹存儲dom
能夠調用python模塊中的pickle序列化對象,這樣可以在每次執行時調用已經構造好的決策樹
""" 函數說明:存儲決策樹 Parameters: inputTree - 已經生成的決策樹 filename - 決策樹的存儲文件名 Returns: 無 """ def storeTree(inputTree, filename): with open(filename, 'wb') as fw: pickle.dump(inputTree, fw)
class sklearn.tree.DecisionTreeClassifier(criterion=’gini’, splitter=’best’, max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, presort=False)
參數介紹:
# -*- coding: UTF-8 -*- from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.externals.six import StringIO from sklearn import tree import pandas as pd import numpy as np import pydotplus if __name__ == '__main__': with open('lenses.txt', 'r') as fr: #加載文件 lenses = [inst.strip().split('\t') for inst in fr.readlines()] #處理文件 lenses_target = [] #提取每組數據的類別,保存在列表裏 for each in lenses: lenses_target.append(each[-1]) print(lenses_target) lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate'] #特徵標籤 lenses_list = [] #保存lenses數據的臨時列表 lenses_dict = {} #保存lenses數據的字典,用於生成pandas for each_label in lensesLabels: #提取信息,生成字典 for each in lenses: lenses_list.append(each[lensesLabels.index(each_label)]) lenses_dict[each_label] = lenses_list lenses_list = [] # print(lenses_dict) #打印字典信息 lenses_pd = pd.DataFrame(lenses_dict) #生成pandas.DataFrame # print(lenses_pd) #打印pandas.DataFrame le = LabelEncoder() #建立LabelEncoder()對象,用於序列化 for col in lenses_pd.columns: #序列化 lenses_pd[col] = le.fit_transform(lenses_pd[col]) # print(lenses_pd) #打印編碼信息 clf = tree.DecisionTreeClassifier(max_depth = 4) #建立DecisionTreeClassifier()類 clf = clf.fit(lenses_pd.values.tolist(), lenses_target) #使用數據,構建決策樹 dot_data = StringIO() tree.export_graphviz(clf, out_file = dot_data, #繪製決策樹 feature_names = lenses_pd.keys(), class_names = clf.classes_, filled=True, rounded=True, special_characters=True) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("tree.pdf") #保存繪製好的決策樹,以PDF的形式存儲。