PyTorch – 如何計算方陣的特徵值和特徵向量?


**torch.linalg.eig()** 計算方陣或方陣批次的特徵值分解。它接受**float、double、cfloat**和**cdouble**資料型別的矩陣和矩陣批次。它返回一個命名元組 (特徵值,特徵向量)。特徵值和特徵向量始終是複數值。特徵向量由**特徵向量**的列給出。

語法

(eigenvalues, eigenvectors) = torch.linalg.eig(A)

其中 A 是方陣或方陣批次。它返回一個命名元組 (特徵值,特徵向量)。

步驟

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫是**torch**。確保您已安裝它。

import torch
  • 建立一個方陣或方陣批次。這裡我們定義一個大小為 [3, 3] 的方陣(一個 2D torch 張量)。

A = torch.randn(3,3)
  • 使用**torch.linalg.eig(A)**計算方陣或方陣批次的特徵值分解。這裡 A 是方陣。

eigenvalues, eigenvectors = torch.linalg.eig(A)
  • 顯示特徵值和特徵向量。

print("Eigen Values:
", eigenvalues) print("Eigen Vectors:
", eigenvectors)

示例 1

在這個程式中,我們計算方陣的特徵值和特徵向量。

# import required library
import torch

# create a 3x3 square matrix
A = torch.randn(3,3)

# print the above created matrix
print("Matrix:
", A) # compute the Eigen values and vectors of the matrix eigenvalues, eigenvectors = torch.linalg.eig(A) print("Eigen Values:
", eigenvalues) print("Eigen Vectors:
", eigenvectors)

輸出

它將產生以下輸出:

Matrix:
   tensor([[-0.7412, 0.6472, -0.4741],
      [ 1.8981, 0.2936, -1.9471],
      [-0.1449, 0.0327, -0.8543]])
Eigen Values:
   tensor([ 1.0190+0.j, -1.3846+0.j, -0.9364+0.j])
Eigen Vectors:
   tensor([[-0.3476+0.j, -0.7716+0.j, 0.5184+0.j],
      [-0.9376+0.j, 0.5862+0.j, 0.3982+0.j],
      [ 0.0105+0.j, -0.2469+0.j, 0.7568+0.j]])

示例 2

在這個程式中,我們計算複數方陣的特徵值和特徵向量。

# import required library
import torch

# create a 2x2 square complex matrix
A = torch.randn(2,2, dtype = torch.cfloat )

# print the above created matrix
print("Matrix:
", A) # computet the eigen values and vectors of the matrix eigenvalues, eigenvectors = torch.linalg.eig(A) print("Eigen Values:
", eigenvalues) print("Eigen Vectors:
", eigenvectors)

輸出

它將產生以下輸出:

Matrix:
   tensor([[-0.1068-0.0045j, 0.7061-0.5698j],
      [-0.2521-1.1166j, 0.6921+1.4637j]])
Eigen Values:
   tensor([0.3194-0.3633j, 0.2659+1.8225j])
Eigen Vectors:
   tensor([[ 0.8522+0.0000j, -0.2012-0.3886j],
      [ 0.5231-0.0109j, 0.8992+0.0000j]])

更新於:2022年1月7日

2K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告