In NumPy, I'm trying to use linalg
to compute matrix inverses at each step of a Newton-Raphson scheme (the problem size is small intentionally so that we can invert analytically computed Hessian matrices). However, after I get far along towards convergence, the Hessian gets close to singular.
Is there any method within NumPy that lets me test whether a matrix is considered singular (computing determinant is not robust enough)? Ideally, it would be nice if there's a way to use a try
except
block to catch NumPy's singular array error.
How would I do this? The NumPy error given at the terminal is:
raise LinAlgError, 'Singular matrix' numpy.linalg.linalg.LinAlgError: Singular matrix
The only way to get around this error is to simply create a matrix that is not singular. What is this? We don't receive any error when inverting the matrix because the matrix is not singular.
LinAlgError[source] Generic Python-exception-derived object raised by linalg functions. General purpose exception class, derived from Python's exception. Exception class, programmatically raised in linalg functions when a Linear Algebra-related condition would prevent further correct execution of the function.
We can create a matrix in Numpy using functions like array(), ndarray() or matrix(). Matrix function by default creates a specialized 2D array from the given input. The input should be in the form of a string or an array object-like.
The syntax would be like this:
import numpy as np try: # your code that will (maybe) throw except np.linalg.LinAlgError as err: if 'Singular matrix' in str(err): # your error handling block else: raise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With