How to Inverse a Matrix in Python Using np.linalg.inv?

This recipe will help you find how to perform matrix inversion in Python using the np.linalg.inv function for efficient numerical computations. | ProjectPro

Matrices play a crucial role in various mathematical and scientific computations. In many scenarios, finding the inverse of a matrix is essential for solving linear equations, optimization problems, and more. In Python, the numpy library provides a convenient function, np.linalg.inv(), for calculating the inverse of a matrix efficiently. Check out this numpy code example to explore how to inverse a matrix in Python using np.linalg.inv, as well as an alternative method without using numpy. 

Why Invert a Matrix in Python?

The inverse of a matrix is analogous to the reciprocal of a number. For a square matrix A, if there exists a matrix B such that the product A × B = B × A = I, where I is the identity matrix, then B is the inverse of A. Inverting a matrix is useful in solving systems of linear equations, computing eigenvalues and eigenvectors, and various other mathematical operations.

How to Invert a Matrix in Python? 

Here is a step-by-step guide to find the inverse of a matrix in Python using np.linalg.inv()- 

Step 1 - Import the library

    import numpy as np

We have only imported numpy which is needed.

Step 2 - Setting up the Data

We have created a matrix using an array and we will find the inverse of this.

     matrix = np.array([[1, 2, 3],

                       [4, 5, 6],

                       [7, 8, 9]])

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Step 3 - Calculating inverse matrix in Python 

We can find the inverse of the matrix by using np.linalg.inv and passing the matrix- 

    Inv = np.linalg.inv(matrix)

    print()

    print(Inv)

So the output comes as - 

[[ 3.15251974e+15 -6.30503948e+15  3.15251974e+15]

 [-6.30503948e+15  1.26100790e+16 -6.30503948e+15]

 [ 3.15251974e+15 -6.30503948e+15  3.15251974e+15]]

How to Invert a Matrix Without NumPy? 

If you want to avoid using numpy for some reason, you can manually calculate the inverse using mathematical operations. However, this method involves more code and is less efficient, especially for larger matrices. Here's a simple implementation without numpy:

Python inverse matrix without NumPy

This implementation uses the formula for the inverse of a 2x2 matrix. For larger matrices, a more generalized approach involving cofactors and adjugates is necessary.

How to Handle Singular Matrices? 

It's important to note that not all matrices have an inverse. A matrix without an inverse is called a singular matrix. Before using np.linalg.inv(), it's a good practice to check if the matrix is invertible using np.linalg.det(). If the determinant is non-zero, the matrix is invertible; otherwise, it is singular.

Handle Singular Matrix using np.linalg inv

Master NumPy Skills with Enterprise Grade Projects by ProjectPro! 

The np.linalg.inv() function in numpy provides a convenient and efficient way to calculate the inverse of a matrix in Python. It handles various edge cases and is widely used in scientific and engineering applications. Gaining practical experience is crucial for mastering NumPy operations, especially in the context of data science. ProjectPro offers a one-stop platform with over 270+ real-world projects in data science and big data. By actively participating in these projects, learners can solidify their understanding of NumPy and enhance their overall proficiency in Python. ProjectPro serves as a bridge between theoretical knowledge and practical application, providing a hands-on approach to mastering NumPy and other essential skills in the field of data science. 

Download Materials

What Users are saying..

profile image

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

Build a Logistic Regression Model in Python from Scratch
Regression project to implement logistic regression in python from scratch on streaming app data.

House Price Prediction Project using Machine Learning in Python
Use the Zillow Zestimate Dataset to build a machine learning model for house price prediction.

Multi-Class Text Classification with Deep Learning using BERT
In this deep learning project, you will implement one of the most popular state of the art Transformer models, BERT for Multi-Class Text Classification

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.