【读书笔记】机器学习实战-第三章 决策树
2017-05-07 17:04
477 查看
机器学习实战
决策树-隐形眼镜类型trees.py
#!/usr/bin/python # -*- coding: utf-8 -*- from math import log import operator import treePlotter def calcShannonEnt(dataSet): # 计算集合熵 numEntires = len(dataSet) labelCounts = {} for featVec in dataSet: # 统计频率 currentLabel = featVec[-1] labelCounts[currentLabel] = labelCounts.get(currentLabel,0)+1 # dic.get()函数,访问不存在的键时,自动插入并设为默认值 shannonEnt = 0.0 for key in labelCounts.keys(): # 遍历字典,计算熵 prob = float(labelCounts[key])/numEntires shannonEnt -= prob * log(prob, 2) # log函数 return shannonEnt def createDataSet(): # 测试数据 dataSet = [[1,1,'yes'], [1,1,'yes'], [1,0,'no'], [0,1,'no'], [0,1,'no']] labels = ['no surfacing','flippers'] # flippers: 脚蹼 return dataSet, labels def splitDataSet(dataSet, axis, value): # 返回第axis特征值为value的列表 retDataSet = [] # 新对象,防止传入参数被修改 for featVec in dataSet: # 寻找符合要求的值,添加到新列表中 if featVec[axis] == value: reduceFeatVec = featVec[:axis] # 除去第axis特征 reduceFeatVec.extend(featVec[axis+1:]) # extend :在列表末尾一次性添加另一个序列的多个值 retDataSet.append(reduceFeatVec) # 列表末尾添加源元素 return retDataSet def chooseBestFeatureToSplit(dataSet): numFeatures f4d3 = len(dataSet[0])-1 # 特征个数 baseEntropy = calcShannonEnt(dataSet) # 计算原始集合熵 bestInfoGain = 0.0 ;bestFeature = -1; # 最优解记录 for i in range(numFeatures): featList = [example[i] for example in dataSet] # 列表推导式 uniqueVals = set(featList) # 获取特征值取值范围 newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) # 获取被划分集合 prob = len(subDataSet)/float(len(dataSet)) # 计算划分集合所占比例 newEntropy += prob*calcShannonEnt(subDataSet) # 计算熵 infoGain = baseEntropy - newEntropy # 计算信息增益 if ( infoGain>bestInfoGain ): bestInfoGain = infoGain bestFeature = i return bestFeature def majoryCnt(classList): # 终止块的分类:多数表决 输入:类列表 classCount = {} for vote in classList: classCount[vote] =classCount.get(vote, 0) + 1 sortedClassCount = sorted(classCount.iteritems(), key = operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] def createTree(dataSet, labels): classList = [example[-1] for example in dataSet] # 列表推导式:获取包含的所有类别 if classList.count(classList[0]) == len(classList): # [].count():统计函数 return classList[0] # 叶子节点 if len(dataSet[0]) == 1: return majoryCnt(classList) # 终止块 bestFeat = chooseBestFeatureToSplit(dataSet) # 确定分类特征 bestFeatLabel = labels[bestFeat] 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 def classify(inputTree,featLabels,testVec): # 使用决策树决策 firstStr = inputTree.keys()[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) # index: 获取当前特征的编号 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) fr = open('lenses.txt') lenses = [sample.strip().split('\t') for sample in fr.readlines()] # 列表推导式 lensesLabels = ['age','prescript','astigmatic','tearRate'] # 特征 lensesTree = createTree(lenses,lensesLabels) # 建树 treePlotter.createPlot(lensesTree) # 作图 #myDat, labels = createDataSet() #tmp = createTree(myDat,labels) #tmp = chooseBestFeatureToSplit(myDat) #splitDataSet(myDat,0,0) #tmp = calcShannonEnt(myDat) #pass
treePlotter.py
#!/usr/bin/python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt # 定义文本框和箭头格式 decisionNode = dict(boxstyle="sawtooth", fc="0.8") leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") 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 createPlot(): fig = plt.figure(1, facecolor= 'white') fig.clf() createPlot.ax1 = plt.subplot(111,frameon=False) # 函数属性 可以在函数里面定义也可以在函数定义后加入也可以 plotNode('decision node',(0.5,0.1),(0.1,0.5),decisionNode) plotNode('leaf node',(0.8,0.1),(0.3,0.8),leafNode) plt.show() def getNumLeafs(myTree): numLeafs = 0 firstStr = 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 nodes numLeafs += getNumLeafs(secondDict[key]) else: numLeafs +=1 return numLeafs def getTreeDepth(myTree): maxDepth = 0 firstStr = 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 nodes thisDepth = 1 + getTreeDepth(secondDict[key]) else: thisDepth = 1 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth def retrieveTree(i): listOfTrees =[{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}, {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}} ] return listOfTrees[i] 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 plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on numLeafs = getNumLeafs(myTree) #this determines the x width of this tree depth = getTreeDepth(myTree) firstStr = myTree.keys()[0] #the text label for this node should be this 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 for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes plotTree(secondDict[key],cntrPt,str(key)) #recursion else: #it's a leaf node print the leaf node 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 def createPlot(inTree): 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 puropses 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() #createPlot()
相关文章推荐
- 《机器学习实战》读书笔记 第三章 决策树(part 1)
- 《机器学习实战》读书笔记 第三章 决策树(part 2)
- 《机器学习实战》读书笔记 第三章 决策树(part 3)
- 机器学习实战-第三章决策树-代码理解-读书笔记
- 《机器学习实战》第三章:决策树(1)基本概念
- 机器学习实战 第三章 决策树 学习笔记
- Python《机器学习实战》读书笔记(三)——决策树
- 《机器学习实战》第三章 决策树
- [完]机器学习实战 第三章 决策树(Decision Tree)
- 《机器学习实战》第三章:决策树(2)树的构造
- 《机器学习实战》第三章 3.1 决策树的构造
- 【2】机器学习实战 第三章 决策树的构造
- 【读书笔记】机器学习实战 第7章 基于单层决策树的adaboost
- 《机器学习实战》第三章:决策树(3)测试、存储、实例
- 机器学习实战第三章——决策树,读书笔记
- 读书笔记_第三章
- 《Javascript编程精解》读书笔记-第三章 数据结构:对象与数组
- python cook book第三版 读书笔记3(第三章)
- 读书笔记--《Python基础教程第二版》-- 第三章 使用字符串
- 《程序员的自我修养——链接、装在与库》第三章《目标文件里有什么》读书笔记