30

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
ely
  • 74,674
  • 34
  • 147
  • 228

2 Answers2

56

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
wim
  • 338,267
  • 99
  • 616
  • 750
  • Thanks. It's one of those head-slapping "d'oh" moments; I didn't realize we could directly use the NumPy errors in an `except` statement. – ely Feb 06 '12 at 05:02
  • Also, is there any way to make this specific to 'Singular matrix' and not just any instance of LinAlgError? – ely Feb 06 '12 at 05:04
  • 1
    Well, you can re-raise the caught exception if it's not that message.. see the latest edit to my answer. This is one way to do it, I'm not sure if there is maybe a better way. – wim Feb 06 '12 at 05:58
6

wim's answer no longer works for current versions of NumPy (I'm using 1.13 at the time of writing). Instead do:

import numpy as np

try:
    # your code that will (maybe) throw
except np.linalg.LinAlgError as e:
    if 'Singular matrix' in str(e):
        # your error handling block
    else:
        raise
harryscholes
  • 1,617
  • 16
  • 18