Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multivariate normal density in Python?

Is there any python package that allows the efficient computation of the PDF (probability density function) of a multivariate normal distribution?

It doesn't seem to be included in Numpy/Scipy, and surprisingly a Google search didn't turn up any useful thing.

like image 793
Benno Avatar asked Jul 23 '12 15:07

Benno


People also ask

How do you check for multivariate normality in Python?

In this approach, the user needs to call the multivariate_normality() function with the required parameters from the pingouin library to conduct the multivariate Normality test on the given data in Python. Parameters: X: Data matrix of shape (n_samples, n_features). alpha: Significance level.

What is NP random multivariate_normal ()?

numpy.random.multivariate_normal(mean, cov[, size]) Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalisation of the one-dimensional normal distribution to higher dimensions.


2 Answers

The multivariate normal is now available on SciPy 0.14.0.dev-16fc0af:

from scipy.stats import multivariate_normal var = multivariate_normal(mean=[0,0], cov=[[1,0],[0,1]]) var.pdf([1,0]) 
like image 123
juliohm Avatar answered Sep 19 '22 17:09

juliohm


I just made one for my purposes so I though I'd share. It's built using "the powers" of numpy, on the formula of the non degenerate case from http://en.wikipedia.org/wiki/Multivariate_normal_distribution and it aso validates the input.

Here is the code along with a sample run

from numpy import * import math # covariance matrix sigma = matrix([[2.3, 0, 0, 0],            [0, 1.5, 0, 0],            [0, 0, 1.7, 0],            [0, 0,   0, 2]           ]) # mean vector mu = array([2,3,8,10])  # input x = array([2.1,3.5,8, 9.5])  def norm_pdf_multivariate(x, mu, sigma):     size = len(x)     if size == len(mu) and (size, size) == sigma.shape:         det = linalg.det(sigma)         if det == 0:             raise NameError("The covariance matrix can't be singular")          norm_const = 1.0/ ( math.pow((2*pi),float(size)/2) * math.pow(det,1.0/2) )         x_mu = matrix(x - mu)         inv = sigma.I                 result = math.pow(math.e, -0.5 * (x_mu * inv * x_mu.T))         return norm_const * result     else:         raise NameError("The dimensions of the input don't match")  print norm_pdf_multivariate(x, mu, sigma) 
like image 40
user692734 Avatar answered Sep 18 '22 17:09

user692734