How to compute the shannon entropy and mutual information of N variables
我需要计算互信息,因此需要计算N个变量的香农熵。
我写了一段计算特定分布的香农熵的代码。
假设我有一个变量x,数字数组。
按照香农熵的定义,我需要计算归一化的概率密度函数,因此使用numpy.histogram很容易获得它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import scipy.integrate as scint from numpy import* from scipy import* def shannon_entropy(a, bins): p,binedg= histogram(a,bins,normed=True) p=p/len(p) x=binedg[:-1] g=-p*log2(p) g[isnan(g)]=0. return scint.simps(g,x=x) |
选择插入x,并仔细选择该功能的箱号。
但是此功能非常依赖于bin编号:选择此参数的不同值会得到不同的值。
特别是如果我的输入是一个常数数组:
1 | x=[0,0,0,....,0,0,0] |
这个变量的熵显然必须为0,但是如果我选择bin数量等于1,我得到正确的答案,如果我选择不同的值,我得到奇怪的非意义(否定性)答案..我的感觉是numpy .histogram具有参数normed = True或density = True,如官方文档中所述,它们应该归一化归一化的直方图,并且在我从概率密度函数(numpy的输出)切入的那一刻可能会出现一些错误.histogram)到概率质量函数(香农熵的输入),我这样做:
1 2 | p,binedg= histogram(a,bins,normed=True) p=p/len(p) |
我想找到一种解决这些问题的方法,我想有一种有效的方法来独立于bin数来计算香农熵。
我写了一个函数来计算更多变量分布的香农熵,但我遇到了同样的错误。
代码是这样的,其中函数shannon_entropydd的输入是一个数组,在该数组中的每个位置上,每个变量都必须参与统计计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | def intNd(c,axes): assert len(c.shape) == len(axes) assert all([c.shape[i] == axes[i].shape[0] for i in range(len(axes))]) if len(axes) == 1: return scint.simps(c,axes[0]) else: return intNd(scint.simps(c,axes[-1]),axes[:-1]) def shannon_entropydd(c,bins=30): hist,ax=histogramdd(c,bins,normed=True) for i in range(len(ax)): ax[i]=ax[i][:-1] p=-hist*log2(hist) p[isnan(p)]=0 return intNd(p,ax) |
我需要这些数量,以便能够计算某些变量集之间的相互信息:
M_info(x,y,z)= H(x)+ H(z)+ H(y)-H(x,y,z)
其中H(x)是变量x的香农熵
我必须找到一种计算这些数量的方法,因此,如果有人使用一种完全不同的代码可以启动它,则无需修复此代码,而是找到一种计算此统计函数的正确方法!
我认为,如果选择
我必须说我没有阅读您的代码,但这对我有用:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import numpy as np x = [0,1,1,1,0,0,0,1,1,0,1,1] bins = 10 cx = np.histogram(x, bins)[0] def entropy(c): c_normalized = c/float(np.sum(c)) c_normalized = c_normalized[np.nonzero(c_normalized)] h = -sum(c_normalized * np.log(c_normalized)) return h hx = entropy(cx) |
结果将在很大程度上取决于估计的密度。您可以假设密度的特定形式吗?如果避免直方图或其他通用估计(例如内核密度估计),则可以减少结果对估计的依赖性。如果您可以提供有关所涉及变量的更多详细信息,我可以提出更具体的意见。
作为论文的一部分,我研究了相互信息的估计[1]。在第8.1节和附录F中有一些关于MI的内容。
[1] http://riso.sourceforge.net/docs/dodier-dissertation.pdf