Calculating pdf Dirichlet distribution in python

I would like to calculate pdf for the Dirichlet distribution in python, but could not find the code for this in any standard library. scipy.stats includes a long list of distributions, but does not seem to include Dirichlet, and numpy.random.mtrand allows you to use one sample from it, but does not provide a PDF.

Since Dirichlet is quite common, I am wondering if there is another name I should look for in scipy.stats or similar, or I just skipped it somehow.

+6
source share
4 answers

I could not find it in numpy, but it looked enough to implement. Here is an ugly little liner. (I followed the function specified on Wikipedia, except that you need to provide x = [x1, ..., xk] and 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))])) 

Warning: I have not tested this. Let me know if this works.

+4
source

With scipy version 0.15 you can use scipy.stats.dirichlet.pdf (see here )

+3
source

You can get the Dirichlet distribution from the gamma distribution. This is shown on the wikipedia page. There you will find this python code:

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

I think it can be included in numpy.random.mtrand.dirichlet , but I'm not quite sure if this is a PDF or for sampling.

-2
source

Source: https://habr.com/ru/post/916122/


All Articles