Multivariate normal density in Python?

后端 未结 10 1145
星月不相逢
星月不相逢 2021-01-30 19:42

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

10条回答
  •  攒了一身酷
    2021-01-30 20:44

    If still needed, my implementation would be

    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()
    

    In case I make future changes, the code is here on GitHub

提交回复
热议问题