How to Fix: numpy.linalg.LinAlgError: Singular matrix


One error you may encounter in Python is:

numpy.linalg.LinAlgError: Singular matrix

This error occurs when you attempt to invert a singular matrix, which by definition is a matrix that has a determinant of zero and cannot be inverted.

This tutorial shares how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following matrix using NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Now suppose we attempt to use the inv() function from NumPy to calculate the inverse of the matrix:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

We receive an error because the matrix that we created does not have an inverse matrix.

Note: Check out this page from Wolfram MathWorld that shows 10 different examples of matrices that have no inverse matrix.

By definition, a matrix is singular and cannot be inverted if it has a determinant of zero.

You can use the det() function from NumPy to calculate the determinant of a given matrix before you attempt to invert it:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

The determinant of our matrix is zero, which explains why we run into an error.

How to Fix the Error

The only way to get around this error is to simply create a matrix that is not singular.

For example, suppose we use the inv() function to invert the following matrix:

import numpy as np
from numpy.linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308  0.26923077]
 [ 0.15384615 -0.03846154]]

We don’t receive any error when inverting the matrix because the matrix is not singular.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: ‘numpy.float64’ object is not callable
How to Fix: ‘numpy.ndarray’ object is not callable
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer

Leave a Reply

Your email address will not be published.