Introduction: What Is a Matrix Inverse?
The inverse of a matrix is the mathematical equivalent of undoing a transformation. For square matrices, the inverse is like a "mirror image" that, when multiplied with the original matrix, returns the identity matrix. In this tutorial, we’ll break down how to compute the inverse using NumPy—and just as importantly, when you shouldn’t try to do so.
Prerequisite: When Is a Matrix Invertible?
Before jumping into code, it’s crucial to know this: not all matrices have an inverse. A matrix is invertible (or non-singular) if:
- It is a square matrix (same number of rows and columns)
- Its determinant is not zero
Step-by-Step: How to Invert a Matrix Using NumPy
Let’s walk through the process of inverting a matrix using NumPy’s linalg.inv()
function.
import numpy as np
# Step 1: Create a square matrix
A = np.array([[4, 7],
[2, 6]])
# Step 2: Calculate its inverse
A_inv = np.linalg.inv(A)
print("Original Matrix A:")
print(A)
print("Inverse of A:")
print(A_inv)
Output Explanation
You’ll see:
Original Matrix A: [[4 7] [2 6]] Inverse of A: [[ 0.6 -0.7] [-0.2 0.4]]
This inverse matrix, when multiplied with the original, will produce the identity matrix.
Verification: Multiply to Check
Let’s verify our inverse calculation by multiplying the original and its inverse. The result should be close to an identity matrix (within floating point precision):
identity_check = np.dot(A, A_inv)
print("Product of A and its inverse (should be identity matrix):")
print(identity_check)
Product of A and its inverse (should be identity matrix): [[ 1.00000000e+00 0.00000000e+00] [ 0.00000000e+00 1.00000000e+00]]
This confirms our matrix inverse is correct. The tiny deviations (like 1e-16) are due to floating-point rounding errors, which are normal in numerical computation.
Important: Handle Singular or Non-Invertible Matrices
If your matrix is not invertible (e.g., its determinant is zero), NumPy will throw a LinAlgError
.
# Non-invertible matrix
B = np.array([[1, 2],
[2, 4]])
# This will raise an error
B_inv = np.linalg.inv(B)
LinAlgError: Singular matrix
Always check the determinant first before attempting an inversion:
if np.linalg.det(B) != 0:
B_inv = np.linalg.inv(B)
else:
print("Matrix is singular and cannot be inverted.")
Summary: Best Practices
- Only square matrices can be inverted
- Always check if the determinant is zero
- Use
np.allclose(np.dot(A, A_inv), np.eye(A.shape[0]))
to verify inversion - Be mindful of floating-point rounding issues
Conclusion
Understanding how to compute the inverse of a matrix in NumPy is foundational for anyone dealing with linear algebra, data science, or machine learning. While it's a powerful tool, use it with caution—especially on large matrices where numerical instability can arise. When in doubt, validate your results and consider alternatives like solving linear systems using np.linalg.solve()
instead of inverting matrices directly.