我想实现KL散度,并且我想将P(x)用作参考分布,以便与之比较模型的分布。如何从参考分布P(x)中获得直方图?
def P(x):
return ((32/(math.pi)**2)*(x)**2*np.exp(-(4/math.pi)*(x)**2))
x = np.array([0,0,0,0,0,3,3,2,2,2,1,1,1,1,])
fig = plt.figure()
ax = fig.add_subplot(111)
n,bins,patches = ax.hist(x,bins=10,density=True)
为计算KL散度,我定义了函数
def KL(p,q):
KL_list =[]
for i in range(p):
val= p*np.log(q /p)
KL_list.append(val)
KL_list=-1*np.sum(np.array(KL_list))
return KL_list
现在,要调用函数KL(p,q),我必须定义p和q,那么我的情况下p和q的值是什么?
答案 0 :(得分:-1)
我已经回答了here,以下是我的互信息计算(基本上是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