如何在 PyTorch 中獲取矩陣的秩?


可以使用 **torch.linalg.matrix_rank()** 獲取矩陣的秩。它接收矩陣或矩陣批次作為輸入,並返回包含矩陣秩值的張量。**torch.linalg** 模組提供了許多線性代數運算。

語法

torch.linalg.matrix_rank(input)

其中 input 是 **二維** 張量/矩陣或矩陣批次。

步驟

我們可以使用以下步驟來獲取矩陣或矩陣批次的秩:

  • 匯入 torch 庫。確保你已經安裝了它。

import torch
  • 建立一個二維張量/矩陣或矩陣批次並列印它。

t = torch.tensor([[1.,2.,3.],[4.,5.,6.]])
print("Tensor:", t)
  • 計算上述定義的矩陣的秩,並可選擇地將此值賦給一個新變數。

rank = torch.linalg.matrix_rank(t)
  • 列印計算出的矩陣秩。

print("Rank:", rank)

示例 1

以下 Python 程式演示瞭如何在 PyTorch 中查詢矩陣的秩:

# import torch library
import torch

# create a 2D Tensor/Matrix
t = torch.rand(4,3)
print("Matrix:
", t) # compute the rank of the matrix rank = torch.linalg.matrix_rank(t) print("Rank:", rank)

輸出

Matrix:
tensor([[0.6594, 0.5502, 0.9927],
   [0.3542, 0.0738, 0.0039],
   [0.7521, 0.9089, 0.7459],
   [0.1236, 0.8219, 0.0199]])
Rank: tensor(3)

示例 2

以下 Python 程式演示瞭如何在 PyTorch 中查詢複數矩陣的秩:

# import torch library
import torch

# create a complex Matrix
C = torch.rand(4,3, dtype = torch.cfloat)
print("Matrix:
", C) # compute the rank of above created complex matrix rank = torch.linalg.matrix_rank(C) print("Rank:", rank)

輸出

Matrix:
tensor([[0.2830+0.9152j, 0.4017+0.3157j, 0.6843+0.7504j],
   [0.5469+0.6831j, 0.5949+0.1112j, 0.1225+0.5372j],
   [0.5016+0.2642j, 0.8466+0.5250j, 0.8644+0.6261j],
   [0.9070+0.0886j, 0.2665+0.7483j, 0.0226+0.3262j]])
Rank: tensor(3)

示例 3

以下 Python 程式演示瞭如何計算矩陣批次的秩:

# import torch library
import torch

# create a batch of a batch of 4, 3x2 Matrices
B = torch.rand(4,3,2)
print("Matrix:
", B) # Compute the ranks of the matrices ranks = torch.linalg.matrix_rank(B) # print the ranks of matrices print("Ranks:", ranks)

輸出

Matrix:
tensor([[[0.1332, 0.6924],
   [0.7986, 0.3856],
   [0.7675, 0.6632]],

   [[0.8832, 0.4365],
   [0.2731, 0.8355],
   [0.8793, 0.0253]],

   [[0.4678, 0.7772],
   [0.4612, 0.8683],
   [0.3522, 0.8857]],

   [[0.5602, 0.1209],
   [0.2810, 0.0738],
   [0.4715, 0.5878]]])
Ranks: tensor([2, 2, 2, 2])

更新於:2021年12月6日

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

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