前一天,我们基于sklearn科学库实现了ID3的决策树程序,本文将基于python自带库实现ID3决策树算法。
一、代码涉及基本知识
1、 为了绘图方便,引入了一个第三方treePlotter模块进行图形绘制。该模块使用方法简单,调用模块createPlot接口,传入一个树型结构对象,即可绘制出相应图像。
2、 在python中,如何定义一个树型结构对象
可以使用了python自带的字典数据类型来定义一个树型对象。例如下面代码,我们定义一个根节点和两个左右子节点:
rootNode = {'rootNode': {}}
leftNode= {'leftNode': {'yes':'yes'}}
rightNode= {'rightNode': {'no':'no'}}
rootNode['rootNode']['left'] =leftNode
rootNode['rootNode']['right'] =rightNode
treePlotter.createPlot(rootNode)
通过调用treePlotter模块,绘制出如下树的图像
2、 递归调用
为了求每个节点的各个子节点,要用到递归的方法来实现,基本思想和二叉树的遍历方法一致,后面我们还会用Python实现一个二叉树源码,此处不再进行介绍。
3、 此外,还需要对python常用的数据类型及其操作比较了解,例如字典、列表、集合等
二、程序主要流程
三、测试数据集
age
income
student
credit_rating
class_buys_computer
youth
high
no
fair
no
youth
high
no
excellent
no
middle_aged
high
no
fair
yes
senior
medium
no
fair
yes
senior
low
yes
fair
yes
senior
low
yes
excellent
no
middle_aged
low
yes
excellent
yes
youth
medium
no
fair
no
youth
low
yes
fair
yes
senior
medium
yes
fair
yes
youth
medium
yes
excellent
yes
middle_aged
medium
no
excellent
yes
middle_aged
high
yes
fair
yes
senior
medium
no
excellent
no
四、程序代码
1、计算测试集熵及信息增益
#求最优的根节点
defchooseBestFeatureToSplit(datase