PyTorch – How to compute the determinant of a square matrix?

PyTorchServer Side ProgrammingProgramming

To compute the determinant of a square matrix, we could apply torch.linalg.det() method. It returns a new tensor with computed determinant. It accepts a square matrix, a batch of square matrices and also batches of square matrices. It supports matrix of float, double, cfloat, and cdouble data types.

We could also apply torch.det() method to compute the determinant. It is an alias of the torch.linalg.det() method.

Syntax

torch.linalg.det(mat)
torch.det(mat)

Where mat is a square matrix or batch/s of square matrices. A matrix is a 2D torch tensor.

Steps

We could use the following steps to compute determinant of a square matrix −

  • Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it.

import torch
  • Define a square matrix. Here, we define a square matrix (2D tensor of size 3×3) of random numbers.

tensor = torch.randn(3,3)
  • Compute the determinant of the square matrix using torch.linalg.det(mat) or torch.det(mat). mat is a square matrix or batch/s of square matrices. Optionally assign this value to a new variable.

det_mat = torch.linalg.det(mat)
  • Print the computed determinant of the matrix.

print("Determinant:", det_mat)

Example 1

In this example, we compute the determinant of a square matrix of size 3×3.

# import required library
import torch

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

# print the above created matrix
print("Matrix:\n", mat)

# computet the determinant of the matrix
det_mat = torch.linalg.det(mat)
print("Determinant:\n", det_mat)

Output

It will produce the following output −

Matrix:
tensor([[ 0.1485, -1.5094, 1.4318],
    [-0.0838, -1.5691, 0.0387],
    [-2.1576, 1.6148, -0.9745]])
Determinant:
   tensor(-4.5740)

Example 2

In this program, we compute the determinants of a batch of two square matrices.

# Python program to determine the determinant of
# a batch of square matrices
# import torch library
import torch

# create a batch of two 3x3 square matrices
mat = torch.randn(2,3,3)

# print the above created batch of matrices
print("Batch of Matrices:\n", mat)

# compute the determinants of the batch of matrices
d = torch.linalg.det(mat)

# print the computed determinants
print("Determinants:\n", d)

Output

It will produce the following output −

Batch of Matrices:
   tensor([[[-0.1068, -1.2593, 0.6575],
      [ 1.3248, 0.3064, 0.2736],
      [-1.4946, -0.5549, -0.6089]],

      [[ 0.6121, -0.1686, 2.3977],
      [-0.4527, 1.1430, 1.6656],
      [ 0.9752, -1.6121, -0.1512]]])
Determinants:
   tensor([-0.6795, 0.3528])

Notice that the number of elements in the determinant tensor is same as the number of matrices in the batch.

raja
Updated on 07-Jan-2022 06:14:10

Advertisements