Matrix inverse in python numpy

How to invert a matrix or nArray in Python?

In this article, we will show you how to calculate the inverse of a matrix or ndArray using NumPy library in python.

What is inverse of a matrix?

The inverse of a matrix is such that if it is multiplied by the original matrix, it results in an identity matrix.

The inverse of a matrix is just the reciprocal of the matrix, as in regular arithmetic, for a single number that is used to solve equations to obtain the value of unknown variables. The inverse of a matrix is the matrix that, when multiplied by the original matrix, produces the identity matrix.

The inverse of a matrix exists only if the matrix is non-singular, that is, if the determinant is not 0. We can simply find the inverse of a square matrix using the determinant and adjoint using the formula below

if det(A) != 0 A-1 = adj(A)/det(A) else "Inverse does not exist"

Method 1 − Using numpy.linalg.inv() function for np.array() type

numpy.linalg.inv() function

Python has a very simple method for calculating the inverse of a matrix. To compute the inverse of a matrix, use the numpy.linalg.inv() function from the NumPy module in Python bypassing the matrix.

Syntax

Parameters

array − It is the matrix that must be inverted.

Return Value − numpy.linalg.inv() function returns the inverse of a matrix.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the numpy module with an alias name(np).
  • Use the numpy.array() function(returns a ndarray. The ndarray is an array object that satisfies the given requirements), for creating a numpy array by passing the 3-Dimensional array(3rows, 3columns) as an argument to it.
  • Use the linalg.inv() function(calculates the inverse of a matrix) of the numpy module to calculate the inverse of an input 3×3 matrix by passing the input matrix as an argument to it and print the inverse matrix.

Example

The following program returns the inverse of an input 3-Dimensional(3×3) matrix using the numpy.linalg.inv() function −

# importing numpy module with an alias name import numpy as np # creating a 3-Dimensional(3x3) numpy matrix inputArray_3d = np.array([[4, 5, 1], [3, 4, 12], [10, 2, 1]]) # printing the input 3D matrix print("The input numpy 3D matrix:") print(inputArray_3d) # calculating the inverse of an input 3D matrix resultInverse= np.linalg.inv(inputArray_3d) # printing the resultant inverse of an input matrix print("The Inverse of 3-Dimensional(3x3) numpy matrix:") print(resultInverse)

Output

On executing, the above program will generate the following output −

The input numpy 3D matrix: [[ 4 5 1] [ 3 4 12] [10 2 1]] The Inverse of 3-Dimensional(3x3) numpy matrix: [[-0.04246285 -0.00636943 0.11889597] [ 0.24840764 -0.01273885 -0.0955414 ] [-0.07218684 0.08917197 0.00212314]]

Method 2 − Using scipy.linalg.inv() function

scipy.linalg.inv()

Using the scipy module’s functionalities, we can perform various scientific calculations. It also works with numpy arrays.

Читайте также:  Чем кормить питона домашних условиях

In Python, scipy.linalg.inv() can also return the inverse of a given square matrix. It works in the same way as the numpy.linalg.inv() function.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import linalg from scipy module.
  • Use the numpy.matrix() function(returns a matrix from a string of data or an array-like object. The resulting matrix is a specialized 2D array), for creating a numpy matrix by passing the 2-Dimensional array(2rows, 2columns) as an argument to it.
  • Use the linalg.inv() function(calculates the inverse of a matrix) of the scipy module to calculate the inverse of an input 2×2 matrix by passing the input matrix as an argument to it and print the inverse matrix.

Example

 
import numpy as np # importing linalg from scipy module from scipy import linalg # creating a 2-Dimensional(2x2) NumPy matrix inputMatrix = np.matrix([[5, 2],[7, 3]]) # printing the input 2D matrix print("The input numpy 2D matrix:") print(inputMatrix) # calculating the inverse of an input 2D matrix resultInverse = linalg.inv(inputMatrix) # printing the resultant inverse of an input matrix print("The Inverse of 2-Dimensional(2x2) numpy matrix:") print(resultInverse)

Output

The input numpy 2D matrix: [[5 2] [7 3]] The Inverse of 2-Dimensional(2x2) numpy matrix: [[ 3. -2.] [-7. 5.]]

Method 3 − Using numpy.linalg.inv() function for np.matrix() type

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the numpy.matrix() function(returns a matrix from a string of data or an array-like object. The resulting matrix is a specialized 4D array), for creating a numpy matrix by passing the 4-Dimensional array(4 rows, 4 columns) as an argument to it.

Example

import numpy as np # creating a NumPy matrix (4x4 matrix) using matrix() method inputMatrix = np.matrix('[11, 1, 8, 2; 11, 3, 9 ,1; 1, 2, 3, 4; 9, 8, 7, 6]') # printing the input 4D matrix print("The input NumPy matrix:") print(inputMatrix) # calculating the inverse of an input matrix resultInverse= np.linalg.inv(inputMatrix) # printing the resultant inverse of an input matrix print("The Inverse of 4-Dimensional(4x4) numpy matrix:") print(resultInverse)

Output

The input NumPy matrix: [[11 1 8 2] [11 3 9 1] [ 1 2 3 4] [ 9 8 7 6]] The Inverse of 4-Dimensional(4x4) numpy matrix: [[ 0.25 -0.23214286 -0.24107143 0.11607143] [-0.25 0.16071429 -0.09464286 0.11964286] [-0.25 0.375 0.3125 -0.1875 ] [ 0.25 -0.30357143 0.12321429 0.05178571]]

Conclusion

In this article, we learned how to calculate the inverse of a matrix using three different examples. We learned how to take a matrix in Numpy using two different methods:numpy.array() and NumPy.matrix().

Источник

numpy.linalg.inv#

Given a square matrix a, return the matrix ainv satisfying dot(a, ainv) = dot(ainv, a) = eye(a.shape[0]) .

Parameters : a (…, M, M) array_like

Returns : ainv (…, M, M) ndarray or matrix

(Multiplicative) inverse of the matrix a.

If a is not square or inversion fails.

Similar function in SciPy.

Broadcasting rules apply, see the numpy.linalg documentation for details.

>>> from numpy.linalg import inv >>> a = np.array([[1., 2.], [3., 4.]]) >>> ainv = inv(a) >>> np.allclose(np.dot(a, ainv), np.eye(2)) True >>> np.allclose(np.dot(ainv, a), np.eye(2)) True 

If a is a matrix object, then the return value is a matrix as well:

>>> ainv = inv(np.matrix(a)) >>> ainv matrix([[-2. , 1. ], [ 1.5, -0.5]]) 

Inverses of several matrices can be computed at once:

>>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) >>> inv(a) array([[[-2. , 1. ], [ 1.5 , -0.5 ]], [[-1.25, 0.75], [ 0.75, -0.25]]]) 

Источник

Matrix inverse in python numpy

  • Numpy | Array Creation
  • numpy.arange() in Python
  • numpy.zeros() in Python
  • Create a Numpy array filled with all ones
  • numpy.linspace() in Python
  • numpy.eye() in Python
  • Creating a one-dimensional NumPy array
  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros | Python
  • How to generate 2-D Gaussian array using NumPy?
  • How to create a vector in Python using NumPy
  • Python | Numpy fromrecords() method
  • Copy and View in NumPy Array
  • How to Copy NumPy array into another array?
  • Appending values at the end of an NumPy array
  • How to swap columns of a given NumPy array?
  • Insert a new axis within a NumPy array
  • numpy.hstack() in Python
  • numpy.vstack() in python
  • Joining NumPy Array
  • Combining a one and a two-dimensional NumPy Array
  • Python | Numpy np.ma.concatenate() method
  • Python | Numpy dstack() method
  • Splitting Arrays in NumPy
  • How to compare two NumPy arrays?
  • Find the union of two NumPy arrays
  • Find unique rows in a NumPy array
  • Python | Numpy np.unique() method
  • numpy.trim_zeros() in Python
  • Matrix manipulation in Python
  • numpy matrix operations | empty() function
  • numpy matrix operations | zeros() function
  • numpy matrix operations | ones() function
  • numpy matrix operations | eye() function
  • numpy matrix operations | identity() function
  • Adding and Subtracting Matrices in Python
  • Matrix Multiplication in NumPy
  • Numpy ndarray.dot() function | Python
  • NumPy | Vector Multiplication
  • How to calculate dot product of two vectors in Python?
  • Multiplication of two Matrices in Single line using Numpy in Python
  • Python | Numpy np.eigvals() method
  • How to Calculate the determinant of a matrix using NumPy?
  • Python | Numpy matrix.transpose()
  • Python | Numpy matrix.var()
  • Compute the inverse of a matrix using NumPy
  • Reshape NumPy Array
  • Python | Numpy matrix.resize()
  • Python | Numpy matrix.reshape()
  • NumPy Array Shape
  • Change the dimension of a NumPy array
  • numpy.ndarray.resize() function – Python
  • Flatten a Matrix in Python using NumPy
  • numpy.moveaxis() function | Python
  • numpy.swapaxes() function | Python
  • Python | Numpy matrix.swapaxes()
  • numpy.vsplit() function | Python
  • numpy.hsplit() function | Python
  • Numpy MaskedArray.reshape() function | Python
  • Python | Numpy matrix.squeeze()
  • Random sampling in numpy | ranf() function
  • Random sampling in numpy | random() function
  • Random sampling in numpy | random_sample() function
  • Random sampling in numpy | sample() function
  • Random sampling in numpy | random_integers() function
  • Random sampling in numpy | randint() function
  • numpy.random.choice() in Python
  • How to choose elements from the list with different probability using NumPy?
  • How to get weighted random choice in Python?
  • numpy.random.shuffle() in python
  • numpy.random.geometric() in Python
  • numpy.random.permutation() in Python
  • Numpy | Array Creation
  • numpy.arange() in Python
  • numpy.zeros() in Python
  • Create a Numpy array filled with all ones
  • numpy.linspace() in Python
  • numpy.eye() in Python
  • Creating a one-dimensional NumPy array
  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros | Python
  • How to generate 2-D Gaussian array using NumPy?
  • How to create a vector in Python using NumPy
  • Python | Numpy fromrecords() method
  • Copy and View in NumPy Array
  • How to Copy NumPy array into another array?
  • Appending values at the end of an NumPy array
  • How to swap columns of a given NumPy array?
  • Insert a new axis within a NumPy array
  • numpy.hstack() in Python
  • numpy.vstack() in python
  • Joining NumPy Array
  • Combining a one and a two-dimensional NumPy Array
  • Python | Numpy np.ma.concatenate() method
  • Python | Numpy dstack() method
  • Splitting Arrays in NumPy
  • How to compare two NumPy arrays?
  • Find the union of two NumPy arrays
  • Find unique rows in a NumPy array
  • Python | Numpy np.unique() method
  • numpy.trim_zeros() in Python
  • Matrix manipulation in Python
  • numpy matrix operations | empty() function
  • numpy matrix operations | zeros() function
  • numpy matrix operations | ones() function
  • numpy matrix operations | eye() function
  • numpy matrix operations | identity() function
  • Adding and Subtracting Matrices in Python
  • Matrix Multiplication in NumPy
  • Numpy ndarray.dot() function | Python
  • NumPy | Vector Multiplication
  • How to calculate dot product of two vectors in Python?
  • Multiplication of two Matrices in Single line using Numpy in Python
  • Python | Numpy np.eigvals() method
  • How to Calculate the determinant of a matrix using NumPy?
  • Python | Numpy matrix.transpose()
  • Python | Numpy matrix.var()
  • Compute the inverse of a matrix using NumPy
  • Reshape NumPy Array
  • Python | Numpy matrix.resize()
  • Python | Numpy matrix.reshape()
  • NumPy Array Shape
  • Change the dimension of a NumPy array
  • numpy.ndarray.resize() function – Python
  • Flatten a Matrix in Python using NumPy
  • numpy.moveaxis() function | Python
  • numpy.swapaxes() function | Python
  • Python | Numpy matrix.swapaxes()
  • numpy.vsplit() function | Python
  • numpy.hsplit() function | Python
  • Numpy MaskedArray.reshape() function | Python
  • Python | Numpy matrix.squeeze()
  • Random sampling in numpy | ranf() function
  • Random sampling in numpy | random() function
  • Random sampling in numpy | random_sample() function
  • Random sampling in numpy | sample() function
  • Random sampling in numpy | random_integers() function
  • Random sampling in numpy | randint() function
  • numpy.random.choice() in Python
  • How to choose elements from the list with different probability using NumPy?
  • How to get weighted random choice in Python?
  • numpy.random.shuffle() in python
  • numpy.random.geometric() in Python
  • numpy.random.permutation() in Python

Источник

Оцените статью