如何在 PyTorch 中获得矩阵的秩?

矩阵的秩可以使用Torchlinalg.matrix_rank()获得. 它以一个矩阵或一批矩阵作为输入,并返回一个具有value(s)矩阵秩的张量。torch.linalg模块为我们提供了许多线性代数运算。

语法

torch.linalg.matrix_rank(input)

其中输入是二维张量/矩阵或矩阵批次。

步骤

我们可以使用以下步骤来获得矩阵或矩阵批次的秩 -

  • 导入火炬库。确保您已经安装了它。

import torch

  • 创建一个 2D 张量/矩阵或一批矩阵并打印它。

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:\n", 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:\n", 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:\n", 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])