In the field of scientific computing in Python, NumPy is the core library for handling matrices and arrays. Whether it’s data analysis, machine learning, or linear algebra problems, proficiently mastering NumPy matrix operations is fundamental. This article will explain matrix multiplication, transposition, and inverse matrices in the simplest way, suitable for beginners to quickly get started.
一、NumPy and Matrix Basics¶
First, ensure you have the NumPy library installed (if not, you can install it via pip install numpy). NumPy provides efficient multi-dimensional array and matrix operations, with its core being the ndarray object. We can treat a matrix as a two-dimensional ndarray.
1. Creating a Matrix¶
You can directly create a matrix using np.array() by passing a nested list:
import numpy as np
# Create a 2×2 matrix
matrix = np.array([[1, 2],
[3, 4]])
print(matrix)
# Output:
# [[1 2]
# [3 4]]
2. Basic Matrix Properties¶
The shape (number of rows and columns) of a matrix can be viewed via .shape, and the dimension via .ndim (a matrix is 2D, so ndim=2):
print("Shape:", matrix.shape) # Output: Shape: (2, 2)
print("Dimension:", matrix.ndim) # Output: Dimension: 2
print("Data Type:", matrix.dtype) # Output: Data Type: int64
二、Matrix Multiplication (Dot Product)¶
Matrix multiplication is one of the most core operations in linear algebra. It is crucial to distinguish between matrix multiplication and element-wise multiplication.
1. Difference Between Two Multiplication Types¶
-
Element-wise Multiplication: Multiply elements at corresponding positions. In NumPy, this is implemented with
*. However, it requires both matrices to have exactly the same shape. -
Matrix Multiplication (Dot Product): Mathematically, the number of columns in the first matrix must equal the number of rows in the second matrix (i.e., an
m×nmatrix multiplied by ann×pmatrix results in anm×pmatrix). In NumPy, this is implemented withnp.dot()or the@operator.
2. Examples of Matrix Multiplication¶
Suppose we have two matrices:
- A = [[1, 2], [3, 4]] (2×2)
- B = [[5, 6], [7, 8]] (2×2)
(1) Element-wise Multiplication (*)¶
C = A * B # Must have the same shape, otherwise an error occurs
print(C)
# Output:
# [[ 5 12]
# [21 32]]
(2) Matrix Multiplication (np.dot() or @)¶
D = np.dot(A, B) # Equivalent to A @ B
print(D)
# Output:
# [[19 22]
# [43 50]]
Verify Shape: The shape after matrix multiplication will become (2,2) (both original matrices are 2×2). If using matrices of different shapes:
A = np.array([[1, 2, 3], [4, 5, 6]]) # 2×3 matrix
B = np.array([[7, 8], [9, 10], [11, 12]]) # 3×2 matrix
print(A @ B) # Result shape should be 2×2
# Output:
# [[ 58 64]
# [139 154]]
三、Matrix Transposition¶
Matrix transposition refers to swapping the rows and columns of a matrix, denoted mathematically as \( A^T \) (or A.T).
1. Transposition Operation¶
Transposition is implemented using the .T attribute, which works for 2D matrices (and higher-dimensional arrays similarly):
A = np.array([[1, 2], [3, 4]])
A_T = A.T # Transposed matrix
print(A_T)
# Output:
# [[1 3]
# [2 4]]
Transposed Shape: A matrix with shape (m,n) becomes (n,m) after transposition:
print(A.shape) # Original shape: (2, 2)
print(A_T.shape) # Transposed shape: (2, 2) (since original is a square matrix)
2. Application of Transposition¶
Transposition is often used to adjust matrix shapes to fit multiplication. For example:
A = np.array([[1, 2], [3, 4], [5, 6]]) # 3×2 matrix
B = np.array([[7, 8, 9], [10, 11, 12]]) # 2×3 matrix
# A and B cannot be directly multiplied due to shape mismatch, but A.T is 2×3 (matches B's shape)
print((A.T @ B).shape) # Result shape: (2, 3)
四、Inverse Matrix¶
The inverse matrix is the “reciprocal” of a matrix: if a matrix \( A \) has an inverse matrix \( A^{-1} \), then \( A \times A^{-1} = I \) (where \( I \) is the identity matrix, with 1s on the diagonal and 0s elsewhere).
1. Prerequisites for Inverse Matrix¶
- Must be a square matrix: The number of rows equals the number of columns (e.g., 2×2, 3×3 matrices).
- Determinant is non-zero: The determinant can be understood as the “scaling factor” of the matrix; if it is zero, the matrix is not invertible.
2. NumPy Implementation of Inverse Matrix¶
Use np.linalg.inv() to compute the inverse matrix. First, import the np.linalg module:
A = np.array([[2, 1], [4, 3]]) # 2×2 square matrix
A_inv = np.linalg.inv(A) # Compute inverse matrix
print(A_inv)
# Output:
# [[ 1.5 -0.5]
# [-2. 1. ]]
Verify the Inverse Matrix: Verify that \( A \times A^{-1} \approx I \) using matrix multiplication. Due to floating-point errors, np.allclose() is more accurate:
I = np.eye(2) # Identity matrix
print(np.allclose(A @ A_inv, I)) # Output: True
3. Notes¶
- Non-square matrices do not have an inverse. For example,
A = np.array([[1, 2], [3, 4], [5, 6]])(3×2 matrix) will throw an error whennp.linalg.inv(A)is called. - Matrices with a determinant of 0 are not invertible. For example,
A = np.array([[1, 2], [2, 4]])(the second row is twice the first row):
det = np.linalg.det(A) # Compute determinant
print(det) # Output: 0.0 (determinant is 0, not invertible)
五、Summary and Exercises¶
This article covers three basic matrix operations in NumPy:
- Multiplication: Distinguish between element-wise multiplication (*) and matrix dot product (np.dot()/@), paying attention to shape matching.
- Transposition: Implemented via .T to swap rows and columns, useful for adjusting matrix shapes.
- Inverse Matrix: Computed using np.linalg.inv(), exists only for square matrices with non-zero determinants.
Mini-exercise: Try combining operations on the matrices A and B from this article, such as (A.T @ B).T or verifying if A_inv × A is the identity matrix.
Once you master these basics, you can further explore more complex linear algebra operations like matrix rank and eigenvalues. As the cornerstone of scientific computing, NumPy requires hands-on practice to improve proficiency!