From 2a3d9aa325119170b716096d5855e507e43d13b6 Mon Sep 17 00:00:00 2001 From: rasbt Date: Wed, 16 Apr 2014 01:58:02 -0400 Subject: [PATCH] multivariate gaussian --- useful_scripts/multivariate_gaussian_pdf.py | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 useful_scripts/multivariate_gaussian_pdf.py diff --git a/useful_scripts/multivariate_gaussian_pdf.py b/useful_scripts/multivariate_gaussian_pdf.py new file mode 100644 index 0000000..2f8c8fe --- /dev/null +++ b/useful_scripts/multivariate_gaussian_pdf.py @@ -0,0 +1,33 @@ +# Sebastian Raschka 04/2014 + +import numpy as np + +def pdf_multivariate_gauss(x, mu, cov): + ''' + Caculate the multivariate normal density (pdf) + + Keyword arguments: + x = numpy array of a "d x 1" sample vector + mu = numpy array of a "d x 1" mean vector + cov = "numpy array of a d x d" covariance matrix + ''' + assert(mu.shape[0] > mu.shape[1]), 'mu must be a row vector' + assert(x.shape[0] > x.shape[1]), 'x must be a row vector' + assert(cov.shape[0] == cov.shape[1]), 'covariance matrix must be square' + assert(mu.shape[0] == cov.shape[0]), 'cov_mat and mu_vec must have the same dimensions' + assert(mu.shape[0] == x.shape[0]), 'mu and x must have the same dimensions' + part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) ) + part2 = (-1/2) * ((x-mu).T.dot(np.linalg.inv(cov))).dot((x-mu)) + return float(part1 * np.exp(part2)) + +def test_gauss_pdf(): + x = np.array([[0],[0]]) + mu = np.array([[0],[0]]) + cov = np.eye(2) + + print(pdf_multivariate_gauss(x, mu, cov)) + + # prints 0.15915494309189535 + +if __name__ == '__main__': + test_gauss_pdf()