【问题标题】:KL ( Kullback-Leibler) distance with histogram smoothing in PythonKL(Kullback-Leibler)距离与Python中的直方图平滑
【发布时间】:2014-02-27 00:36:06
【问题描述】:

我有两个(不同长度的)数字列表。 使用 Python,我想用 10 个 bin 计算直方图。 然后我想用标准内核平滑这两个直方图(高斯内核,mean = 0,sigma=1) 然后我想计算这两个平滑直方图之间的 KL 距离。 我找到了一些关于直方图计算的代码,但不确定如何应用标准内核进行平滑以及如何计算 KL 距离。 请帮忙。

【问题讨论】:

    标签: python histogram gaussian smoothing


    【解决方案1】:

    要计算直方图,您可以使用numpy.histogram() 和高斯平滑scipy.ndimage.filters.gaussian_filter()。 Kullback-Leibler 散度代码可以在here 找到。

    进行所需计算的方法如下所示:

    import numpy as np
    from scipy.ndimage.filters import gaussian_filter
    
    def kl(p, q):
        p = np.asarray(p, dtype=np.float)
        q = np.asarray(q, dtype=np.float)
    
        return np.sum(np.where(p != 0, p * np.log(p / q), 0))
    
    def smoothed_hist_kl_distance(a, b, nbins=10, sigma=1):
        ahist, bhist = (np.histogram(a, bins=nbins)[0],
                        np.histogram(b, bins=nbins)[0])
    
        asmooth, bsmooth = (gaussian_filter(ahist, sigma),
                            gaussian_filter(bhist, sigma))
    
        return kl(asmooth, bsmooth)
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 2017-10-24
      • 2011-06-19
      • 1970-01-01
      相关资源
      最近更新 更多