标签:

本节讲解如何预测患者需要佩戴的隐形眼镜类型。

1、使用决策树预测隐形眼镜类型的一般流程

(1)收集数据:提供的文本文件(数据来源于UCI数据库)

(2)准备数据:解析tab键分隔的数据行

(3)分析数据:快速检查数据,确保正确地解析数据内容,使用createPlot()函数绘制最终的树形图

(4)训练算法:createTree()函数

(5)测试算法:编写测试函数验证决策树可以正确分类给定的数据实例

(6)使用算法:存储数的数据结构,以使下次使用时无需重新构造树

trees.py如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

from math import log

#计算给定数据集的香农熵

def calcShannonEnt(dataSet):

numEntries=len(dataSet)

labelCounts={}

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:

prob=float(labelCounts[key])/numEntries

shannonEnt -=prob*log(prob,2)

return shannonEnt

#按照给定特征划分数据集

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

#选择最好的数据集划分方式

def chooseBestFeatureToSplit(dataSet):

numFeatures=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 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]

#创建树的函数代码

def createTree(dataSet,labels):

classList=[example[-1] for example in dataSet]

if classList.count(classList[0])==len(classList): #类别完全相同规则停止继续划分

return classList[0]

if len(dataSet[0])==1: return majorityCnt(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)

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

#使用算法:决策树的存储

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)

treePlotter.py如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt

from numpy import *

import operator

#定义文本框和箭头格式

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(U‘决策节点‘,(0.5,0.1),(0.1,0.5),decisionNode)

plotNode(U‘叶节点‘,(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‘:

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‘:

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)

#计算宽和高

def plotTree(myTree,parentPt,nodeTxt):

numLeafs=getNumLeafs(myTree)

depth=getTreeDepth(myTree)

firstStr=myTree.keys()[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]

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))

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)

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()

lenses.txt如下:

运行如下:

1 >>> importtrees2 >>> importtreePlotter3 >>> fr=open(‘lenses.txt‘)4 >>> lenses=[inst.strip().split(‘\t‘) for inst infr.readlines()]5 >>> lensesLabels=[‘age‘,‘prescript‘,‘astigmatic‘,‘tearRate‘]6 >>> lensesTree=trees.createTree(lenses,lensesLabels)7 >>>lensesTree8 {‘tearRate‘: {‘reduced‘: ‘no lenses‘, ‘normal‘: {‘astigmatic‘: {‘yes‘: {‘prescript‘: {‘hyper‘: {‘age‘: {‘pre‘: ‘no lenses‘, ‘presbyopic‘: ‘no lenses‘, ‘young‘: ‘hard‘}}, ‘myope‘: ‘hard‘}}, ‘no‘: {‘age‘: {‘pre‘: ‘soft‘, ‘presbyopic‘: {‘prescript‘: {‘hyper‘: ‘soft‘, ‘myope‘: ‘no lenses‘}}, ‘young‘: ‘soft‘}}}}}}9 >>> treePlotter.createPlot(lensesTree)

由图看出决策树非常好地匹配了实验数据,然而这些匹配选项可能太多。我们将这种问题称之为过度匹配(overfitting)。为了减少过度匹配问题,我们可以裁剪决策树,去掉一些不必要的叶子节点。如果叶子节点只能增加少许信息,则可以删除该节点,将它并入到其他叶子节点中。

标签:

python决策树id3算法_决策树ID3算法预测隐形眼睛类型--python实现相关推荐

  1. 【Matlab】智能优化算法_蜻蜓优化算法DA

    [Matlab]智能优化算法_蜻蜓优化算法DA 1.背景介绍 2.灵感 3.公式推导 3.1 勘探和开发操作 4.算法流程图 5.文件结构 6.伪代码 7.详细代码及注释 7.1 DA.m 7.2 d ...

  2. 【Matlab】智能优化算法_蚁狮优化算法ALO

    [Matlab]智能优化算法_蚁狮优化算法ALO 1.背景介绍 2.基本思想 3.公式推导 3.1 ALO算法的运算符 3.2 蚂蚁的随机游动 3.3 困在蚂蚁坑里 3.4 修建陷阱 3.5 蚂蚁划向 ...

  3. 【Matlab】智能优化算法_灰狼优化算法GWO

    [Matlab]智能优化算法_灰狼优化算法GWO 1.背景介绍 2.基本思想 2.1 等级制度 2.2 狩猎方式 3.公式推导 3.1 社会等级制度 3.2 包围猎物 3.3 包围猎物 3.4 攻击猎 ...

  4. cart算法_决策树学习笔记(三):CART算法,决策树总结

    点击上方"Python数据科学",选择"星标公众号" 关键时刻,第一时间送达! 作者:xiaoyu 介绍:一个半路转行的数据挖掘工程师 推荐导读:本篇为树模型系 ...

  5. r语言 C4.5 剪枝是用什么算法_决策树,逻辑回归,PCA算法面经

    目录 决策树 简述决策树原理? 为什么要对决策树进行减枝?如何进行减枝? 简述决策树的生成策略 PCA 简述主成分分析PCA工作原理,以及PCA的优缺点? PCA中有第一主成分.第二主成分,它们分别是 ...

  6. python决策树逻辑回归_决策树,逻辑回归,PCA-算法面试题

    决策树 简述决策树原理? 决策树是一种自上而下,对样本数据进行树形分类的过程,由节点和有向边组成.节点分为内部节点和叶节点,其中每个内部节点表示一个特征或属性,叶节点表示类别.从顶部节点开始,所有样本 ...

  7. python二分查找时间复杂度_二分查找算法的时间复杂度计算(logN)

    二分查找算法的时间复杂度计算(logN) 马富天 2019-08-10 20:25:24 54 [摘要]二分查找算法是对顺序查找算法的优化,二分查找算法的前提是数列是一个有序数列,递增或者递减,本文就 ...

  8. python实现洗牌算法_洗牌算法及 random 中 shuffle 方法和 sample 方法浅析

    对于算法书买了一本又一本却没一本读完超过 10%,Leetcode 刷题从来没坚持超过 3 天的我来说,算法能力真的是渣渣.但是,今天决定写一篇跟算法有关的文章.起因是读了吴师兄的文章 <扫雷与 ...

  9. python 查找算法_七大查找算法(Python)

    查找算法 -- 简介 查找(Searching)就是根据给定的某个值,在查找表中确定一个其关键字等于给定值的数据元素. 查找表(Search Table):由同一类型的数据元素构成的集合 关键字(Ke ...

最新文章

  1. python主成分分析相关系数_python如何进行主成分分析
  2. centos 禁用root登录
  3. 【C++ 学习笔记】 MFC CEdit
  4. raise JSONDecodeError(“Expecting value“, s, err.value) from None
  5. 简单的Jquery焦点图切换效果
  6. String replaceAll()
  7. 昆仑通态复制的程序可以用吗_第478期丨相同功能带定时器的PLC程序怎么简化?非标设备出口到日本,应该怎么配电。...
  8. 棉猴论坛VIP之驱动基础系列教程 视频教程
  9. NM3000多用表校验仪
  10. 起点中文网字体反爬注意事项
  11. 理解opencv读取图片后的格式,理解图片矩阵的储存方式
  12. ZOJ-3939 The Lucky Week
  13. 试述Linux内核启动过程,Linux内核启动过程和Bootloader(总述)
  14. 连接重置Connection reset异常
  15. 2021-08-18 关于PC与ipad的远程控制
  16. 16、什么是拟牛顿法(Quasi-Newton Methods)?
  17. 服务器群发消息,群发消息怎么发
  18. JAVA泛型尖括号中的 T 和 ? 有什么区别?
  19. Codeforces E. Game With String
  20. 木马伪装“刷单任务” 劫持QQ语音暗中盗号

热门文章

  1. ABAP GUI Text Edit
  2. Database specific hint in One order search
  3. where is document CURRENCY field stored
  4. 部署在SAP ABAP服务器上的SAP UI5应用的JavaScript文件,是如何被SAP UI5 repository handler处理的
  5. SAP Cloud for Customer Account和individual customer的区别
  6. win10蓝牙开关不见了_Win8系统电脑蓝牙图标不见了的解决方法
  7. 使用回溯法解决编辑距离问题(C语言)
  8. 画箱线图_箱线图的N种画法
  9. on duplicate key update不生效_为什么不把蚊子吸血原理应用于医院化验抽血?
  10. 东南大学计算机学院方效林,方效林