# -*- coding: utf-8 -*-
"""
熵定义为信息的期望值。
熵:表示随机变量的不确定性。
条件熵:在一个条件下,随机变量的不确定性。
信息增益:熵 - 条件熵
在一个条件下,信息不确定性减少的程度!
如果选择一个特征后,信息增益最大(信息不确定性减少的程度最大),那么我们就选取这个特征。
"""
from math import log
"""
函数说明:创建测试集
Parameter:
无
Returns:
dataSet 数据集
Labels 分类属性
"""
def createDataSet():
dataSet = [[0, 0, 0, 0, 'no'],
[0, 0, 0, 1, 'no'],
[0, 1, 0, 1, 'yes'],
[0, 1, 1, 0, 'yes'],
[0, 0, 0, 0, 'no'],
[1, 0, 0, 0, 'no'],
[1, 0, 0, 1, 'no'],
[1, 1, 1, 1, 'yes'],
[1, 0, 1, 2, 'yes'],
[1, 0, 1, 2, 'yes'],
[2, 0, 1, 2, 'yes'],
[2, 0, 1, 1, 'yes'],
[2, 1, 0, 1, 'yes'],
[2, 1, 0, 2, 'yes'],
[2, 0, 0, 0, 'no']]
Labels = ['不放贷', '放贷']
return dataSet, Labels
"""
函数说明:计算给定数据集的经验熵(香农熵)
Parameters:
dataSet 数据集
Returns:
shannonEnt 经验熵
"""
def calcShannonEnt(dataSet):
#返回数据集的行数
numEntirs = 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]) / numEntirs
#
shannonEnt -= prob * log(prob, 2)
return shannonEnt
"""
函数说明:按照给定特征划分数据集
Parameters:
dataSet 待划分的数据集
axis 划分数据集的特征
value 需要返回的特征值
Returns:
retDataSet 返回的数据集列表
"""
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
"""
函数说明:选择最优特征
Paramaters:
dataSet
Returns:
beatFeature 信息增益最优的特征的索引值
"""
def chooseBestFeatureToSplit(dataSet):
#特征数量
numFeatures = len(dataSet[0]) - 1
#计算数据集的香农熵
baseEntropy = calcShannonEnt(dataSet)
#信息增益
bestInfoGain = 0.0
#最优特征的索引值
bestFeature = -1
for i in range(numFeatures):
#获取dataSet的第i个所有特征
#将dataSet中的数据先按行依次放入example中,
#然后取得example中的example[i]元素,放入列表featList中
#相当于取所有行的第一个值
#之所以这样取,是因为dataSet是个列表,而不是矩阵,矩阵取第一列有方法
featList = [ example[i] for example in dataSet]
#创建集合set,元素不可重复
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
if __name__ == '__main__':
dataSet, features = createDataSet()
print("最优特征索引值:" + str(chooseBestFeatureToSplit(dataSet)))