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

ely picture ely · Feb 6, 2012 · Viewed 13.5k times · Source

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

Answer

wim picture wim · Feb 6, 2012

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