决策树算法学习–链接:
机器学习–决策树算法
信息增益=整体熵-条件熵
1.
信息熵
:
H
(
D
)
=
−
∑
k
=
1
K
∣
C
k
∣
∣
D
∣
l
o
g
2
∣
C
k
∣
∣
D
∣
1.信息熵: \textcolor{red}{H(D)=-\sum_{k=1}^K \frac{|C_k|}{|D|}log_2\frac{|C_k|}{|D|} }
1.信息熵:H(D)=−k=1∑K∣D∣∣Ck∣log2∣D∣∣Ck∣
2.
特征
A
对于数据集
D
的经验
r
e
d
条件熵可以表示为
H
(
D
∣
A
)
=
−
∑
i
=
1
n
∣
D
i
∣
∣
D
∣
∑
k
=
1
K
∣
D
i
k
∣
∣
D
i
∣
l
o
g
2
∣
D
i
k
∣
∣
D
i
∣
2.特征 A 对于数据集 D 的经验red条件熵可以表示为 \\ \textcolor{red}{H(D|A)=-\sum^n_{i=1}\frac{|D_i|}{|D|} \sum_{k=1}^K \frac{|D_{ik}|}{|D_i|}log_2\frac{|D_{ik}|}{|D_i|}}
2.特征A对于数据集D的经验red条件熵可以表示为H(D∣A)=−i=1∑n∣D∣∣Di∣k=1∑K∣Di∣∣Dik∣log2∣Di∣∣Dik∣
#自定义数据
df=pd.DataFrame(data=[[0,0,0,0,0],[0,0,0,1,0],[0,1,0,1,1],[0,1,1,0,1],
[0,0,0,0,0],[1,0,0,0,0],[1,0,0,1,0],[1,1,1,1,1],
[1,0,1,2,1],[1,0,1,2,1],[2,0,1,2,1],[2,0,1,1,1],
[2,1,0,1,1],[2,1,0,2,1],[2,0,0,0,0]],
columns['Education','is_Car','is_Job','Credit_conditions','is_credit'])
1-特征描述
'Education':教育程度 0,1,2
'is_Car': 是否有车 0,1
'is_Job': 是否有正式工作 0,1
'Credit_conditions':征信情况 0,1,2
'is_credit':标签:是否予审批信用卡 0,1
2-计算数据集的熵
#计算数据集的信息熵,也就是整体熵
def calcInfoEnt(data):
num = len (data)
labelcnt = {}
#label
label=[i[-1] for i in data]
for i in label:
if i not in labelcnt:
labelcnt[i] = 0
labelcnt[i] += 1
infoEnt = 0
for i in labelcnt:#计算信息熵
curr_info_entr = labelcnt[i]/num
infoEnt -= curr_info_entr*np.log2(curr_info_entr)
return infoEnt
>>calcInfoEnt(data)#整体熵
0.9709505944546686
#方便计算任意一个特征下的特征值的特征熵
def create_sub_dataset(dataSet, i, value):
res = []
for item in dataSet:
if item[i] == value:
curr_data = item[:i] + item[i+1:]
res.append(curr_data)
return res
#res:任意第i个特征,其中的特征值为value的样本————
#len(res):该特征值的个数/data:该特征值的概率P ,以此进行计算条件熵
3-函数图解:

4-信息增益计算
def calc_max_info_gain(dataSet):#计算所有特征的最大信息增益,dataSet为给定的数据集
n = len(dataSet[0])-1 # n 是特征的数量,-1 的原因是最后一列是分类标签
total_entropy = calcInfoEnt(dataSet)#整体数据集的信息熵
max_info_gain = [0,0]#返回值初始化
infoGain_list=[]
for i in range(n):
featList=[feat[i] for feat in dataSet]
featValues=set(featList)#第i个特征的,特征值
newEntropy=0.0
for value in featValues:
subDataset=create_sub_dataset(dataSet,i,value)
prob=len(subDataset)/len(dataSet)#该特征值value 先验概率
newEntropy+=prob*calcInfoEnt(subDataset)#条件熵
infoGain=total_entropy-newEntropy#信息增益=整体熵-条件熵
infoGain_list.append([i,infoGain])#各个特征得信息增益,一般筛选信息增益最大的点作为分裂点
if infoGain>max_info_gain[1]:
max_info_gain[1]=infoGain
max_info_gain[0]=i
return max_info_gain,infoGain_list
info_res,infoGain_list = calc_max_info_gain(data)
print("信息增益最大的特征索引为:{0},对应的信息增益为{1}".format(info_res[0],info_res[1]))
>>
>信息增益最大的特征索引为:2,对应的信息增益为0.4199730940219749
>>infoGain_list
>[[0, 0.08300749985576883],#第0个特征的信息增益
[1, 0.32365019815155627],#第1个特征的信息增益
[2, 0.4199730940219749],#第2个特征的信息增益
[3, 0.36298956253708536]]#第3个特征的信息增益
6329

被折叠的 条评论
为什么被折叠?



