ML2

Decision Tree

A. Information Gain - Shannon Entropy

Given a discrete random variable $X$, with possible outcomes $x_{1},x_{2},…,x_{n}$, which occur with probability $P(x_{1}),P(x_{2}),…,P(x_{n})$, the entropy of X is formally defined as:
$H(X) = -\sum_{i=1}^{N} P(x_{i})log_{2}P(x_{i})$

B. ID3 algorithm

  1. Calculate the entropy of every attribute $\alpha$ of the data set $S$.
  2. Partition (“split”) the set $S$ into subsets using the attribute for which the resulting entropy after splitting is minimized; or, equivalently, information gain is maximum.
  3. Make a decision tree node containing that attribute.
  4. Recurse on subsets using the remaining attributes.
  5. 核心思想就是以信息增益来度量属性的选择,选择分裂后信息增益最大的属性进行分裂。该算法采用自顶向下的贪婪搜索遍历可能的决策空间。

Pseudocode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ID3 (Examples, Target_Attribute, Attributes)
Create a root node for the tree
If all examples are positive, Return the single-node tree Root, with label = +.
If all examples are negative, Return the single-node tree Root, with label = -.
If number of predicting attributes is empty, then Return the single node tree Root,
with label = most common value of the target attribute in the examples.
Otherwise Begin
A ← The Attribute that best classifies examples.
Decision Tree attribute for Root = A.
For each possible value, vi, of A,
Add a new tree branch below Root, corresponding to the test A = vi.
Let Examples(vi) be the subset of examples that have the value vi for A
If Examples(vi) is empty
Then below this new branch add a leaf node with label = most common target value in the examples
Else below this new branch add the subtree ID3 (Examples(vi), Target_Attribute, Attributes – {A})
End
Return Root
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 20:07:48 2020

@author: chen
"""

from math import log

"""
函数说明:创建测试数据集

Parameters:
None

Returns:
dataSet - 数据集
labels - 分类属性
"""
def createDataSet():
# 数据集
dataSet = [[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']]
# 分类属性
labels = ['no surfacing', 'flippers']
# 返回数据集和分类属性
return dataSet, labels

划分数据集(引入信息熵的概念)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
函数说明:计算数据集的经验熵(香农熵)
Ent(D) = -SUM{_i}(p(xi)*Log2(p(xi)))

Parameters:
dataSet - 数据集

Returns:
shannonEnt - 经验熵(香农熵)
"""
def calcShannonEnt(dataSet):
# 返回样本总量
numEntires = len(dataSet)
# 生成字典{label:次数}
labelCounts = {}
# 遍历dataSet统计
for featVec in dataSet:
# 提取label信息
currentLabel = featVec[-1]
# 如果label没有放入统计次数的字典,添加进去
if currentLabel not in labelCounts.keys():
# 创建一个新的键值对,键为currentLabel值为0
labelCounts[currentLabel] = 0
# Label计数
labelCounts[currentLabel] += 1
# 经验熵(香农熵)
shannonEnt = 0.0
# 计算香农熵
for key in labelCounts:
# 选择该标签(Label)的概率
prob = float(labelCounts[key]) / numEntires
# 利用公式计算
shannonEnt -= prob*log(prob, 2)
# 返回经验熵(香农熵)
return shannonEnt

划分数据集(根据指定特征)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""
函数说明:按照给定特征划分数据集

Parameters:
dataSet - 待划分的数据集
axis - 划分数据集的特征
values - 需要返回的特征的值

Returns:
None

"""
def splitDataSet(dataSet, axis, value):
# 创建新的数据集对象
retDataSet = []
# 遍历数据集
for featVec in dataSet:
if featVec[axis] == value:
# 返回去掉axis特征的数据
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
# 嵌套产生新的数据集
retDataSet.append(reducedFeatVec)
# 返回划分后的数据集
return retDataSet

选择信息增益最大的特征划分数据集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
函数说明:选择最优特征
Gain(D,g) = Ent(D) - SUM(|Dv|/|D|)*Ent(Dv)

Parameters:
dataSet - 数据集

Returns:
bestFeature - 信息增益最大的(最优)特征的索引值
"""
def chooseBestFeatureToSplit(dataSet):
# 特征数量
numFeatures = len(dataSet[0]) - 1
# 计算数据集的香农熵
baseEntropy = calcShannonEnt(dataSet)
# 信息增益
bestInfoGain = 0.0
# 最优特征的索引值
bestFeature = -1
# 遍历所有特征
for i in range(numFeatures):
# 获取dataSet的第i个所有特征存在featList这个列表中(列表生成式)
featList = [example[i] for example in dataSet]
# 创建set集合{},元素不可重复,重复的元素均被删掉
# 从列表中创建集合是python语言得到列表中唯一元素值的最快方法
uniqueVals = set(featList)
# 经验条件熵
newEntropy = 0.0
# 计算信息增益
for value in uniqueVals:
# subDataSet划分后的子集
subDataSet = splitDataSet(dataSet, i, value)
# 计算子集的概率
prob = len(subDataSet) / float(len(dataSet))
# 根据公式计算经验条件熵
newEntropy += prob * calcShannonEnt(subDataSet)
# 信息增益
infoGain = baseEntropy - newEntropy
# 打印每个特征的信息增益
print("第%d个特征的增益为%.3f" % (i, infoGain))
# 计算信息增益
if(infoGain > bestInfoGain):
# 更新信息增益,找到最大的信息增益
bestInfoGain = infoGain
# 记录信息增益最大的特征的索引值
bestFeature = i
# 返回信息增益最大的特征的索引值
return bestFeature

创建叶子节点(多数表决原则)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
函数说明:统计classList中出现次数最多的元素(类标签)
服务于递归第两个终止条件

Parameters:
classList - 类标签列表

Returns:
sortedClassCount[0][0] - 出现次数最多的元素(类标签)
"""
def majorityCnt(classList):
classCount = {}
# 统计classList中每个元素出现的次数
for vote in classList:
if vote not in classCount.keys():
classCount[vote] = 0
classCount[vote] += 1
# 根据字典的值降序排序
# operator.itemgetter(1)获取对象的第1列的值
sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)
# 返回classList中出现次数最多的元素
return sortedClassCount[0][0]

决策树是一种依托决策而建立起来的一种树。在机器学习中,决策树是一种预测模型,代表的是一种对象属性与对象值之间的一种映射关系,每一个节点代表某个对象,树中的每一个分叉路径代表某个可能的属性值,而每一个叶子节点则对应从根节点到该叶子节点所经历的路径所表示的对象的值。决策树仅有单一输出。

递归获得决策树(ID3算法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
函数说明:创建决策树(ID3算法)
递归有两个终止条件:1、所有的类标签完全相同,直接返回类标签
2、用完所有标签但是得不到唯一类别的分组,即特征不够用,挑选出现数量最多的类别作为返回

Parameters:
dataSet - 训练数据集
labels - 分类属性标签
featLabels - 存储选择的最优特征标签

Returns:
myTree - 决策树
"""
def createTree(dataSet, labels, featLabels):
# 取分类标签
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]
featLabels.append(bestFeatLabel)
# 根据最优特征的标签生成树
myTree = {bestFeatLabel:{}}
# 删除已经使用的特征标签
del(labels[bestFeat])
# 得到训练集中所有最优解特征的属性值
featValues = [example[bestFeat] for example in dataSet]
# 去掉重复的属性值
uniqueVals = set(featValues)
# 遍历特征,创建决策树
for value in uniqueVals:
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), labels, featLabels)
return myTree

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!