Sub topic 13
Matrix multiplication with @ and basic linear algebra
This chapter covers the @ operator, how it differs from elementwise *, and the shape rules that decide whether a product is defined. It also covers a few functions from np.linalg. It assumes you know what shape, ndim, and dtype mean, and that you have seen broadcasting. You should also know what a matrix product is on paper: row times column, summed.
Elementwise versus matrix product
The * operator multiplies arrays element by element, and broadcasting applies. The @ operator computes the matrix product. The two give different results on the same inputs.
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]]Entry (i, j) of A @ B is the sum over k of A[i, k] * B[k, j]. For the top-left entry that is 1*0 + 2*1 = 2.
The shape rule
A product of an (m, n) array and an (n, p) array has shape (m, p). The two inner sizes must match, and they disappear from the result.
import numpy as np
X = np.ones((4, 3)) # 4 samples, 3 features
W = np.ones((3, 2)) # 3 features, 2 outputs
print((X @ W).shape) # (4, 2)
try:
X @ X # (4, 3) @ (4, 3): inner sizes 3 and 4 differ
except ValueError as err:
print("ValueError:", type(err).__name__)When you hit this error, print both shapes first. The usual fix is a transpose (X @ X.T is (4, 3) @ (3, 4), which gives (4, 4)), not a reshape. Reshaping to force the sizes to agree produces a result that runs but is mathematically wrong.
One-dimensional operands
NumPy does not distinguish row vectors from column vectors when an array is 1-D. @ follows these rules:
- Two 1-D arrays give the dot product, a scalar.
- A 2-D array and a 1-D array treat the 1-D array as a vector. The result is 1-D.
- If the first operand is 1-D, NumPy temporarily prepends a length-1 axis to it, multiplies, and then removes that axis.
- If the second operand is 1-D, NumPy temporarily appends a length-1 axis and removes it afterward.
import numpy as np
v = np.array([1, 2, 3])
w = np.array([4, 5, 6])
M = np.array([[1, 0, 0],
[0, 2, 0]]) # shape (2, 3)
print(v @ w) # 32, because 1*4 + 2*5 + 3*6
print(M @ v) # [1 4], shape (2,)
print(v @ M.T) # [1 4], (3,) @ (3, 2) gives (2,)A 1-D result means you never need to call .reshape(-1, 1) just to multiply a matrix by a vector. If you do want a column result with shape (2, 1), give the vector a column shape first: M @ v.reshape(3, 1).
Batches of matrices
If either operand has more than two dimensions, @ treats the last two axes as the matrices and the leading axes as a stack. The leading axes broadcast against each other, using the rules you already know.
import numpy as np
stack = np.arange(24).reshape(2, 3, 4) # two (3, 4) matrices
other = np.ones((4, 2)) # one (4, 2) matrix
print((stack @ other).shape) # (2, 3, 2)Here other is 2-D, so it is reused for every matrix in the stack. This is how you apply one weight matrix to a whole batch without a Python loop.
@ versus np.dot and np.matmul
A @ B calls np.matmul(A, B). The older np.dot agrees with it for 1-D and 2-D inputs but differs in two ways:
| Case | `@` / `np.matmul` | `np.dot` |
|---|---|---|
| Scalar operand | Raises `ValueError` | Multiplies elementwise |
| N-D with N > 2 | Stack of matrix products, leading axes broadcast | Sum product over last axis of first and second-to-last of second, a different and less intuitive result |
Prefer @ in new code. For a scalar, write 2 * A.
Types and speed
Matrix products of floating-point arrays are handed to an optimized BLAS library, which makes them much faster than any Python loop. Integer arrays are multiplied by a plain compiled loop without BLAS, so large integer products are slower. Mixing dtypes upcasts, as in other operations: int64 @ float64 gives float64.
Integer products also wrap around silently on overflow. If your entries are large, convert to floats first with astype(np.float64).
Basic linear algebra with np.linalg
The numpy.linalg module provides the common operations. The examples below use a small system of equations: 3x + y = 9 and x + 2y = 8.
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(np.round(x, 10)) # [2. 3.]
print(np.allclose(A @ x, b)) # True
print(round(np.linalg.det(A), 6)) # 5.0
Ainv = np.linalg.inv(A)
print(np.round(Ainv, 2)) # [[ 0.4 -0.2]
# [-0.2 0.6]]
print(np.allclose(A @ Ainv, np.eye(2))) # True
print(np.linalg.norm(np.array([3.0, 4.0]))) # 5.0Useful functions:
np.linalg.solve(A, b)solvesA x = bfor a squareA.np.linalg.inv(A)returns the inverse.np.linalg.det(A)returns the determinant.np.linalg.norm(v)returns the Euclidean length of a vector, or the Frobenius norm of a matrix by default.np.eye(n)builds an identity matrix, andA.Tgives the transpose as a view.np.outer(u, v)returns the outer product of two vectors, with shape(len(u), len(v)).
Prefer solve to inv
To compute x in A x = b, call solve and do not compute np.linalg.inv(A) @ b. solve is faster and numerically more accurate, because it never forms the full inverse. Reserve inv for cases where you need the inverse itself.
Floating-point comparisons
Results from linear algebra carry rounding error, so A @ Ainv == np.eye(2) can be False even when the math is right. Compare with np.allclose(a, b), which uses a tolerance.
Singular matrices
A matrix whose rows are linearly dependent has no inverse. NumPy raises an error instead of returning nonsense:
import numpy as np
S = np.array([[1.0, 2.0],
[2.0, 4.0]]) # second row is twice the first
try:
np.linalg.inv(S)
except np.linalg.LinAlgError as err:
print("LinAlgError:", err) # LinAlgError: Singular matrixA matrix that is nearly singular does not raise an error. It returns an inverse with huge values and low accuracy. np.linalg.cond(A) returns the condition number, and a very large value (for example, above 1e10) warns you that results are unreliable.
Common mistakes
- Using
*when you meant@. Square arrays of the same shape run without error, so the bug is silent. - Reshaping to silence a shape error instead of checking whether a transpose is what the math requires.
- Expecting a 1-D vector to behave as a column.
v @ vis a scalar, andnp.outer(v, v)is the matrix you may have wanted. - Comparing float results with
==. - Inverting a matrix to solve a system.
Exercise
A has shape (5, 3), B has shape (3,), and C has shape (2, 5, 3). What are the shapes of A @ B, C @ B, and A.T @ A? Which one of A @ A, B @ A, and C @ A raises an error, and why?
Show answer
A @ B has shape (5,). C @ B has shape (2, 5), because B is a vector applied to each of the two (5, 3) matrices. A.T @ A is (3, 5) @ (5, 3), so its shape is (3, 3). All three of A @ A, B @ A, and C @ A fail. A @ A is (5, 3) @ (5, 3), where 3 does not equal 5. B @ A is (3,) @ (5, 3), where the vector's length 3 does not equal A's first axis, 5. C @ A is (2, 5, 3) @ (5, 3), where the last two axes of C, (5, 3), need the inner sizes 3 and 5 to match, and they do not.
Exercise
Write code that solves 2x + y = 5 and x - y = 1 with NumPy, then checks the answer with a tolerance-based comparison.
Show answer
import numpy as np A = np.array([[2.0, 1.0], [1.0, -1.0]]) b = np.array([5.0, 1.0]) x = np.linalg.solve(A, b) print(x) # [2. 1.] print(np.allclose(A @ x, b)) # True