一、 决策树简介
决策树是一种特殊的树形结构,一般由节点和有向边组成。其中,节点表示特征、属性或者一个类。而有向边包含有判断条件。如图所示,决策树从根节点开始延伸,经过不同的判断条件后,到达不同的子节点。而上层子节点又可以作为父节点被进一步划分为下层子节点。一般情况下,我们从根节点输入数据,经过多次判断后,这些数据就会被分为不同的类别。这就构成了一颗简单的分类决策树。
二、 相关知识
请参考周志华《机器学习》第4章:决策树
注意,第75页有一行内容:信息熵的值越小,则样本集合的纯度越高。
这怎么理解呢?可举几个例子来帮助理解
例1:
p1 = 1, p2 = 0, 则Ent(D) = - (1 * log1 + 0 * log0) = 0
这表示样本集合里只有一种样本。纯度最高。
例2:
p1 = p2 = 0.5,则Ent(D) = - (0.5 * log0.5 + 0.5 * log0.5) = - (-0.5 - 0.5) = 1
样本集合中有两种样本,每种样本的纯度都是50%
例3:
p1 = 0.5, p2 = p3 = 0.25,则Ent(D) = -(0.5 * log0.5 + 0.25 * log0.25 + 0.25 * log0.25) = -(-0.5 - 0.5 - 0.5) = 1.5
例4:
p1 = p2 = p3 = p4 = 0.25,则Ent(D) = 2
例5:
p1 = p2 = p3 = p4 = 1/1024,则Ent(D) = 10
通过上面几个可以看出来,熵值越小,纯度越高,熵值越大,纯度越低。纯度范围为[0, log|y|]
三、 数据集
为了更好地理解程序,咱们只采用15行数据来实现决策树二分类。这些数据中,前6行是特征属性,最后一行是分类结果。
对于上面的十五行数据,咱们可以把前1/3(即前5行)数据做为测试集,把后2/3(即后10行)数据作为训练集。
注意:这里是为了好理解,划分成前1/3和后2/3,更好的做法是随机挑选一部分作为测试集,剩余的部分作为训练集。
四、 算法思路
可直接查看周志华《机器学习》中的思路
五、 实现过程
(一)利用信息熵和信息增益
信息熵越小越好,信息增益越大越好。
信息熵的公式为:
对于各属性,信息增益的公式为:
因为D都是一样的,程序中可以省略掉D。用信息增益最大的属性作为节点划分,即要也上式最大,也即要求下式最小:
实现代码:
(二)划分属性
训练集的数据(后10行)为
根据上面的代码,计算出的各属性的信息增益分别为:
上述中最后一个值0.4最小,所以取该值所对应的第5列(从0开始计数)属性作为根结点。
用第5列属性进行划分,属性0对应着分类0,属性1对应着分类0,属性2对应着分类0和1,此时树的结构是这样的:
第二个属性如何计算呢?
找出第5列属性的值为2所对应的类别。再找出这些类别对应的各列属性值(不包含第5列属性),得
这里前五列表示属性0,1,2,3,4;最后一列表示分类。
计算出的各属性的信息增益分别为:
则取第3个属性来划分。第3个属性取值为2时,分类为0;取值为4时,分类为1。
此时的决策树为
(三)预测结果
需要预测的五条数据为
2,2,2,4,0,2,1
2,2,2,2,0,1,0
2,2,2,2,0,2,0
2,2,2,2,1,0,0
2,2,2,2,1,1,0
前六列是特征属性,最后一列是实际结果,用来和预测结果做比较。
第一条数据,第5个属性值是2,需要再判断第3个属性,第3个属性的值为4,根据决策树得出的预测分类为1,与实际结果吻合
第二条数据,第5个属性值是1,根据决策树得出的预测分类为0,与实际结果吻合
第三条数据,第5个属性值是2,需要再判断第3个属性,第3个属性的值为2,根据决策树得出的预测分类为0,与实际结果吻合
第四条数据,第5个属性值是0,根据决策树得出的预测分类为0,与实际结果吻合
第五条数据,第5个属性值是1,根据决策树得出的预测分类为0,与实际结果吻合
六、 完整代码
(1)DecisionTree.py
(2)Main.py
运行结果:
机器学习交流QQ群:658291732TopCoder & Codeforces & AtCoder交流QQ群:648202993更多内容请关注微信公众号