How can I calculate the nearest positive semi-definite matrix?

前端 未结 4 580
名媛妹妹
名媛妹妹 2020-12-29 07:27

I\'m coming to Python from R and trying to reproduce a number of things that I\'m used to doing in R using Python. The Matrix library for R has a very nifty function called

4条回答
  •  一向
    一向 (楼主)
    2020-12-29 07:53

    I would submit a non-iterative approach. This is slightly modified from Rebonato and Jackel (1999) (page 7-9). Iterative approaches can take a long time to process on matrices of more than a few hundred variables.

    import numpy as np
    
    def nearPSD(A,epsilon=0):
       n = A.shape[0]
       eigval, eigvec = np.linalg.eig(A)
       val = np.matrix(np.maximum(eigval,epsilon))
       vec = np.matrix(eigvec)
       T = 1/(np.multiply(vec,vec) * val.T)
       T = np.matrix(np.sqrt(np.diag(np.array(T).reshape((n)) )))
       B = T * vec * np.diag(np.array(np.sqrt(val)).reshape((n)))
       out = B*B.T
       return(out)
    

    Code is modified from a discussion of this topic here around nonPD/PSD matrices in R.

提交回复
热议问题