我想在 python 中计算 Dirichlet 分布的 pdf,但无法在任何类型的标准库中找到这样做的代码。 scipy.stats 包括一长串分布,但似乎不包括 Dirichlet,而 numpy.random.mtrand 允许从中抽取一个样本,但不提供 pdf。
由于 Dirichlet 非常常见,我想知道我是否应该在 scipy.stats 或类似文件中搜索它的其他名称,或者我是否只是以某种方式错过了它。
最佳答案
我在 numpy 中找不到,但看起来足以实现。这是一个丑陋的小单线。 (我遵循维基百科上给出的函数,除了你必须提供 x = [x1, ..., xk] 和 alpha = [a1, ..., ak])。
import math
import operator
def dirichlet_pdf(x, alpha):
return (math.gamma(sum(alpha)) /
reduce(operator.mul, [math.gamma(a) for a in alpha]) *
reduce(operator.mul, [x[i]**(alpha[i]-1.0) for i in range(len(alpha))]))
警告:我还没有测试过这个。让我知道它是否有效。
关于python - 在python中计算狄利克雷分布的pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658866/