首页 > 解决方案 > 在使用特定 P(x) 作为参考分布的 python 计算 KL 散度时,如何定义输入值 p 和 q?

问题描述

我想实现 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 的值是多少?

标签: pythonnumpymatplotlib

解决方案


正如我在这里已经回答的那样,以下是我的互信息计算解决方案(基本上是 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

推荐阅读