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

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

Loan Eligibility Prediction Project using Machine learning on GCP
Loan Eligibility Prediction Project - Use SQL and Python to build a predictive model on GCP to determine whether an application requesting loan is eligible or not.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

End-to-End Speech Emotion Recognition Project using ANN
Speech Emotion Recognition using RAVDESS Audio Dataset - Build an Artificial Neural Network Model to Classify Audio Data into various Emotions like Sad, Happy, Angry, and Neutral

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 a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Build a Wealth Management Agentic AI Chatbot with MS Fabric
In this Agentic AI project , you will learn to build an intelligent financial assistant that autonomously analyzes your financial data, assesses risks, and designs personalized investment strategies, making wealth management more efficient and personalized to your needs

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 Regression Models in Python for House Price Prediction
In this Machine Learning Regression project, you will build and evaluate various regression models in Python for house price prediction.

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

OSZAR »