# Get the inverse of a 3D array in Python

To compute the inverse of a 3D array, use the numpy.linalg.tensorinv() method in Python. The result is an inverse for a relative to the tensordot operation tensordot(a, b, ind), i. e., up to floating-point accuracy, tensordot(tensorinv(a), a, ind) is the “identity” tensor for the tensordot operation. The method returns a’s tensordot inverse, shape a.shape[ind:] + a.shape[:ind].

The 1st parameter is a, the Tensor to ‘invert’. Its shape must be ‘square’, i. e., prod(a.shape[:ind]) == prod(a.shape[ind:]). The 2nd parameter is ind, the number of first indices that are involved in the inverse sum. Must be a positive integer, default is 2.

## Steps

At first, import the required libraries −

import numpy as np
from numpy.linalg import inv

Create an array. The numpy.eye() returns a 2-D array with ones on the diagonal and zeros elsewhere −

arr = np.eye(4*6)

Changing the shape of the array created above −

arr.shape = (24, 8, 3)

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)

To compute the inverse of a 3D array, use the numpy.linalg.tensorinv() method in Python −

print("\nResult...\n",np.linalg.tensorinv(arr, ind = 1))


## Example

import numpy as np
from numpy.linalg import inv

# Create an array
# The numpy.eye() returns a 2-D array with ones on the diagonal and zeros elsewhere
arr = np.eye(4*6)

# Changing the shape of the array created above
arr.shape = (24, 8, 3)

# 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)

# To compute the inverse of a 3D array, use the numpy.linalg.tensorinv() method in Python.
print("\nResult...\n",np.linalg.tensorinv(arr, ind = 1))

## Output

Our Array...
[[[1. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

[[0. 1. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.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