Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy error: Singular matrix

Tags:

python

numpy

What does the error Numpy error: Matrix is singular mean specifically (when using the linalg.solve function)? I have looked on Google but couldn't find anything that made it clear when this error occurs.

like image 465
KaliMa Avatar asked Dec 10 '12 05:12

KaliMa


2 Answers

A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; linalg.solve can't handle this.

You may find that linalg.lstsq provides a usable solution.

like image 114
Michael J. Barber Avatar answered Sep 19 '22 08:09

Michael J. Barber


This function inverts singular matrices as well using numpy.linalg.lstsq:

def inv(m):
    a, b = m.shape
    if a != b:
        raise ValueError("Only square matrices are invertible.")

    i = np.eye(a, a)
    return np.linalg.lstsq(m, i)[0]
like image 31
Procope Avatar answered Sep 21 '22 08:09

Procope