NumPy Linear Algebra
Linear algebra works with vectors and matrices as whole objects: matrix products, systems of linear equations, inverses, determinants, eigenvalues. It is the mathematics underneath computer graphics, machine learning, statistics (linear regression) and physics simulations. NumPy covers it with the @ operator and the np.linalg module.
Element-wise * vs matrix product @
This is the first thing to get right. * multiplies matching elements; @ (or np.matmul / np.dot) computes the matrix product, where each result entry is a row of the left matrix "dotted" with a column of the right one:
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
print(A * B) # element-wise
print(A @ B) # matrix product: [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]][[ 5 12]
[21 32]]
[[19 22]
[43 50]]
For a matrix product of shapes (n, k) @ (k, m), the inner sizes must match, and the result has shape (n, m).
Dot products and vectors
The dot product of two vectors multiplies matching elements and adds them up. It measures how much two vectors point in the same direction:
import numpy as np
prices = np.array([2.5, 4.0, 1.2]) # per item
quantities = np.array([4, 1, 10])
print("total bill:", prices @ quantities)
u = np.array([3.0, 4.0])
v = np.array([4.0, 3.0])
print("length of u:", np.linalg.norm(u))
cos_angle = (u @ v) / (np.linalg.norm(u) * np.linalg.norm(v))
print("cosine similarity:", cos_angle)total bill: 26.0
length of u: 5.0
cosine similarity: 0.96
Cosine similarity (1 = same direction, 0 = perpendicular) is how search engines and recommendation systems compare documents represented as vectors.
Transpose, identity, inverse, determinant
import numpy as np
M = np.array([[4.0, 7.0],
[2.0, 6.0]])
print(M.T) # transpose: rows become columns
print(np.linalg.det(M).round(6)) # determinant: 4*6 - 7*2 = 10
M_inv = np.linalg.inv(M)
print(M_inv)
print(np.allclose(M @ M_inv, np.eye(2))) # M times its inverse = identity[[4. 2.]
[7. 6.]]
10.0
[[ 0.6 -0.7]
[-0.2 0.4]]
True
A matrix with determinant 0 is singular: it has no inverse, and np.linalg.inv raises LinAlgError.
Solving systems of linear equations
A system like
2x + 1y = 11
1x + 3y = 13is written as A @ [x, y] = b and solved with np.linalg.solve(A, b). That is faster and more accurate than computing inv(A) @ b:
import numpy as np
A = np.array([[2.0, 1.0],
[1.0, 3.0]])
b = np.array([11.0, 13.0])
x = np.linalg.solve(A, b)
print("solution:", x)
print("check A @ x:", A @ x)
# A bakery problem: 3 cakes + 2 pies cost 31; 1 cake + 4 pies cost 27
A2 = np.array([[3.0, 2.0], [1.0, 4.0]])
print("cake, pie prices:", np.linalg.solve(A2, [31.0, 27.0]))solution: [4. 3.]
check A @ x: [11. 13.]
cake, pie prices: [7. 5.]
Least squares: fitting a line
When there are more equations than unknowns (for instance, many noisy data points and a line with 2 parameters), there's usually no exact solution. np.linalg.lstsq finds the best fit in the least-squares sense, the basis of linear regression:
import numpy as np
hours = np.array([1, 2, 3, 4, 5, 6], dtype=float)
score = np.array([52, 55, 61, 64, 70, 73], dtype=float)
X = np.column_stack((hours, np.ones_like(hours))) # columns: slope, intercept
(slope, intercept), *_ = np.linalg.lstsq(X, score, rcond=None)
print(f"score = {slope:.3f} * hours + {intercept:.3f}")
print("predicted for 8 hours:", round(slope * 8 + intercept, 1))score = 4.371 * hours + 47.200
predicted for 8 hours: 82.2
Eigenvalues and eigenvectors
An eigenvector of a matrix is a direction that the matrix only stretches (by a factor, the eigenvalue) without rotating. They appear in vibration analysis, Google's original PageRank and principal component analysis (PCA):
import numpy as np
A = np.array([[2.0, 0.0],
[0.0, 3.0]])
values, vectors = np.linalg.eig(A)
print(values)
print(vectors)
S = np.array([[2.0, 1.0],
[1.0, 2.0]])
w, V = np.linalg.eigh(S) # eigh: for symmetric matrices
print(w)
print(np.allclose(S @ V[:, 1], w[1] * V[:, 1])) # A v = lambda v[2. 3.]
[[1. 0.]
[0. 1.]]
[1. 3.]
True
| Function | Purpose |
|---|---|
a @ b, np.matmul, np.dot |
matrix / dot product |
np.linalg.norm(v) |
length of a vector (or matrix norm) |
np.linalg.det(A) |
determinant |
np.linalg.inv(A) |
inverse |
np.linalg.solve(A, b) |
solve A x = b |
np.linalg.lstsq(A, b) |
least-squares solution |
np.linalg.eig(A) / eigh |
eigenvalues and eigenvectors |
np.linalg.matrix_rank(A) |
rank |
Test yourself
What is the shape of np.ones((3, 2)) @ np.ones((2, 5))?
- (3, 5)
- (2, 2)
- (3, 2)
- An error
Which is the recommended way to solve A x = b?
- np.linalg.inv(A) * b
- np.linalg.solve(A, b)
- A / b
- b @ A
For 2-D arrays, what is the difference between A * B and A @ B?
- None
- * is element-wise, @ is the matrix product
- * is the matrix product, @ is element-wise
- @ only works for vectors