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

Ameeruddin Mohammed

ETL (Abintio) developer at IBM
linkedin profile url

I come from a background in Marketing and Analytics and when I developed an interest in Machine Learning algorithms, I did multiple in-class courses from reputed institutions though I got good... Read More

Relevant Projects

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Learn to Build an End-to-End Machine Learning Pipeline - Part 2
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, incorporating Hopsworks' feature store and Weights and Biases for model experimentation.

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

PyTorch Project to Build a GAN Model on MNIST Dataset
In this deep learning project, you will learn how to build a GAN Model on MNIST Dataset for generating new images of handwritten digits.

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

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.

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.

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..

Build CNN for Image Colorization using Deep Transfer Learning
Image Processing Project -Train a model for colorization to make grayscale images colorful using convolutional autoencoders.