Sub topic 13
Matrix multiplication with @ and basic linear algebra
This chapter assumes you know shapes and ndim, elementwise arithmetic, and how axis and transposing work. It covers the @ operator and a few routines from np.linalg.
Elementwise versus matrix product
* multiplies matching elements. @ computes the matrix product, where each result entry is a row of the left array times a column of the right array, summed.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[0, 1], [1, 0]])
print(A @ B) # matrix product: [[2 1]
# [4 3]]
print(A * B) # elementwise product: [[0 2]
# [3 0]]np.matmul(A, B) is the function form of A @ B. np.dot gives the same result for 1-D and 2-D inputs, but @ is clearer and behaves more predictably with higher dimensions.
The shape rule
An inner dimension must match. A (m, n) array times an (n, p) array gives an (m, p) array. The two n values are summed away.
A 1-D operand is treated as a vector and its extra axis is dropped from the result.
import numpy as np
A = np.array([[1, 2], [3, 4]])
v = np.array([1, 1])
print(A @ v) # [3 7], shape (2,)
print(v @ v) # 2, a scalar inner product
try:
np.ones((2, 3)) @ np.ones((2, 3))
except ValueError as err:
print(type(err).__name__) # ValueErrorSolving and inspecting with np.linalg
The np.linalg module holds common routines. To solve A x = b, use np.linalg.solve.
import numpy as np
A = np.array([[3.0, 1.0], [1.0, 2.0]])
b = np.array([9.0, 8.0])
x = np.linalg.solve(A, b)
print(x) # [2. 3.]
print(np.allclose(A @ x, b)) # True
print(np.linalg.det(A)) # about 5.0
print(np.linalg.norm(b)) # Euclidean length of b
print(np.linalg.inv(A) @ b) # same answer, but less preferredOther routines you will meet are np.linalg.eig for eigenvalues and np.linalg.svd for the singular value decomposition. They follow the same pattern of arrays in and arrays out.
Common errors
- Using
*when you meant@. Square arrays of the same shape raise no error, so the wrong answer goes unnoticed. - Comparing floating-point results with
==. Usenp.allclose, because rounding makes results differ in the last digits. - Calling
invto solve a system.solveis faster and more accurate, especially when the matrix is nearly singular. - Expecting
@to work with scalars.2 @ Araises an error, so use2 * A. - Forgetting that a 1-D array has no row or column orientation.
v.Tleavesvunchanged.
Exercise
Let M have shape (4, 3) and w have shape (3,). What is the shape of M @ w? What does M.T @ M give in terms of shape, and why does w @ M fail?
Show answer
M @ w has shape (4,), because the inner dimension 3 matches and is summed away. M.T has shape (3, 4), so M.T @ M is (3, 4) @ (4, 3) and gives shape (3, 3). The product w @ M fails because w has length 3 and M's first axis has length 4. The inner dimensions do not match, so NumPy raises ValueError.