Skip to content

Commit 2a3d9aa

Browse files
committed
multivariate gaussian
1 parent ac689da commit 2a3d9aa

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Sebastian Raschka 04/2014
2+
3+
import numpy as np
4+
5+
def pdf_multivariate_gauss(x, mu, cov):
6+
'''
7+
Caculate the multivariate normal density (pdf)
8+
9+
Keyword arguments:
10+
x = numpy array of a "d x 1" sample vector
11+
mu = numpy array of a "d x 1" mean vector
12+
cov = "numpy array of a d x d" covariance matrix
13+
'''
14+
assert(mu.shape[0] > mu.shape[1]), 'mu must be a row vector'
15+
assert(x.shape[0] > x.shape[1]), 'x must be a row vector'
16+
assert(cov.shape[0] == cov.shape[1]), 'covariance matrix must be square'
17+
assert(mu.shape[0] == cov.shape[0]), 'cov_mat and mu_vec must have the same dimensions'
18+
assert(mu.shape[0] == x.shape[0]), 'mu and x must have the same dimensions'
19+
part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
20+
part2 = (-1/2) * ((x-mu).T.dot(np.linalg.inv(cov))).dot((x-mu))
21+
return float(part1 * np.exp(part2))
22+
23+
def test_gauss_pdf():
24+
x = np.array([[0],[0]])
25+
mu = np.array([[0],[0]])
26+
cov = np.eye(2)
27+
28+
print(pdf_multivariate_gauss(x, mu, cov))
29+
30+
# prints 0.15915494309189535
31+
32+
if __name__ == '__main__':
33+
test_gauss_pdf()

0 commit comments

Comments
 (0)