【问题标题】:How to calculate probabilities using numpy.histogram and then use it for calculating KL divergence?如何使用 numpy.histogram 计算概率,然后用它来计算 KL 散度?
【发布时间】:2020-01-01 09:20:44
【问题描述】:

在以下代码中,density=True 返回每​​个 bin 的概率密度函数。现在如果必须计算 P(x),我可以说hist 显示的是概率吗?例如,如果第一个 bin 的平均值是 0.5,我可以说 x=0.5 的概率是 hist[0] 吗?我必须使用使用 P(x) 的 KL 散度。

x = np.array([0,0,0,0,0,3,3,2,2,2,1,1,1,1,])
hist,bin_edges= np.histogram(x,bins=10,density=True)

【问题讨论】:

  • 因为概率是概率密度的积分,所以值在nth bin 中的概率是hist[n]*np.diff(bin_edges)[n]。

标签: python numpy statistics probability


【解决方案1】:

当您设置density=True 时,NumPy 返回一个概率密度函数(比如说p)。从理论上讲,p(0.5) = 0 因为概率定义为 PDF 曲线下的面积。您可以阅读有关它的更多详细信息here。因此,如果您想计算概率,则必须定义所需的范围并将该范围内的所有 PDF 值相加。

对于KL,我可以分享我的互信息计算解决方案(基本上是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

编辑: KL 可以这样计算(请注意我没有测试这个!):

def kl(x, y, sigma=1):
    # 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)

    kl = -np.sum(hist_x * np.log(hist_y / hist_x ))
    return kl

此外,为了获得最佳结果,您应该使用一些启发式方法计算 sigma,例如 A rule-of-thumb bandwidth estimator。

【讨论】:

  • @carobnodrov 对于 KL 散度我应该使用直方图的 y 轴值吗? KL 散度衡量两个分布的 b/w 差异。如果我选择每个 bin 的中心(在 x 轴上)作为 x 值假设它是 0.5,然后计算 x=0.5 的参考分布(泊松或任何其他)。这就是我们在KL散度中进行的方式吗?我很困惑KL散度的公式是否使用y轴值?还是我需要计算概率?
  • @jerry 对于 KL,在这种情况下您不应该使用 2D 直方图(或者您可以然后只对边际概率求和)。我将尝试编辑我的问题以包含 KL 的解决方案。
  • 在维基百科上,他们使用了一个例子来解决 KL 散度。他们将 x 轴显示为 bin 编号,将 y 轴显示为概率。我在我的问题中真的很困惑,我将 x 定义为输入,那么替换 KL 散度的相应 y 值是多少?
  • 请检查我的编辑是否对您有帮助。 KL 测量两个概率之间的“距离”。所以x 和y 是两个概率。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 2019-10-10
  • 2017-04-28
相关资源
最近更新 更多