Multivariate normal density in Python?

后端 未结 10 1128
星月不相逢
星月不相逢 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:26

    I use the following code which calculates the logpdf value, which is preferable for larger dimensions. It also works for scipy.sparse matrices.

    import numpy as np
    import math
    import scipy.sparse as sp
    import scipy.sparse.linalg as spln
    
    def lognormpdf(x,mu,S):
        """ Calculate gaussian probability density of x, when x ~ N(mu,sigma) """
        nx = len(S)
        norm_coeff = nx*math.log(2*math.pi)+np.linalg.slogdet(S)[1]
    
        err = x-mu
        if (sp.issparse(S)):
            numerator = spln.spsolve(S, err).T.dot(err)
        else:
            numerator = np.linalg.solve(S, err).T.dot(err)
    
        return -0.5*(norm_coeff+numerator)
    

    Code is from pyParticleEst, if you want the pdf value instead of the logpdf just take math.exp() on the returned value

提交回复
热议问题