Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to try-except an illegal matrix operation due to singularity in NumPy

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 
like image 538
ely Avatar asked Feb 06 '12 04:02

ely


People also ask

How do you avoid a singular matrix error in Python?

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.

What is LinAlgError?

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.

How do I create a matrix in Numpy?

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.


1 Answers

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 
like image 62
wim Avatar answered Sep 16 '22 11:09

wim