简体   繁体   中英

Testing if an operation has been performed correctly in python 3 numpy?

I need to calculate a Hessian (matrix of second derivatives), and modify it iff it is not positive definite. Cholesky decomposition fails if a matrix is not symmetric positive (semi)definite, and Hessians are symmetric. Therefore I can use numpy.linalg.cholesky on my matrix, and this seems to be one of the most efficient ways of checking. See this post for example .

Now I am not sure how to condition on the Cholesky decomposition being performed without error. For instance

H=hessian(X)

if np.linalg.cholesky(H) ...??? :
      'modification'

Check the numpy docs . The function np.linalg.cholesky raises an LinAlgError if the decomposition fails. Hence, wrapping it up in a try / except block would be a possible solution.

import numpy as np

X = np.random.randint(0, 10, (5, 5))

# compute hessian of X
# H = hessian(X)

try:
    L = np.linalg.cholesky(H)
except np.linalg.LinAlgError:
    # modifications

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM