Sub topic 15
Matrix products with matmul and @
This chapter assumes you can read array shapes, reshape arrays, and apply the broadcasting rules from earlier chapters. It adds the one common operation that does not broadcast elementwise: the matrix product.
Elementwise product versus matrix product
The * operator multiplies elementwise. Its operands must have broadcast-compatible shapes. The @ operator, which calls np.matmul, computes the matrix product. Each output entry is the sum of products of one row of the left array with one column of the right array.
For two 2-D arrays, the inner dimensions must match:
- Left shape
(m, n) - Right shape
(n, p) - Result shape
(m, p)
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6]]) # shape (2, 3)
B = np.array([[1, 0],
[0, 1],
[2, 2]]) # shape (3, 2)
print(A @ B)
# [[ 7 8]
# [16 17]]
print((A @ B).shape) # (2, 2)
try:
A @ A # (2, 3) @ (2, 3): inner sizes 3 and 2
except ValueError:
print("shapes not aligned")The first entry is 1*1 + 2*0 + 3*2 = 7. The dimension n is summed away, so it does not appear in the result.
One-dimensional operands
A 1-D array is treated as a vector. NumPy temporarily adds a length-1 axis, does the product, then removes that axis:
- As the left operand, shape
(n,)becomes(1, n). - As the right operand, shape
(n,)becomes(n, 1).
v = np.array([1, 2, 3])
print(A @ v) # [14 32], shape (2,)
print(v @ v) # 14, the dot productThe result is a plain scalar only when both operands are 1-D.
Stacks of matrices
When an operand has more than two dimensions, NumPy treats the last two axes as the matrices. It treats the leading axes as a stack and broadcasts them using the usual rules. This lets you multiply many matrices in one call, with no Python loop.
batch = np.arange(30).reshape(5, 2, 3) # five (2, 3) matrices
print((batch @ B).shape) # (5, 2, 2)Here B has no stack axis, so it is reused for all five matrices.
Shape summary
| Left shape | Right shape | Result shape |
|---|---|---|
| `(m, n)` | `(n, p)` | `(m, p)` |
| `(m, n)` | `(n,)` | `(m,)` |
| `(n,)` | `(n, p)` | `(p,)` |
| `(n,)` | `(n,)` | `()` (scalar) |
| `(b, m, n)` | `(n, p)` | `(b, m, p)` |
| `(b, m, n)` | `(b, n, p)` | `(b, m, p)` |
Common errors
- Using
*when you mean@. Two square matrices multiply without error under*, but the result is elementwise and almost never what you want. With non-square shapes such as(2, 3) * (3, 2), you get a broadcastingValueErrorinstead. - Misaligned inner dimensions. The error names a "core dimension" mismatch. Check which axis is
non each side, then fix it with.T(transpose) orreshape. - Scalars.
@does not accept a scalar operand. Use*to scale an array. np.doton stacks. For arrays above 2-D,np.dotdoes not treat leading axes as a stack. Usematmulor@for batches.
Reshaping to make products line up
A 1-D result often needs an explicit axis before it works as a column or row. For example, v[:, np.newaxis] has shape (3, 1). Then A @ v[:, np.newaxis] has shape (2, 1), a column, where A @ v has shape (2,). Pick the form your next step expects.
Exercise
An array x has shape (4, 3, 2) and y has shape (2,). What is the shape of x @ y, and why?
Show answer
(4, 3). The 1-D right operand y is treated as (2, 1), so each (3, 2) matrix in x is multiplied by a (2, 1) column, giving (4, 3, 1). The added axis is then removed, leaving (4, 3).
Exercise
A has shape (5, 3). Write an expression using A and its transpose that gives a (5, 5) matrix of dot products between all pairs of rows.
Show answer
A @ A.T. The shapes are (5, 3) @ (3, 5), which gives (5, 5).