1.熵的基本概念
2.信息熵
上式信息熵可以算出结果为:0.97
3.信息增益
[[1,1,'yes'],[1,1,'yes'],[1,0,'no'],[0,1,'no'],[0,1,'no']]
如果不拆分信息熵为0.97。
按第一个变量拆分为两个数据集。
[[1,1,'yes'],[1,1,'yes'],[1,0,'no']]和[[0,1,'no'],[0,1,'no']]
分类后第一个数据集的信息熵为:
其结果为:0.92
分类后第二个数据集的信息熵为:
注:结果只有一个选择的数据集信息熵为0 其结果为:0
可见按第一个变量拆分数据集,其信息熵下降,混乱程度降低。其对应的信息增益为:
0.97-0.551=0.42
4.python代码实现
#计算熵(熵越大说明该数据集变化程度越高、不确定性越强)
from math import log,exp
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVec in dataSet: #the the number of unique elements and their occurance
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])/numEntries
shannonEnt -= prob * log(prob, 2) #log base 2
return shannonEnt
#拆分数据集,方便后续求不同的熵
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis] #chop out axis used for splitting
reducedFeatVec.extend(featVec[axis+1:])
retDataSet.append(reducedFeatVec)
return retDataSet
def chooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) - 1 #the last column is used for the labels
baseEntropy = calcShannonEnt(dataSet)
bestInfoGain = 0.0; bestFeature = -1
for i in range(numFeatures): #iterate over all the features
featList = [example[i] for example in dataSet]#create a list of all the examples of this feature
uniqueVals = set(featList) #get a set of unique values
newEntropy = 0.0
for value in uniqueVals:
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet)/float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy #calculate the info gain; ie reduction in entropy
print("按第几个变量拆分:"+str(round(i,3)),"未拆分前的信息熵:"+str(round(baseEntropy,3)),
"拆分后的信息熵:"+str(round(newEntropy,3)),"信息增益:"+str(round(infoGain,3)))
chooseBestFeatureToSplit([[1,1,'yes'],[1,1,'yes'],[1,0,'no'],[0,1,'no'],[0,1,'no']])