KL (Kullback-Leibler) 距离与Python中的直方图平滑。

问题描述 投票:2回答:1

我有两个列表(不同长度的)数字.使用Python,我想计算直方图,比如说10个bin.然后我想用标准核(高斯核,平均数=0,sigma=1)平滑这两个直方图,然后我想计算这两个平滑直方图之间的KL距离.我发现了一些关于直方图计算的代码,但不知道如何应用标准核来平滑,然后如何计算KL距离.请帮助。

python histogram gaussian smoothing
1个回答
7
投票

对于计算直方图,你可以使用以下方法 numpy.histogram() 而对于高斯平滑 scipy.ndimage.filter.gaussian_filter(). Kullback-Leibler分叉码可以找到。此处.

计算的方法做所需的计算将是这样的。

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)
© www.soinside.com 2019 - 2024. All rights reserved.