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

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Build a Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

Multilabel Classification Project for Predicting Shipment Modes
Multilabel Classification Project to build a machine learning model that predicts the appropriate mode of transport for each shipment, using a transport dataset with 2000 unique products. The project explores and compares four different approaches to multilabel classification, including naive independent models, classifier chains, natively multilabel models, and multilabel to multiclass approaches.

CI/CD Deployment of Gaussian Process Time Series Models
In this MLOps project, you will learn to build an automated, end-to-end MLOps pipeline to deploy a Gaussian Process Time Series forecasting model on AWS. Using Terraform for infrastructure provisioning, the solution implements CI/CD pipelines that support safe, reproducible staging and production environments.

Image Classification Model using Transfer Learning in PyTorch
In this PyTorch Project, you will build an image classification model in PyTorch using the ResNet pre-trained model.

Autogen Project to Build an Intelligent AI Personal Assistant
Build a multi-agent AI personal assistant using Autogen that can handle tasks like managing calendars, emails, reminders, messaging, research, and weather updates, automating everyday workflows with LLMs and tool integrations.

Build and Deploy an AI Resume Analyzer with OpenAI and Azure
In this AI Resume Analyzer project, you will learn to build and deploy AI resume analyzer that helps job seekers assess how effectively their resumes match job descriptions using OpenAI's language models and Azure's cloud infrastructure.

Build an Outreach AI Agent using CrewAI,Twilio and OpenAI APIs
In this project, you will learn to build an end-to-end AI-powered customer outreach system using CrewAI. You’ll design a workflow where different AI agents handle different tasks like analyzing customer data, creating personalized call scripts, making voice calls, and sending follow-up emails.

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

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.