当前位置: 首页 > 编程日记 > 正文

决策树(chap3)Machine Learning In Action学习笔记

优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据。
缺点:可能会产生过度匹配问题。
适用数据类型:数值型(必须离散化)和标称型。

决策树创建分支的伪代码函数createBranch():
检测数据集中的每个子项是否属于同一分类:
If so return 类标签;
Else
寻找划分数据集的最好特征
划分数据集
创建分支节点
for 每个划分的子集
调用函数createBranch并增加返回结果到分支节点中
return 分支节点

决策树的一般流程 
收集数据:可以使用任何方法。
准备数据:树构造算法只适用于标称型数据,因此数值型数据必须离散化
分析数据:可以使用任何方法,构造树完成之后,我们应该检查图形是否符合预期。
训练算法:构造树的数据结构。(ID3算法
测试算法:使用经验树计算错误率
使用算法:此步骤可以适用于任何监督学习算法,而使用决策树可以更好地理解数据的内在含义

划分数据集的大原则是:将无序的数据变得更加有序。
组织杂乱无章数据的一种方法就是使用信息论度量信息。
信息增益:划分数据集之前之后信息发生的变化。(计算每个特征值划分数据集获得的信息增益,获得信息增益最高的特征就是最好的选择。)
集合信息的度量方式称为香农熵或者简称为熵(信息的期望值熵越大则数据越无序。
待分类的事务可能划分在多个分类之中,则符号xi 的信息 (p(xi)是选择该分类的概率)
(信息的期望值):(n是分类的数目)

对每个特征划分数据集的结果计算一次信息熵,然后判断按照哪个特征划分数据集是最好的划分方式。

递归构建决策树:
工作原理如下:得到原始数据集,然后基于最好的属性值划分数据集,由于特征值可能多于两个,因此可能存在大于两个分支的数据集划分。第一次划分之后,数据将被向下传递到树分支的下一个节点,在这个节点上,我们可以再次划分数据。因此我们可以采用递归的原则处理数据集。
递归结束的条件是:程序遍历完所有划分数据集的属性,或者每个分支下的所有实例都具有相同的分类。如果所有实例具有相同的分类,则得到一个叶子节点或者终止块。任何到达叶子节点的数据必然属于叶子节点的分类。

构造决策树是很耗时的任务,即使处理很小的数据集,如前面的样本数据,也要花费几秒的时间,如果数据集很大,将会耗费很多计算时间。然而用创建好的决策树解决分类问题,则可以很快完成。因此,为了节省计算时间,最好能够在每次执行分类时调用已经构造好的决策树。为了解决这个问题,需要使用Python模块pickle序列化对象

本章代码:(略去画图部分,太繁琐了……)
  1. # -*- coding:utf-8 -*-
  2. from math import log
  3. from numpy import *
  4. import operator
  5. def createDataSet():
  6. dataSet = [[1, 1, 'yes'],
  7. [1, 1, 'yes'],
  8. [1, 0, 'no'],
  9. [0, 1, 'no'],
  10. [0, 1, 'no']]
  11. labels = ['no surfacing', 'flippers']
  12. # change to discrete values
  13. return dataSet, labels
  14. # 测量给定数据集的信息熵,度量数据的无序程度,熵越大则数据越无序。
  15. def calcShannonEnt(dataSet):
  16. numEntries = len(dataSet)
  17. labelCounts = {}
  18. for featVec in dataSet:
  19. currentLabel = featVec[-1]
  20. labelCounts[currentLabel] = labelCounts.get(currentLabel, 0) + 1
  21. shannonEnt = 0.0
  22. for key in labelCounts:
  23. prob = float(labelCounts[key]) / numEntries
  24. shannonEnt -= prob * log(prob, 2)
  25. return shannonEnt
  26. # 按照给定特征划分数据集(当我们按照某个特征划分数据集时,就需要将所有符合要求的元素抽取出来)
  27. # axis:用来划分数据集的特征(索引值), value:该特征选取的属性值(需要返回的值)
  28. def splitDataSet(dataSet, axis, value):
  29. retDataSet = []
  30. for featVec in dataSet:
  31. if featVec[axis] == value:
  32. reducedFeatVec = featVec[:]
  33. reducedFeatVec.remove(value)
  34. retDataSet.append(reducedFeatVec)
  35. return retDataSet
  36. # 选择最好的数据集划分方式
  37. def chooseBestFeatureToSplit(dataSet):
  38. numFeatures = len(dataSet[0]) - 1
  39. baseEntropy = calcShannonEnt(dataSet)
  40. bestInfoGain = 0.0
  41. bestFeature = -1
  42. for i in range(numFeatures):
  43. # 创建唯一的分类标签列表
  44. featList = [example[i] for example in dataSet]
  45. uniqueVals = set(featList)
  46. newEntropy = 0.0
  47. # 计算每种划分方式的信息熵
  48. for value in uniqueVals:
  49. subDataSet = splitDataSet(dataSet, i, value)
  50. prob = len(subDataSet) / float(len(dataSet))
  51. newEntropy += prob * calcShannonEnt(subDataSet)
  52. infoGain = baseEntropy - newEntropy
  53. # 计算最好的信息增益
  54. if infoGain > bestInfoGain:
  55. bestInfoGain = infoGain
  56. bestFeature = i
  57. return bestFeature
  58. def majorityCnt(classList):
  59. classCount = {}
  60. for vote in classList:
  61. classCount[vote] = classCount.get(vote, 0) + 1
  62. sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
  63. return sortedClassCount[0][0]
  64. def createTree(dataSet, labels):
  65. classList = [example[-1] for example in dataSet]
  66. # 两个结束条件:类别完全相同或者遍历完所有特征
  67. if len(set(classList)) == 1:
  68. return classList[0]
  69. if len(dataSet[0]) == 1:
  70. return majorityCnt(classList)
  71. bestFeat = chooseBestFeatureToSplit(dataSet)
  72. bestFeatLabel = labels[bestFeat]
  73. myTree = {bestFeatLabel: {}}
  74. del(labels[bestFeat])
  75. featValues = [example[bestFeat] for example in dataSet]
  76. uniqueVals = set(featValues)
  77. for value in uniqueVals:
  78. subLabels = labels[:]
  79. myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
  80. return myTree
  81. def classify(inputTree, featLabels, testVec):
  82. firstStr = inputTree.keys()[0]
  83. secondDict = inputTree[firstStr]
  84. featIndex = featLabels.index(firstStr)
  85. for key in secondDict.keys():
  86. if testVec[featIndex] == key:
  87. if type(secondDict[key]).__name__ == 'dict':
  88. classLabel = classify(secondDict[key], featLabels, testVec)
  89. else:
  90. classLabel = secondDict[key]
  91. return classLabel
  92. # 使用pickle模块存储决策树
  93. def storeTree(inputTree, filename):
  94. import pickle
  95. fw = open(filename, 'w')
  96. pickle.dump(inputTree, fw)
  97. fw.close()
  98. def grabTree(filename):
  99. import pickle
  100. fr = open(filename)
  101. return pickle.load(fr)

参考资料:
1. Peter Harrington《机器学习实战》第三章


来自为知笔记(Wiz)


转载于:https://www.cnblogs.com/woaielf/p/5511164.html

相关文章:

BigdCIMAL类型数据的使用选择

现在常用的数值类型有Integer , Double , Float , BigDecimal几种 , 常用的当然要数前两种 了 , Integer代表的是整数类型的数据 , double则是代表的是浮点型 , 双精度 ,double的计算精度相对于float来讲要 高 , BigDecimal的计算精度则是最高的 . 可是BigDecimal的一些计算方…

数字字符串转化为时间字符串

(NSString *)dateStringFromNumberTimer:(NSString *)timerStr {//转化为Doubledouble t [timerStr doubleValue];//计算出距离1970的NSDateNSDate *date [NSDate dateWithTimeIntervalSince1970:t];//转化为 时间格式化字符串NSDateFormatter *df [[NSDateFormatter alloc]…

git 覆盖本地修改_Git拉力–如何使用Git覆盖本地更改

git 覆盖本地修改When you learn to code, sooner or later youll also learn about Version Control Systems. And while there are many competing tools in this space, one of them is the de facto standard used by almost everyone in the industry. Its so popular tha…

云计算大会记录

一、要点及主要技术内容记录消费金融刘志军 马上消费大额 分散 小额 短期OpenStack OpenStack是一个由NASA(美国国家航空航天局)和Rackspace合作研发并发起的,以Apache许可证授权的自由软件和开放源代码项目。 OpenStack是一个开源的云计算管…

获取iOS版本号

(double)getCurrentIOS {return [[[UIDevice currentDevice] systemVersion] doubleValue];}

spring boot 服务 正确关闭方式

引言 Spring Boot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行、产品级别的基于Spring框架的应用,大部分Spring Boot应用只需要非常少的配置就可以快速运行…

如何在5美元的Raspberry Pi上构建个人开发服务器

In this article, youll learn how to build a personal dev server by installing Git, Node.js, Rust, and Docker on a Raspberry Pi. The cheapest option costs just $5. You can get a starter kit ($25) for free here.在本文中,您将学习如何通过在Raspberry…

Eclipse:xml文件中添加.xsd约束文件

今天在使用dubbo的时候,XML文件一直报错。找不到dubbo的xsd约束文件。 cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element dubbo:reference 解决方法: 找到dubbo的jar包,然后在META-…

029 浏览器不能访问虚拟机的问题解决

1.在搭建分布式时 ssh一直不能进行scp,后来发现一个问题。 windows中的hosts配置了三台虚拟机的映射,但是在虚拟机中的hosts没有配置。 做法是在每台虚拟机上都配置三台虚拟机的映射。 2.端口访问与防火墙 最近帮别人解决问题时才注意的。 以前安装好虚拟…

获取 一个文件 在沙盒Library/Caches/ 目录下的路径

(NSString *)getFullPathWithFile:(NSString *)urlName {//先获取 沙盒中的Library/Caches/路径NSString *docPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *myCacheDirectory [docPath stringByAppendingPat…

如何有效使用每一点脑力总结_如何更有效地节省脑力和编码

如何有效使用每一点脑力总结如果您知道这些工具的存在,那么您现在可能会使用它们。 (If you knew these tools existed, youd probably be using them by now.) This article isn’t going to tell you about saving your neck with a Roost stand, or your wrists …

C语言程序设计50例(一)(经典收藏)

【程序1】题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去      掉不满足条件的排列。 1 #include…

python多线程执行类中的静态方法

在python 中如果通过多线程的方式执行某个方法很简单,只需要把同步函数的第一个参数为该函数对象即可。但是如果函数对象是某个类的静态方法,这时候如果直接使用类的该函数对象会报错。此时需要构造一个代理的方法来实现。 如:上一个博文中的…

检测缓存文件是否超时

(BOOL)isTimeOutWithFile:(NSString *)filePath timeOut:(double)timeOut {//获取文件的属性NSDictionary *fileDict [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];//获取文件的上次的修改时间NSDate *lastModfyDate fileDict.fileModificat…

JavaScript创建对象–如何在JS中定义对象

Objects are the main unit of encapsulation in Object-Oriented Programming. In this article, I will describe several ways to build objects in JavaScript. They are:对象是面向对象编程中封装的主要单元。 在本文中,我将介绍几种使用JavaScript构建对象的方…

MyBatis中#{}和${}的区别

------------------------siwuxie095 MyBatis 中 #{} 和 ${} 的区别 1、在 MyBatis 的映射配置文件中,动态传递参数有两种方式: (1)#{} 占位符 (2)${} 拼接符 2、#{} 和 ${} 的区别 (1&#xff…

十进制字符串转十六进制字符串

NSString *colorStr[self.model.sclass_color substringFromIndex:1]; unsigned long cor strtoul([colorStr UTF8String],0,16);

gi克隆github文件_如何构建GitHub文件搜索功能的克隆

gi克隆github文件In this article, we will build a project that mimics the lesser known but awesome file search functionality provided by GitHub.在本文中,我们将构建一个项目,该项目模仿GitHub提供的鲜为人知但功能强大的文件搜索功能。 To se…

ipython --pandas

d定义: pandas是一个强大的Python数据分析的工具包。 pandas是基于NumPy构建的。 安装方法: pip install pandas import pandas as pd pandas的主要功能 具备对其功能的数据结构DataFrame、Series 集成时间序列功能 提供丰富的数学运算和操作 灵活处理缺失数据 Series 定义:Ser…

玩转Android之二维码生成与识别

二维码,我们也称作QRCode,QR表示quick response即快速响应,在很多App中我们都能见到二维码的身影,最常见的莫过于微信了。那么今天我们就来看看怎么样在我们自己的App中集成二维码的扫描与生成功能。OK,废话不多说&…

属性字符串(富文本)的使用

改变字符串中某些字符串字体的颜色 NSMutableAttributedString *attrStr[[NSMutableAttributedString alloc] initWithString:str]; [attrStr addAttribute:NSForegroundColorAttributeName value:kUIColorFromRGB(0xb2151c) range:[str rangeOfString:[NSString stringWith…

如何使用create-react-app在本地设置HTTPS

Running HTTPS in development is helpful when you need to consume an API that is also serving requests via HTTPS. 当您需要使用同时通过HTTPS服务请求的API时,在开发中运行HTTPS会很有帮助。 In this article, we will be setting up HTTPS in development …

Swift强制解析

IDE:Xcode Version7.3.1 Swift中"数据类型?"表示这是可选类型,即 某个常量或者变量可能是一个类型,也可能什么都没有,不确定它是否有值,也许会是nil。 比如: let num1 “123” let num2 Int(number1) pri…

rfc6455 WebSockets

https://tools.ietf.org/html/rfc6455 转载于:https://www.cnblogs.com/cheungxiongwei/p/8385719.html

2020-mb面试指南_2020年最佳代码面试准备平台

2020-mb面试指南Software developer interviews are rapidly evolving. Years ago, mastering data structures and common algorithms was enough to ace an interview and get a job. Today though, employers want candidates with real-world experience and skills. 软件开…

设计模式学习笔记(一)之工厂模式、单例模式

一、工厂模式 (1)简单工厂模式: 1 public interface IProduct { 2 3 public void saleProduct(); 4 5 } 创建一个产品接口,有一个卖产品的方法。 1 public class ProductA implements IProduct{ 2 3 public void saleProduct(){ 4 Sy…

iOS使用支付宝支付步骤

开发平台 (http://open.alipay.com/index.htm(这个里面找不到sdk) 需要进入下面的链接) 使用支付宝进行一个完整的支付功能,大致有以下步骤: 1>先与支付宝签约,获得商户ID(partner)和账号ID&#xff08…

heroku_了解如何使用Heroku部署全栈Web应用程序

herokuBuilding a full stack web app is no mean feat. Learning to deploy one to production so that you can share it with the world can add an additional layer of complexity.构建全栈式Web应用程序绝非易事。 学习将其部署到生产环境中,以便您可以与世界…

SpringMVC学习手册(三)------EL和JSTL(上)

1.含义 EL: Expression Language , 表达式语言JSTL: Java Server Pages Standard Tag Library, JSP标准标签库 2.测试项目构建 2.1 复制JSTL的标准实现 复制Tomcat中webapps\examples\WEB-INF\lib下的两个jar包到新建项目目录的WEB-INF\lib下2.2 在JSP文件中使用tagli…

OpenStack Heat模板详解

Heat模板全称为heat orchestration template,简称为HOT。 1 典型Heat模板结构 heat_template_version: 2015-04-30 description:# a description of the template parameter_groups:# a declaration of input parameter groups and order parameters:# declaration …