How to Compute Matrix inverse with Numpy

In this post, we will learn how to compute the inverse of matrix in Python using Numpy. Computing the inverse of a matrix is at the heart of linear algebra and important for many real world problem.

We will use Numpy’s linalg.inv() function to to compute the inverse of a matrix in Python.

Before we jump into seeing some examples, let us get some useful facts in inverse of a matrix. First, not all matrices have an inverse. If a matrix has an inverse, we say the matrix is invertible or non-singular. And if a matrix does not have an inverse, we say the matrix is non-invertible or singular.

Another very useful fact is that a matrix is invertible if and only if its determinant is non-zero.

Computing Matrix Inverse with. linalg.inv()

Now with basic understanding of inverse of a matrix, let’s see how to compute the inverse of a matrix using NumPy.

import numpy as np

Let us create a 3×3 matrix with Numpy ndarray.

A = np.array([[1,3,5],
              [2,5,1],
              [2,3,8]])
A

array([[1, 3, 5],
       [2, 5, 1],
       [2, 3, 8]])

The basic syntax of using Numpy’s linalg.inv() function is to use the matrix we want to invert as its argument. In this example, we provide the 3×3 matrix as argument to linalg.inv().

A_inverse = np.linalg.inv(A)

And the result is the inverse of the input matrix, if the matrix is invertible. In our example, the input matrix has inverse and it looks like this.

A_inverse

array([[-1.48,  0.36,  0.88],
       [ 0.56,  0.08, -0.36],
       [ 0.16, -0.12,  0.04]])

Checking the inverse of matrix

We can verify how. good the inverse of a matrix is by multiplying (dot product) the original matrix with the inverse of the matrix, i.e. AA^(-1). And the result should an identity matrix, i.e. ones along the diagonal and zeros in the off diagonal elements.
And our result does look like an identity matrix.

A.dot(np.linalg.inv(A))

array([[ 1.00000000e+00,  1.11022302e-16, -6.24500451e-17],
       [-1.38777878e-16,  1.00000000e+00, -1.45716772e-16],
       [-2.22044605e-16,  0.00000000e+00,  1.00000000e+00]])

By using, Numpy’s allclose() function, we can check if the result of AA^(-1) is close to identify matrix as shown below.

np.allclose(np.dot(A, A_inv), np.eye(3))

True

And the result is True suggesting that it is an identity matrix.

When does linalg.inv() fails

Let us consider a simple example where linalg.inv() might fail. As we stated before, a matrix that doess not have an inverse is called non-invertible or singular.

Here is a simple matrix that does not have an inverse.


A = np.array([[1,2],
              [-2,-4]])

And let us see what error that linalg.inv() throws for this non-invertible matrrix.

np.linalg.inv(A)

We get the following error message showing the matrix is singular.

---------------------------------------------------------------------------
LinAlgError                               Traceback (most recent call last)
Input In [28], in <cell line: 3>()
      1 A = np.array([[1,2],
      2               [-2,-4]])
----> 3 np.linalg.inv(A)

File <__array_function__ internals>:200, in inv(*args, **kwargs)

File /opt/anaconda3/lib/python3.9/site-packages/numpy/linalg/linalg.py:538, in inv(a)
    536 signature = 'D->D' if isComplexType(t) else 'd->d'
    537 extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 538 ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
    539 return wrap(ainv.astype(result_t, copy=False))

File /opt/anaconda3/lib/python3.9/site-packages/numpy/linalg/linalg.py:89, in _raise_linalgerror_singular(err, flag)
     88 def _raise_linalgerror_singular(err, flag):
---> 89     raise LinAlgError("Singular matrix")

<strong>LinAlgError: Singular matrix</strong>