当您设置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。