PyTorch – 如何计算方阵的逆矩阵?
为了计算方阵的逆矩阵,我们可以使用`**torch.linalg.inv()**`方法。它返回一个包含给定矩阵逆矩阵的新张量。它接受一个方阵、一批方阵,以及方阵的批次。
矩阵是一个二维PyTorch张量。它支持**float、double、cfloat**和**cdouble**数据类型作为输入。逆矩阵存在当且仅当方阵可逆。
语法
torch.linalg.inv(M)
其中`**M**`是一个方阵或一批方阵。它返回逆矩阵。
步骤
我们可以使用以下步骤来计算方阵的逆矩阵:
- 导入所需的库。在以下所有示例中,所需的Python库是`**torch**`。确保你已经安装了它。
import torch
定义一个方阵。这里,我们定义一个方阵(大小为3×3的二维张量)。
M = torch.tensor([[1.,2., 3.],[1.5, 2., 2.3],[.1, .2, .5]])
使用`**torch.linalg.inv(M)**`计算方阵的逆矩阵。`M`是方阵或方阵的批次。可以选择将此值赋给一个新变量。
M_inv = torch.linalg.inv(M)
打印上面计算出的逆矩阵。
print("Norm:", M_inv)
让我们来看几个例子来演示如何计算方阵的逆矩阵。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例1
# Python program to compute the inverse of a square matrix # import required library import torch # define a 3x3 square matrix M = torch.tensor([[1.,2., 3.],[1.5, 2., 2.3],[.1, .2, .5]]) print("Matrix M:", M) # compute the inverse of above defined matrix Minv = torch.linalg.inv(M) print("Inversr Matrix:", Minv)
输出
它将产生以下输出:
Matrix M: tensor([[1.0000, 2.0000, 3.0000], [1.5000, 2.0000, 2.3000], [0.1000, 0.2000, 0.5000]]) Inversr Matrix: tensor([[ -2.7000, 2.0000, 7.0000], [ 2.6000, -1.0000, -11.0000], [ -0.5000, 0.0000, 5.0000]])
示例2
# Python program to compute the inverse of a square matrix # import required library import torch # define a 3x3 square matrix of random complex numbers M = torch.randn(3,3, dtype = torch.complex128) print("Matrix M:", M) # compute the inverse of above defined matrix Minv = torch.linalg.inv(M) print("Inverse Matrix:", Minv)
输出
它将产生以下输出:
Matrix M: tensor([[ 0.4425-1.4046j, -0.2492+0.7280j, -0.4746-0.4261j], [-0.0246-0.4826j, -0.0250-0.3656j, 1.1983-0.4130j], [ 0.1904+0.7817j, 0.5823-0.2140j, 0.6129+0.0590j]], dtype=torch.complex128) Inversr Matrix: tensor([[ 0.3491+0.2565j, -0.2743+0.2843j, 0.4041-0.3382j], [ 0.4856-0.6789j, -0.2541+0.0598j, 1.2471-0.5962j], [ 0.0221+0.2874j, 0.6732+0.0512j, 0.1537+0.5768j]], dtype=torch.complex128)
示例3
# Python program to compute the inverse of batch of matrices # import required library import torch # define a batch of two 3x3 square matrices B = torch.randn(2,3,3) print("Batch of Matrices :", B) # compute the inverse of above defined batch matrices Binv = torch.linalg.inv(B) print("Inverse Matrices:", Binv)
输出
它将产生以下输出:
Batch of Matrices : tensor([[[ 1.0002, 0.4318, -0.9800], [-1.7990, 0.0913, 0.9440], [-0.1339, 0.0824, -0.5501]], [[ 0.5289, -0.0909, 0.0354], [-0.2159, -0.5417, 0.3659], [-0.7216, -0.0669, -0.6662]]]) Inverse Matrices: tensor([[[ 0.2685, -0.3290, -1.0427], [ 2.3415, 1.4297, -1.7177], [ 0.2852, 0.2941, -1.8211]], [[ 1.6932, -0.2766, -0.0620], [-1.7919, -1.4360, -0.8838], [-1.6543, 0.4438, -1.3452]]])
广告