计算条件熵代码(Python)

首先给出条件熵的定义,摘自维基百科:

If H(Y|X=x) is the entropy of the discrete random variable Y conditioned on the discrete random variable X taking a certain value x, then H(Y|X) is the result of averaging H(Y|X=x) over all possible values x that X may take.

大致可以理解为在条件X下,Y的条件概率分布对X的期望。

计算公式如下,摘自维基百科:


由于没有在网上找到相关计算条件熵的代码,于是我根据以上公式自己写了一个Python版本的代码。

首先给出一段待计算的数据。这里给出的是两个随机变量间的具体数量分布,并转换为联合概率密度。

data=np.array([[0,1963,0],
               [0,363,0],
               [0,425,0],
               [0,936,2],
               [1265,256,4755],
               [0,95,0],
               [98,36,1374],
               [0,1751,0]])
totalval=float(np.sum(data))
data=(data)/totalval    #求联合概率分布
print data

具体计算代码如下:

def calcConditionalEnt(data):
    #先计算条件熵的每一项
    def calcSingleEnt(p_xy,p_x):
        return p_xy*math.log((p_x/p_xy),2) if p_xy!=0 else 0

    ConditionEnt=0
    for i in range(len(data[0])):
        colsum=map(sum,zip(*data))  #各列求和
        for j in range(len(data)):
            ConditionEnt+=calcSingleEnt(data[j][i],colsum[i])   #各项熵求和

    return ConditionEnt





猜你喜欢

转载自blog.csdn.net/baike33/article/details/80982245