Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating pdf of Dirichlet distribution in python

I'd like to calculate the pdf for the Dirichlet distribution in python, but haven't been able to find code to do so in any kind of standard library. scipy.stats includes a long list of distributions but doesn't seem to include the Dirichlet, and numpy.random.mtrand lets one sample from it, but doesn't give the pdf.

Since the Dirichlet is pretty common, I'm wondering whether there's some other name I should be searching for it by in scipy.stats or similar, or whether I've just missed it somehow.

like image 950
jpmccoy Avatar asked May 18 '12 19:05

jpmccoy


2 Answers

I couldn't find one in numpy, but it looked enough to implement. Here's an ugly little one-liner. (I followed the function given on Wikipedia, except you have 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 haven't tested this. Let me know if it works.

like image 140
John Zhang Avatar answered Sep 22 '22 09:09

John Zhang


As of scipy version 0.15, you can use scipy.stats.dirichlet.pdf (see here)

like image 43
Tim Goodman Avatar answered Sep 19 '22 09:09

Tim Goodman