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

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Build a Text Classification Model with Attention Mechanism NLP
In this NLP Project, you will learn to build a multi class text classification model with attention mechanism.

Machine Learning project for Retail Price Optimization
In this machine learning pricing project, we implement a retail price optimization algorithm using regression trees. This is one of the first steps to building a dynamic pricing model.

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Time Series Forecasting Project-Building ARIMA Model in Python
Build a time series ARIMA model in Python to forecast the use of arrival rate density to support staffing decisions at call centres.

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.

Learn Object Tracking (SOT, MOT) using OpenCV and Python
Get Started with Object Tracking using OpenCV and Python - Learn to implement Multiple Instance Learning Tracker (MIL) algorithm, Generic Object Tracking Using Regression Networks Tracker (GOTURN) algorithm, Kernelized Correlation Filters Tracker (KCF) algorithm, Tracking, Learning, Detection Tracker (TLD) algorithm for single and multiple object tracking from various video clips.

MLOps Project to Deploy Resume Parser Model on Paperspace
In this MLOps project, you will learn how to deploy a Resume Parser Streamlit Application on Paperspace Private Cloud.

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 Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.

Build Classification Algorithms for Digital Transformation[Banking]
Implement a machine learning approach using various classification techniques in Python to examine the digitalisation process of bank customers.