Compute log-determinants for a stack of matrices in Python


To compute log-determinants for a stack of matrices, use the numpy.linalg.slogdet() method in Python. The 1st parameter, s is an input array, has to be a square 2-D array. The method, with sign returns a number representing the sign of the determinant. For a real matrix, this is 1, 0, or -1. For a complex matrix, this is a complex number with absolute value 1, or else 0.

The method, with logdet returns the natural log of the absolute value of the determinant. If the determinant is zero, then sign will be 0 and logdet will be -Inf. In all cases, the determinant is equal to sign * np.exp(logdet).

Steps

At first, import the required libraries-

import numpy as np

Create an array −

arr = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])

Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)

Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array object...\n",arr.shape)

The determinant of an array in linear algebra −

print("\nDeterminant...\n",np.linalg.det(arr))

To compute log-determinants for a stack of matrices, use the numpy.linalg.slogdet() method. If the determinant is zero, then sign will be 0 and logdet will be -Inf. In all cases, the determinant is equal to sign * np.exp(logdet) −

(sign, logdet) = np.linalg.slogdet(arr)
print("\nResult....\n",(sign, logdet))

Example

import numpy as np

# Create an array
arr = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]]])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# The determinant of an array in linear algebra
print("\nDeterminant...\n",np.linalg.det(arr))

# To compute log-determinants for a stack of matrices, use the numpy.linalg.slogdet() method in Python
(sign, logdet) = np.linalg.slogdet(arr)
print("\nResult....\n",(sign, logdet))

Output

Our Array...
[[[1 2]
[3 4]]

[[1 2]
[2 1]]

[[1 3]
[3 1]]]

Dimensions of our Array...
3

Datatype of our Array object...
int64

Shape of our Array object...
(3, 2, 2)

Determinant...
[-2. -3. -8.]

Result....
(array([-1., -1., -1.]), array([0.69314718, 1.09861229, 2.07944154]))

Updated on: 25-Feb-2022

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements