Understanding numpy.matmul() — Matrix Multiplication Made Simple 🔢
One operation powers every neural-network layer, recommendation system, and image transform. Here’s exactly what it does — visually and correctly.
A @ B → Result
Matrix A
[ 3 4 ]
Matrix B
[ 7 8 ]
Matrix C
[ 43 50 ]
1. Row × Column — the core idea
Take first row of A and first column of B:
[ 7 ]
(1 × 5) + (2 × 7) = 5 + 14 = 19
→ This becomes C[0,0] = 19
2. Next cell (same pattern)
Same row of A × second column of B:
→ C[0,1] = 22 | Repeat for every output cell
3. The Shape Rule (must remember)
(m × n) @ (n × p) → (m × p)
Inner dimensions must match. Outer dimensions become the result shape.
✓ (2 × 3) @ (3 × 4) → (2 × 4)
✗ (2 × 3) @ (2 × 4) → shape error
4. NumPy syntax
C = np.matmul(A, B)
C = A @ B # preferred modern form
@ is NumPy’s matrix-multiplication operator (Python 3.5+)
5. matmul ≠ element-wise multiply
Matrix multiplication
np.matmul(A, B) or A @ B
row × column → sum → one cell
[[19 22]
[43 50]]
Element-wise
A * B
matching positions multiply
[[ 5 12]
[21 32]]
Completely different results!
6. Quick memory cards
Matrix multiplication
Core calculation
Must match
Outer dimensions
A @ B → take a row → take a column → multiply + add → fill one output cell
That is the entire mechanism. Once you see “row × column → one cell”, every matmul call in NumPy (and in every neural network) becomes transparent.
Comments
Post a Comment