假设我有两个 pdf,例如:
from scipy import stats
pdf_y = stats.beta(5, 9).pdf
pdf_x = stats.beta(9, 5).pdf
我想计算他们的KL 散度。在我重新发明轮子之前,PyData 生态系统中是否有任何内置函数可以做到这一点?
假设我有两个 pdf,例如:
from scipy import stats
pdf_y = stats.beta(5, 9).pdf
pdf_x = stats.beta(9, 5).pdf
我想计算他们的KL 散度。在我重新发明轮子之前,PyData 生态系统中是否有任何内置函数可以做到这一点?
KL 散度在 scipy.stats.entropy 中可用。从文档字符串
stats.entropy(pk, qk=None, base=None)
Calculate the entropy of a distribution for given probability values.
If only probabilities `pk` are given, the entropy is calculated as
``S = -sum(pk * log(pk), axis=0)``.
If `qk` is not None, then compute a relative entropy (also known as
Kullback-Leibler divergence or Kullback-Leibler distance)
``S = sum(pk * log(pk / qk), axis=0)``.
看起来这个包nimfa
有你要找的东西。http://nimfa.biolab.si
V = np.matrix([[1,2,3],[4,5,6],[6,7,8]])
fctr = nimfa.mf(V, method = "lsnmf", max_iter = 10, rank = 3)
fctr_res = nimfa.mf_run(fctr)
# Print the loss function according to Kullback-Leibler divergence. By default Euclidean metric is used.
print "Distance Kullback-Leibler: %5.3e" % fctr_res.distance(metric = "kl")
这并不是您要寻找的,因为它似乎只需要一个输入,但它可能是一个开始的地方。
此外,此链接可能很有用。似乎有一些代码(不是用 numpy)来计算相同的东西。 https://code.google.com/p/tackbp2011/source/browse/TAC-KBP2011/src/python-utils/LDA/kullback-leibler-divergence.py?r=100
在其他答案中,有经验的 KL 散度计算,而我们可以为所讨论的 Beta 分布提供封闭形式的解决方案。
我无法在网络上找到带有 KL-div 的片段以进行 beta 分发。最后我自己编码。
分享它,因为它可能对其他人有用:
import numpy as np
from scipy import special
def kl(a1, b1, a2, b2):
"""https://en.wikipedia.org/wiki/Beta_distribution"""
B = special.beta
DG = special.digamma
return np.log(B(a2, b2) / B(a1, b1)) + (a1 - a2) * DG(a1) + (b1 - b2) * DG(b1) + (
a2 - a1 + b2 - b1) * DG(a1 + b1)