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)

讓我們來看幾個例子來演示如何計算方陣的逆矩陣。

示例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]]])

更新於:2022年1月7日

913 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.