我们先看计算信息熵的公式
第二 计算信息熵
def entr(data): prob1 pd.value_counts(str1)/len(data[str1]) entropy sum( (-1)*prob1*np.log2(prob1) ) return entropy
第三 计算条件熵和信息增益率
def conditional_entropy(data, str1, str2): entr1 data.groupby(str1).apply(lambda x:entr(x[str2])) prob2 pd.value_counts(data[str1])/len(data[str1]) con_ent sum(entr1*prob2) #信息增益率率 Information_gain_rate entr(data[str2])-con_ent return Information_gain_rate conditional_entropy(data, 天气 , 打球 )
下面是完整代码图片
信息熵的详细解释 信息、信息熵、条件熵、信息增益、信息增益率、GINI指数、交叉熵、相对熵_江湖人称星爷-CSDN博客_gini 信息熵
参考代码 python详细步骤计算信息增益_spartanfuk的博客-CSDN博客_python计算信息增益



