Math Fundamentals · lesson 05/15
Matrices
A matrix is a grid of numbers that acts as a linear function on vectors. When a layer says nn.Linear(768, 3072), it means a matrix with 3072 rows and 768 columns, and the forward pass is one matrix-vector product. Shapes and the multiplication rule are the whole game.
The idea
A matrix of shape maps a vector to a vector :
Two readings of that formula are equally useful:
- Rows — entry of the output is the dot product of row of with .
- Columns — the output is a weighted sum of the columns of , where the weights are the entries of .
Other essentials:
- Transpose swaps rows and columns; a symmetric matrix satisfies .
- Identity leaves every vector unchanged.
- Multiplication ; the inner dimensions must agree. It is associative but not commutative.
- Rank is the number of linearly independent columns. An matrix with must have rank at most , so it compresses information — you cannot recover from .
Worked example
Let and .
Row view: and , so .
Column view: . Same answer, and the column view explains why a zero in the input simply drops that column's contribution.
In code
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
x = np.array([1, 0, -1])
print(A.shape) # (2, 3)
print(A @ x) # [-2 -2]
print(A.T.shape) # (3, 2)
print(np.linalg.matrix_rank(A)) # 2@ also chains: (A @ B) @ x costs the same as A @ (B @ x) mathematically, but the parenthesization changes the intermediate shapes and therefore the runtime.
Check yourself
- What are the inner dimensions required for to be defined, and what shape is the result?
- Give two matrices with and compute both products.
- What does a rank-1 matrix do to an input space, and why does that matter for model capacity?
Key takeaways
- A matrix is a linear map; shapes record inputs and outputs.
- Matrix-vector multiplication is a dot product per row, or a weighted sum of columns.
- Rank counts independent directions and bounds how much information survives.