Sub topic 15
Matrix products with matmul and @
This chapter assumes you know the earlier material: shape and ndim, reshaping, elementwise operations, and the broadcasting rules. It covers matrix products, which look like broadcasting but follow different rules.
Elementwise product versus matrix product
The * operator multiplies elements in matching positions. The @ operator computes a matrix product, where each output entry is the sum of products of a row from the left operand and a column from the right operand.
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
print(A * B)
# [[ 5 12]
# [21 32]]
print(A @ B)
# [[19 22]
# [43 50]]The entry (A @ B)[0, 0] is 1*5 + 2*7 = 19. The @ operator calls np.matmul, so A @ B and np.matmul(A, B) give the same result. np.matmul is a universal function, so it also accepts out= and other ufunc arguments.
The shape rule
For two 2-D arrays, the inner dimensions must match. The outer dimensions form the result shape: (n, k) @ (k, m) gives (n, m).
import numpy as np
X = np.ones((3, 4)) # 3 samples, 4 features
W = np.ones((4, 2)) # 4 features, 2 outputs
Y = X @ W
print(Y.shape) # (3, 2)
print(Y[0]) # [4. 4.]Each output entry sums over the shared dimension k. That dimension disappears from the result, which is why a matrix product reduces rank information in a way broadcasting does not.
One-dimensional operands
A 1-D array is not a row or a column. matmul promotes it temporarily and then removes the added axis.
- A 1-D left operand of shape
(k,)is treated as(1, k). - A 1-D right operand of shape
(k,)is treated as(k, 1). - After the product, the added axis is dropped.
import numpy as np
M = np.arange(6).reshape(2, 3) # [[0 1 2], [3 4 5]]
v = np.array([1, 0, 2])
u = np.array([1, 2])
print(M @ v) # [ 4 13] shape (2,)
print(u @ M) # [ 6 9 12] shape (3,)
print(v @ v) # 5 inner productM @ v treats v as a column, so the result has shape (2,). It is not (2, 1). If a later step needs a column, add the axis yourself with Y[:, np.newaxis] or reshape(-1, 1).
Fixing shape mismatches
When the inner dimensions disagree, matmul raises a ValueError. The message names a mismatch in a core dimension. The exact wording varies between NumPy versions.
import numpy as np
P = np.ones((3, 4))
try:
P @ P # (3, 4) @ (3, 4): inner sizes 4 and 3
except ValueError as err:
print('ValueError:', err)
print((P @ P.T).shape) # (3, 3): (3, 4) @ (4, 3)The attribute .T swaps the axes of a 2-D array. It returns a view, so it costs no copy. For arrays with more than two axes, .T reverses all axes, which is rarely what you want. Use np.swapaxes(a, -1, -2) or np.moveaxis to transpose only the last two.
A common source of this error is a vector of shape (n,) where you expected a column. Compare shapes first, then decide whether you need a transpose or a reshape.
Stacks of matrices
When an operand has more than two axes, matmul treats the last two axes as the matrices. It treats the leading axes as a stack of matrices, called batch dimensions. The batch dimensions broadcast against each other using the same rules you learned earlier.
import numpy as np
A = np.arange(24).reshape(2, 3, 4) # a stack of two (3, 4) matrices
B = np.ones((4, 5)) # one (4, 5) matrix
print((A @ B).shape) # (2, 3, 5)
S = np.ones((2, 1, 3, 4)) # batch shape (2, 1)
T = np.ones((5, 4, 2)) # batch shape (5,)
print((S @ T).shape) # (2, 5, 3, 2)In the first case, B has no batch axes, so the same matrix multiplies every matrix in A. In the second case, the batch shapes (2, 1) and (5,) broadcast to (2, 5). Then each pair of (3, 4) and (4, 2) matrices produces a (3, 2) result.
Two separate checks apply:
- The last two axes must satisfy the inner-dimension rule.
- The batch axes must be broadcast-compatible.
A failure in either check raises a ValueError.
matmul versus np.dot
np.dot agrees with matmul for 1-D and 2-D operands. The two differ in other cases.
| Case | `np.matmul` / `@` | `np.dot` |
|---|---|---|
| Scalar operand | Raises `ValueError` | Multiplies elementwise |
| N-D with N > 2 | Treats leading axes as a broadcast stack | Sums over the last axis of `a` and the second-to-last axis of `b`, pairing every batch of `a` with every batch of `b` |
| Result shape for `(2,3,4)` and `(5,4,2)` | Error: batch sizes 2 and 5 do not broadcast | `(2, 3, 5, 2)` |
import numpy as np
a = np.ones((2, 3, 4))
b = np.ones((5, 4, 2))
print(np.dot(a, b).shape) # (2, 3, 5, 2)
try:
a @ b
except ValueError:
print('matmul: batch axes 2 and 5 do not broadcast')Prefer @ in new code. Its behavior for stacks matches how most people expect batched matrix products to work, and the operator makes formulas easier to read.
Using a matrix product in place of broadcasting
You can often write a computation either as a broadcast followed by a sum, or as a matrix product. The matrix product avoids building a large intermediate array. The pairwise distance example from the broadcasting chapter built a (3, 3, 2) array of differences. For n points with d coordinates, that array has n * n * d elements.
The identity |a - b|² = |a|² + |b|² - 2 a·b lets you compute the same distances from an (n, n) matrix of dot products.
import numpy as np
pts = np.array([[0.0, 0.0],
[3.0, 4.0],
[6.0, 8.0]])
sq = (pts ** 2).sum(axis=1) # shape (3,)
d2 = sq[:, np.newaxis] + sq[np.newaxis, :] - 2 * (pts @ pts.T)
dist = np.sqrt(np.clip(d2, 0.0, None))
print(dist)
# [[ 0. 5. 10.]
# [ 5. 0. 5.]
# [10. 5. 0.]]The np.clip call matters. Floating-point rounding can leave a tiny negative value in d2 where the true distance is zero, and np.sqrt of a negative number gives nan. The trade-off is that this form can lose precision when points are far from the origin and close to each other. The broadcast-difference form is slower in memory but numerically safer.
Dtype behavior
The result dtype follows the usual promotion rules. Two integer arrays give an integer result, and mixing an integer and a float array gives a float result. Integer matrix products use no wider type than the operands require, so small integer types can overflow without any warning.
import numpy as np
a = np.array([[100]], dtype=np.int8)
b = np.array([[2]], dtype=np.int8)
print(a @ b) # [[-56]] 200 wrapped around in int8
print(a.astype(np.int32) @ b.astype(np.int32)) # [[200]]Float products are also the case where NumPy calls an optimized BLAS library, so large float matrix products run much faster than integer ones of the same size. If speed matters and your values fit in float64 exactly, converting integer inputs to floats can help.
Common mistakes
- Using
*when you meant@, which gives wrong values without an error. - Passing a
(n,)vector where a(n, 1)column is needed, then getting(n,)back instead of(n, 1). - Using
.Ton arrays with three or more axes and reversing every axis. - Multiplying by a scalar with
@, which raises an error. Use*for scalars. - Expecting
np.dotand@to match for stacks of matrices.
Exercise
Array a has shape (8, 1, 5, 3) and array b has shape (6, 3, 2). What is the shape of a @ b, and which axes are the batch axes? What would change if b had shape (6, 4, 2)?
Show answer
The matrices are the last two axes: (5, 3) in a and (3, 2) in b. The inner sizes are both 3, so the product is valid and each matrix result has shape (5, 2). The batch shapes are (8, 1) and (6,), which broadcast to (8, 6). The result shape is (8, 6, 5, 2). If b had shape (6, 4, 2), the inner sizes would be 3 and 4, so matmul would raise a ValueError about a core dimension mismatch.
Exercise
You have a feature matrix X of shape (100, 3) and a weight vector w of shape (3,). Write the expression that gives one score per sample, state its shape, and say how to get the scores as a column of shape (100, 1).
Show answer
scores = X @ w has shape (100,), because w is treated as a column and the added axis is removed. To get a column, use scores[:, np.newaxis] or scores.reshape(-1, 1). Another option is X @ w[:, np.newaxis], which keeps the column axis and returns shape (100, 1) directly.