• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • Conferences
  • Python Books
  • About
    • Privacy Policy
You are here: Home / Numpy Tips / How to Compute Matrix inverse with Numpy

How to Compute Matrix inverse with Numpy

December 27, 2022 by cmdlinetips

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>

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related posts:

Default Thumbnail9 Basic Linear Algebra Operations with NumPy Default ThumbnailHow to Compute Euclidean distance in Numpy Default ThumbnailHow to Compute Manhattan Distance in Python with Numpy Linear Regression fit with Matrix Multiplication in PythonLinear Regression Using Matrix Multiplication in Python Using NumPy

Filed Under: Numpy linalg.inv, Numpy Tips Tagged With: numpy matrix inverse

Primary Sidebar

Subscribe to Python and R Tips and Learn Data Science

Learn Pandas in Python and Tidyverse in R

Tags

Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

RSS RSS

  • How to convert row names to a column in Pandas
  • How to resize an image with PyTorch
  • Fashion-MNIST data from PyTorch
  • Pandas case_when() with multiple examples
  • An Introduction to Statistical Learning: with Applications in Python Is Here
  • 10 Tips to customize ggplot2 title text
  • 8 Plot types with Matplotlib in Python
  • PCA on S&P 500 Stock Return Data
  • Linear Regression with Matrix Decomposition Methods
  • Numpy’s random choice() function

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in

Go to mobile version