在用python计算KL散度时,使用特定的P(x)作为参考分布,如何定义输入值P和q?
我想要实现KL散度,并且我想要使用p(x)作为参考分布,我想要与我的模型的分布进行比较。如何从参考分布P(x)得到直方图在用python计算KL散度时,使用特定的P(x)作为参考分布,如何定义输入值P和q?,python,numpy,matplotlib,Python,Numpy,Matplotlib,我想要实现KL散度,并且我想要使用p(x)作为参考分布,我想要与我的模型的分布进行比较。如何从参考分布P(x)得到直方图 defp(x): 返回((32/(数学pi)**2)*(x)**2*np.exp(-(4/数学pi)*(x)**2)) x=np.数组([0,0,0,0,0,3,3,2,2,2,1,1,1,1,])) 图=plt.图() ax=图添加_子批次(111) n、 存储箱,补丁=ax.hist(x,存储箱=10,密度=True) 为了计算KL散度,我定义了函数 def KL(p,
defp(x):
返回((32/(数学pi)**2)*(x)**2*np.exp(-(4/数学pi)*(x)**2))
x=np.数组([0,0,0,0,0,3,3,2,2,2,1,1,1,1,]))
图=plt.图()
ax=图添加_子批次(111)
n、 存储箱,补丁=ax.hist(x,存储箱=10,密度=True)
为了计算KL散度,我定义了函数
def KL(p,q):
KL_列表=[]
对于范围(p)内的i:
val=p*np.log(q/p)
KL_列表追加(val)
KL_list=-1*np.sum(np.array(KL_list))
返回KLU列表
现在为了调用函数KL(p,q),我必须定义p和q,那么在我的例子中p和q的值是多少?正如我已经回答的,下面是我的互信息计算解决方案(基本上是KL):
def mutual_information(x, y, sigma=1):
bins = (256, 256)
# histogram
hist_xy = np.histogram2d(x, y, bins=bins)[0]
# smooth it out for better results
ndimage.gaussian_filter(hist_xy, sigma=sigma, mode='constant', output=hist_xy)
# compute marginals
hist_xy = hist_xy + EPS # prevent division with 0
hist_xy = hist_xy / np.sum(hist_xy)
hist_x = np.sum(hist_xy, axis=0)
hist_y = np.sum(hist_xy, axis=1)
# compute mi
mi = (np.sum(hist_xy * np.log(hist_xy)) - np.sum(hist_x * np.log(hist_x)) - np.sum(hist_y * np.log(hist_y)))
return mi