Chapter 4 gave a taste of matrices; here we go deeper. Linear algebra is the language of machine learning, computer graphics and data science — a regression fit, a neural-net layer and a PCA are all matrix operations. np.linalg gives you the full toolkit.
Dot & matrix products
The @ operator is matrix multiplication; np.dot is equivalent. Remember it's not element-wise — inner dimensions must match:
A = np.array([[1, 2], [3, 4]]) # (2, 2)B = np.array([[5, 6], [7, 8]]) # (2, 2)A @ B # matrix product (rows·columns)A * B # element-wise (different result!)v = np.array([1, 0])A @ v # matrix–vector product → [1 3]np.dot(v, v) # 1 dot product of a vector with itself
Solving linear systems
To solve Ax = b, don't invert A — np.linalg.solve is faster and more numerically stable:
A = np.array([[3, 1], [1, 2]])b = np.array([9, 8])x = np.linalg.solve(A, b) # [2. 3.] → the solutionA @ x # ≈ b, confirming it
Determinant, rank, inverse
np.linalg.det(A) # determinant (0 → singular, not invertible)np.linalg.matrix_rank(A) # number of independent rows/columnsnp.linalg.inv(A) # inverse (only if det ≠ 0)np.linalg.norm(v) # length/magnitude of a vector
Eigenvalues & the SVD
Eigenvalues and the singular value decomposition power dimensionality reduction (PCA), recommender systems and much of ML:
vals, vecs = np.linalg.eig(A) # eigenvalues & eigenvectorsU, S, Vt = np.linalg.svd(A) # singular value decomposition# SVD underlies PCA: the singular values rank each direction's importance.
Practice
Solve the 2×2 system 3x + y = 9, x + 2y = 8 with np.linalg.solve and verify by multiplying back. Compute a matrix's determinant and rank, and check whether it's invertible. Find the eigenvalues of a symmetric 2×2 matrix.
Key takeaways
- 01@ (or np.dot) is matrix multiplication — not element-wise; inner dimensions must match.
- 02Solve Ax = b with np.linalg.solve, not by inverting A — it is faster and more stable.
- 03det = 0 means singular (no inverse); matrix_rank counts independent rows/columns.
- 04np.linalg provides inv, norm, eig and svd — the core of ML and graphics maths.
- 05The SVD underlies PCA and dimensionality reduction; eigenvalues reveal a matrix's structure.
