How to get the rank of a matrix in PyTorch

In this article, we are going to discuss how to get the rank of a matrix in PyTorch. we can get the rank of a matrix by using torch.linalg.matrix_rank() method.
torch.linalg.matrix_rank() method
matrix_rank() method accepts a matrix and a batch of matrices as the input. This method returns a new tensor with the rank of the input matrices and if the input is a batch of matrices then the output tensor also has the same batch dimensions as the input. the below syntax is used to get the rank of a matrix in PyTorch.
Syntax: torch.linalg.matrix_rank(mat)
Parameters:
- mat: This is our input Matrix or a batch of matrices.
Returns: returns a tensor with the rank of the input matrix.
Example 1:
The following program is to understand how to get the rank of matrix.
Python3
# import torch module import torch # define a tensor tens = torch.tensor([[0.5322, 0.9232, 0.232], [0.1112, 0.2323, 0.2611], [0.7556, 0.1217, 0.5435]]) # display tensor/matrix print("\n Input Matrix: ") print(tens) # get the rank of input matrix r = torch.linalg.matrix_rank(tens) # display rank of matrix print("\n Rank of input matrix: ", r) |
Output:
Example 2:
The following program is to know how to get the rank of a batch of matrices.
Python3
# import torch module import torch # define a batch of matrix # the below code create 2 matrix of 4x3 Batch = torch.rand(2, 4, 3) # Display matrices print("\n Batch of Matrices: ") print(Batch) # get ranks of the matrices r = torch.linalg.matrix_rank(Batch) # Display Result print("\n Batch of matrices rank: ") print(r) |
Output:



