2014-02-27 17 views
1

直方圖平滑化距離我有號碼的兩個列表(不同長度的)。使用Python ,我想說10檔來計算直方圖。 然後我要平滑這些兩個直方圖與標準內核(高斯核函數,平均= 0,標準差= 1) 然後我想計算這些2個平滑直方圖之間的KL距離。 我發現了大約直方圖計算一些代碼,但沒有確定如何適用標準內核平滑,然後如何計算KL距離。 請幫忙。KL(的Kullback-Leibler距離)與在Python

回答

3

爲了計算直方圖可以使用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) 
+0

非常感謝您的回答。這個對我有用。 – Yantra