📜  如何使用 NumPy 对矩阵求逆

📅  最后修改于: 2022-05-13 01:55:21.044000             🧑  作者: Mango

如何使用 NumPy 对矩阵求逆

矩阵的逆只是矩阵的倒数,就像我们在普通算术中对单个数字所做的那样,该数字用于求解方程以找到未知变量的值。矩阵的逆矩阵是与原始矩阵相乘时将作为单位矩阵的矩阵。只有当矩阵是非奇异的,即行列式不应该是 0时,矩阵的逆才存在。使用行列式和伴随,我们可以很容易地使用下面的公式找到方阵的逆,

if det(A) != 0
    A-1 = adj(A)/det(A)
else
    "Inverse doesn't exist"  

矩阵方程

=>Ax = B\\ =>A^{-1}Ax = A^{-1}B\\ =>x = A^{-1}B

使用 NumPy 逆矩阵

Python提供了一种非常简单的方法来计算矩阵的逆。 Python NumPy 模块中可用的函数numpy.linalg.inv()用于计算矩阵的逆。

示例 1:

Python
# Python program to inverse
# a matrix using numpy
  
# Import required package
import numpy as np
  
# Taking a 3 * 3 matrix
A = np.array([[6, 1, 1],
              [4, -2, 5],
              [2, 8, 7]])
  
# Calculating the inverse of the matrix
print(np.linalg.inv(A))


Python
# Python program to inverse
# a matrix using numpy
  
# Import required package
import numpy as np
  
# Taking a 4 * 4 matrix
A = np.array([[6, 1, 1, 3],
              [4, -2, 5, 1],
              [2, 8, 7, 6],
              [3, 1, 9, 7]])
  
# Calculating the inverse of the matrix
print(np.linalg.inv(A))


Python
# Python program to inverse
# a matrix using numpy
  
# Import required package
import numpy as np
  
# Inverses of several matrices can
# be computed at once
A = np.array([[[1., 2.], [3., 4.]],
              [[1, 3], [3, 5]]])
  
# Calculating the inverse of the matrix
print(np.linalg.inv(A))


输出:

[[ 0.17647059 -0.00326797 -0.02287582]
 [ 0.05882353 -0.13071895  0.08496732]
 [-0.11764706  0.1503268   0.05228758]]

示例 2:

Python

# Python program to inverse
# a matrix using numpy
  
# Import required package
import numpy as np
  
# Taking a 4 * 4 matrix
A = np.array([[6, 1, 1, 3],
              [4, -2, 5, 1],
              [2, 8, 7, 6],
              [3, 1, 9, 7]])
  
# Calculating the inverse of the matrix
print(np.linalg.inv(A))

输出:

[[ 0.13368984  0.10695187  0.02139037 -0.09090909]
 [-0.00229183  0.02673797  0.14820474 -0.12987013]
 [-0.12987013  0.18181818  0.06493506 -0.02597403]
 [ 0.11000764 -0.28342246 -0.11382735  0.23376623]]

示例 3:

Python

# Python program to inverse
# a matrix using numpy
  
# Import required package
import numpy as np
  
# Inverses of several matrices can
# be computed at once
A = np.array([[[1., 2.], [3., 4.]],
              [[1, 3], [3, 5]]])
  
# Calculating the inverse of the matrix
print(np.linalg.inv(A))

输出:

[[[-2.    1.  ]
  [ 1.5  -0.5 ]]

 [[-1.25  0.75]
  [ 0.75 -0.25]]]