计算python中Dirichlet分布的pdf

时间:2012-05-18 19:50:30

标签: python numpy statistics scipy probability

我想在python中计算Dirichlet发行版的pdf,但是在任何类型的标准库中都找不到代码。 scipy.stats包含一长串分布,但似乎不包括Dirichlet,numpy.random.mtrand允许一个样本,但不提供pdf。

由于Dirichlet很常见,我想知道是否有其他名称我应该通过scipy.stats或类似的方式搜索它,或者我是否只是错过了它。

4 个答案:

答案 0 :(得分:4)

我找不到一个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))]))

警告:我没有测试过这个。如果有效,请告诉我。

答案 1 :(得分:3)

从scipy version 0.15开始,您可以使用scipy.stats.dirichlet.pdf (见here

答案 2 :(得分:-1)

您可以从伽玛分布中推导出Dirichlet分布。这显示在wikipedia page上。在那里你找到了这个python代码:

    params = [a1, a2, ..., ak]
    sample = [random.gammavariate(a,1) for a in params]
    sample = [v/sum(sample) for v in sample]

答案 3 :(得分:-2)

我认为它可能包含在numpy.random.mtrand.dirichlet但我不完全确定这是pdf还是采样。