Identity and Inverse Matrices in NumPy

NumPy makes it simple to work with identity and inverse matrices, fundamental concepts in linear algebra. You can easily create identity matrices using np.eye() and compute matrix inverses with np.linalg.inv().

  • Identity Matrix: A square matrix with ones on the diagonal and zeros elsewhere, acting as the multiplicative identity in matrix multiplication.
  • Inverse Matrix: For a square matrix A, the inverse A-1 satisfies A × A-1 = I, where I is the identity matrix.

Understanding these matrices is key to solving linear systems, transformations, and many algorithms in data science and machine learning. Let’s explore how to create and use them with NumPy.


Transpose of a Matrix

The transpose of a matrix flips it over its diagonal, swapping rows with columns. In NumPy, you can easily get the transpose of a matrix using the .T attribute or the np.transpose() function.

For example, if you have a matrix A of shape (m, n), its transpose will have shape (n, m).

python
import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])

# Using .T attribute
transpose_A = A.T

# Using np.transpose()
transpose_A_func = np.transpose(A)

print(transpose_A)
print(transpose_A_func)

How It Works:

  • The .T attribute returns the transpose of the array by swapping its rows and columns.
  • np.transpose() is a function that also returns the transpose and can handle more complex axis permutations for higher dimensions.
  • For 2D arrays, both methods produce the same output by flipping the matrix over its diagonal.
  • Transpose converts shape from (m, n) to (n, m).

Output

[[1 4]
 [2 5]
 [3 6]]

Transposing is widely used in linear algebra operations, data manipulation, and preparing matrices for multiplication.

To learn more about transpose matrices in NumPy, click here.


Identity Matrix in NumPy

An identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. It acts as the multiplicative identity in matrix multiplication, meaning any matrix multiplied by the identity matrix remains unchanged.

In NumPy, you can create an identity matrix using the np.eye() function, specifying the size of the matrix.

python
import numpy as np

# Create a 3x3 identity matrix
I = np.eye(3)

print(I)

How It Works:

  • np.eye(n) creates an n × n identity matrix.
  • The identity matrix has 1’s on the main diagonal and 0’s elsewhere.
  • It acts like 1 in matrix multiplication: I @ A = A @ I = A.

Output

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Identity matrices are fundamental in linear algebra, often used as the starting point for many matrix operations including finding inverses and solving systems of equations.


Determinant of a Matrix in NumPy

The determinant of a square matrix is a scalar value that tells us whether the matrix is invertible. In NumPy, you can compute it using the numpy.linalg.det() function.

A matrix is invertible (also called non-singular) only if its determinant is not zero.

python
import numpy as np

# Define a square matrix
A = np.array([[4, 7],
              [2, 6]])

# Compute the determinant
det = np.linalg.det(A)

print(det)

How It Works:

  • np.linalg.det() computes the determinant of any square matrix.
  • If det != 0, the matrix has an inverse.
  • If det == 0, the matrix is singular and cannot be inverted.
  • Floating point results might include very small decimal errors due to precision.

Output

10.000000000000002

💡 Tip: Always check the determinant before attempting to compute the inverse to avoid runtime errors.

For example, if you try to invert a matrix with a zero determinant, NumPy will raise a LinAlgError.

python
# Non-invertible (singular) matrix
B = np.array([[1, 2],
              [2, 4]])

# Try to compute determinant and inverse
det_B = np.linalg.det(B)
print("Determinant:", det_B)

inv_B = np.linalg.inv(B)  # This will raise an error if determinant is 0

Output

Determinant: 0.0
LinAlgError: Singular matrix

Inverse Matrix in NumPy

The inverse of a square matrix A is another matrix, denoted A-1, such that when multiplied together, they produce the identity matrix: A × A-1 = I.

Not all matrices have an inverse — only those that are square and have a non-zero determinant (called invertible or non-singular matrices).

In NumPy, you can compute the inverse of a matrix using the np.linalg.inv() function.

python
import numpy as np

# Define a 2x2 matrix
A = np.array([[4, 7],
              [2, 6]])


try:
  
    # Compute the inverse
    A_inv = np.linalg.inv(A)
    print("Inverse matrix:")
    print(A_inv)

except np.linalg.LinAlgError:
    print("Matrix is singular and not invertible.")

How It Works:

  • If the determinant is zero, the matrix is singular (non-invertible), so a Error is raised.
  • If invertible, np.linalg.inv(A) calculates the matrix inverse.
  • Try-except block gracefully handles the error if the matrix cannot be inverted.

Output

Inverse matrix:
[[ 0.6 -0.7]
 [-0.2  0.4]]

You can verify the result by multiplying the matrix with its inverse, which should give the identity matrix:

python
identity = (A @ A_inv)
print(identity)

Output

[[1. 0.]
 [0. 1.]]

Calculating inverses is essential in solving systems of linear equations, optimization problems, and many applications in machine learning.


Example 1: Verifying the Inverse Using the Identity Matrix (3×3)

You can verify a matrix inverse by multiplying the original matrix by its inverse. The result should be the identity matrix.

python
import numpy as np

# Define a 3x3 matrix
A = np.array([[2, 5, 7],
              [6, 3, 4],
              [5, -2, -3]])

# Compute the inverse
A_inv = np.linalg.inv(A)

# Multiply original matrix by its inverse
identity = A @ A_inv

print("Original matrix (A):")
print(A)

print("Inverse matrix (A_inv):")
print(A_inv)

print("Product (A @ A_inv):")
print(identity)

How It Works:

  • np.linalg.inv(A) computes the inverse of matrix A.
  • The product of a matrix and its inverse is the identity matrix.
  • The @ operator performs matrix multiplication.
  • The identity matrix has 1's on the diagonal and 0's elsewhere, confirming the inversion.

Output

Original matrix (A):
[[ 2  5  7]
 [ 6  3  4]
 [ 5 -2 -3]]

Inverse matrix (A_inv):
[[ 1.  -1.  1. ]
 [-38.  41. -34.]
 [ 27. -29.  24.]]

Product (A @ A_inv):
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

This confirms that A_inv is indeed the inverse of A, as their product yields the identity matrix.


Frequently Asked Questions

How do I create an identity matrix in NumPy?

Use np.eye(n) where n is the size of the identity matrix you want. It returns an n × n matrix with ones on the diagonal and zeros elsewhere.


How do I find the inverse of a matrix in NumPy?

Use np.linalg.inv(matrix). The matrix must be square and have a non-zero determinant to be invertible.


What is the identity matrix used for in NumPy?

The identity matrix serves as the multiplicative identity in matrix algebra. That means for any matrix A, A @ I = I @ A = A.


How can I check if a matrix is invertible in NumPy?

Check the determinant using np.linalg.det(matrix). If the result is not 0, the matrix is invertible.


What happens if I try to invert a singular matrix in NumPy?

NumPy will raise a LinAlgError indicating that the matrix is singular (non-invertible).



What's Next?

Coming up next, we’ll dive into the topic of Solving the Linear System Ax = b using NumPy — a fundamental concept in linear algebra that's crucial for understanding how to find solutions to equations, model real-world problems, and apply techniques in machine learning, data science, and engineering.